你如何在C#中打开一个新窗口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9457651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you open a new window in C#
提问by Joshua
I am creating a Kinect application and want to open a new window called 'Help' from the 'MainWindow.xaml.cs' file.
我正在创建一个 Kinect 应用程序,并希望从“MainWindow.xaml.cs”文件中打开一个名为“Help”的新窗口。
I tried using the following code:
我尝试使用以下代码:
// The commented code is what I have tried.
public static void ThreadProc()
{
// Window Help = new Window();
//Application.Run(new Window(Help);
Application.Run(new Form());
}
private void button1_Click(object sender, EventArgs e)
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
t.Start();
}
采纳答案by Drew Noakes
Showing a window just requires a call to its Showmethod.
显示一个窗口只需要调用它的Show方法。
However, keeping an application running requires a call to Application.Run. If you pass this method a form, it'll call Showfor you.
但是,保持应用程序运行需要调用Application.Run. 如果您将此方法传递给表单,它会Show为您打电话。
However, if you already have a running application, you can just do something like new MyForm().Show().
但是,如果您已经有一个正在运行的应用程序,则可以执行类似new MyForm().Show().
I strongly suspect you don't need to create a new thread and Applicationfor your new window. Can't you just use:
我强烈怀疑您不需要Application为新窗口创建新线程。你不能只使用:
private void button1_Click(object sender, EventArgs e)
{
new Form().Show();
}
回答by H.B.
I don't understand why you run the application there but usually you open a window by creating an instance and showingit.
我不明白你为什么在那里运行应用程序,但通常你通过创建一个实例并显示它来打开一个窗口。
var window = new Help(); // Help being the help window class
window.Show();
Also as this on the background thread it may cause trouble in terms of inter-control communication. Usually you will want to create and access UI-elements on the UI thread only. To move any operation to the UI-thread you can use the Dispatcherof the UI-thread. See also: Threading Model
同样在后台线程上,它可能会导致控制间通信方面的麻烦。通常,您只想在 UI 线程上创建和访问 UI 元素。要将任何操作移动到 UI 线程,您可以使用DispatcherUI 线程的 。另见: 线程模型
回答by Tigran
If you need your own, just add to the project a new form, or create your own from the stratch and call
如果您需要自己的表单,只需在项目中添加一个新表单,或者从stratch 中创建您自己的表单并调用
myForm.Show()
回答by Pruthvi Shrikaanth
Type this code to create and show a new window:
键入此代码以创建并显示一个新窗口:
//When I type Application1, that is the name of your application
...
Window Application1 = new Window();
Application1.Show;
...
Your welcome in advance!
提前欢迎您!

