当我的程序的自动生成代码启动时,它会调用
Application.Run(new Form1());
并启动Form1。我有另一种形式,我想同时切换到并关闭Form1。问题是如果我在使用“Form.ShowDialog()”调用另一个表单之前在Form1中使用“this.Close()”,则程序结束。如果我把它放在ShowDialog之后,那么它将保持在后台,直到我关闭Form2,此时程序结束。
如何在同时关闭当前打开的帧的同时生成Frame2的副本?
编辑:我也试过用.Show()调用Frame2,但新框架立即关闭。
答案 0 :(得分:7)
以下解决方案可以按预期工作。
要尝试此示例代码,请在Visual Studio中创建一个新的WinForms应用程序(即File - > New Project,选择Visual C# - > Windows Classic Desktop并使用模板“Windows Forms App(.NET Framework) “),然后添加第二个表格。
确保将两个表单命名为Form1
和Form2
,然后按如下方式修改生成的解决方案中的代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.FormClosed +=
new System.Windows.Forms.FormClosedEventHandler(this.Form1_FormClosed);
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
(new Form2()).Show();
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
this.FormClosed +=
new System.Windows.Forms.FormClosedEventHandler(this.Form2_FormClosed);
}
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
}
这是应用程序的入口点,修改如下:
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Show first form and start the message loop
(new Form1()).Show();
Application.Run(); // needed, otherwise app closes immediately
}
}
诀窍是在没有参数的情况下使用Application.Run(),在要退出应用程序的位置使用Application.Exit()。
现在,当您运行应用程序时,Form1
会打开。点击 X (右上角),Form1关闭,但会显示Form2
。再次单击 X ,表单将关闭。
您可以创建一个执行作业的按钮,而不是将Form2
的启动放入FormClosed事件中,但是在这种情况下,不要忘记通过{关闭按钮所属的表单{明确地{1}}:
this.Close()
答案 1 :(得分:5)
你需要调用this.Hide()
使其不可见但仍然打开,而不是关闭它的this.Close()
(并且看到它是应用程序的主要形式,也关闭了应用程序)。 / p>
答案 2 :(得分:1)
在同一个谷歌上找到了这个问题和一个codeproject。
作者基本上创建了一个顶级表单,用于管理他想要显示的表单之间的切换。