- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我的 C# 应用程序中有 3 个表单——Form1、Form2 和 Form3。目前,当我的应用程序启动时,它会加载 Form1。我希望所有三种形式都在应用程序启动时打开。
我尝试在 Program.cs
中这样做:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
Application.Run(new Form2());
}
但是Form2只有在Form1关闭后才会出现。
如何让所有 3 个表单在应用程序启动时同时显示?
最佳答案
通常,让您的应用程序执行默认操作以外的操作(打开一个表单,等待它关闭,然后退出)的正确方法是创建一个继承自 ApplicationContext
的类。然后将您的类的一个实例传递给 Application.Run
方法。当应用程序应该关闭时,从您的类中调用 ExitThread()
。
在这种情况下,您可以在应用程序加载时创建三种形式的实例,并为它们的 Closed
事件注册一个处理程序。当每个表单关闭时,处理程序将检查是否还有任何其他表单仍然打开,如果没有则关闭应用程序。
The example on MSDN 做了两件事:
一个更简单的示例,仅在所有表单关闭后才关闭应用程序:
class MyApplicationContext : ApplicationContext {
private void onFormClosed(object sender, EventArgs e) {
if (Application.OpenForms.Count == 0) {
ExitThread();
}
}
public MyApplicationContext() {
//If WinForms exposed a global event that fires whenever a new Form is created,
//we could use that event to register for the form's `FormClosed` event.
//Without such a global event, we have to register each Form when it is created
//This means that any forms created outside of the ApplicationContext will not prevent the
//application close.
var forms = new List<Form>() {
new Form1(),
new Form2(),
new Form3()
};
foreach (var form in forms) {
form.FormClosed += onFormClosed;
}
//to show all the forms on start
//can be included in the previous foreach
foreach (var form in forms) {
form.Show();
}
//to show only the first form on start
//forms[0].Show();
}
}
然后,您的 Program
类如下所示:
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyApplicationContext());
}
}
应用程序关闭逻辑显然可以定制 - 任何表单是否仍然打开,或者只有这三种类型中的一种,或者只有前三个实例(这需要持有对前三个实例的引用,可能在 List<Form>
中) .
回复:每个表单创建的全局事件——this 看起来很有希望。
类似的例子 here 。
关于c# - C#应用程序启动时显示多个窗体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13406077/
对于一个科学实验,我写了一个turtle.py ,它会打开一个 800x480 的窗口并绘制一个缓慢增长的黑点。 turtle.py以 C:\Users\kaza>python C:\Users\ka
我开发了一个 swing 应用程序,但每次运行应用程序时都会打开一个新窗口。我希望如果一个窗口已经打开,则其他窗口不允许打开。 最佳答案 Here是一个 Java 单一应用实例的例子: A singl
有没有办法检测主进程中 Electron 的结构? process.platform 似乎也在 x64 机器上返回 win32,我没有在文档中找到任何获取架构的选项。 最佳答案 你试过 process
public short[] HanningWindow(short[] signal_in ,int pos ,int size) { for (int i= pos; i < pos+si
我有一个具有这些属性的 Electron 窗口: mainWindow = new BrowserWindow({ width: 800, height: 600, title: "Aqu
我有一个 Ubuntu 工作站,我正在尝试引导一个 Windows 节点。 Windows 节点在端口 2222 上打开了 ssh。我一直在关注 http://docs.opscode.com/plu
我是一名优秀的程序员,十分优秀!