打开一个新窗体,关闭旧窗体 C#
我对 C# 有点陌生,我正在自学,尝试制作一个具有多种功能的程序来教自己如何使用 C#。如果我不知道什么,我通常会上网查看,但这让我发疯。
我记得一开始我开始这个,我想打开一个表单并关闭旧的表单,但是当我关闭新的表单时,旧的表单会再次出现,以及这个问题的其他奇怪的变体。 this.Hide() 似乎也没有做任何事情。
目前,为了打开一个新表单,我正在使用这段代码,但感觉应该有 1 行代码来完成像打开表单这样简单的事情...... 我的问题是是否有。
private void OpenMainForm()
{
MainForm frm2 = new MainForm();
frm2.FormClosed += new FormClosedEventHandler(frm2_FormClosed);
frm2.Show();
// Since this.Hide() for some reason doesn't work, i'll have to do this crap
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
}
private void frm2_FormClosed(object sender, FormClosedEventArgs e)
{
this.Close();
}
I'm kinda new to C# and I'm doing self study by trying to make a program with a variety of functions to teach myself how to work with C#. I usually look at the internet if I don't know something but this has been driving me crazy.
I remember in the very beginning i started this that I wanted to open a form and close the old one, but when i closed the new form, the old form would reappear again, and other weird varieties of this issue. this.Hide() didn't seem to do anything either.
Currently for opening a new form I'm using this code, but it feels like there should be something with 1 line of code for something as simple as opening a form...
My question is if there is.
private void OpenMainForm()
{
MainForm frm2 = new MainForm();
frm2.FormClosed += new FormClosedEventHandler(frm2_FormClosed);
frm2.Show();
// Since this.Hide() for some reason doesn't work, i'll have to do this crap
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
}
private void frm2_FormClosed(object sender, FormClosedEventArgs e)
{
this.Close();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您想在辅助窗口中隐藏主窗口,则应使用
ShowDialog()
方法。这样,您甚至不需要form_close 事件
。您的代码应如下所示:
If you want to hide your main window when you're in the secondary one, you should use the
ShowDialog()
method. With that, you won't even need theform_closed event
.Your code should look like:
您还可以使用此代码:
You can also use this code:
这对我来说非常适合,
但如果你想从 Form2 关闭整个应用程序...你必须在 Form2 的
FormClosing
事件中添加Application.Exit();
This works perfectly for me
but if you want to close the whole application from Form2...you have to add
Application.Exit();
inFormClosing
event of Form2您可以隐藏旧表单,如下所示。
You can hide old form as below.