C# 中表单之间的切换
当我的程序自动生成的代码启动时,它会调用
Application.Run(new Form1());
并启动 Form1
。我想同时切换到另一个表单并关闭 Form1
。问题是,如果我在使用 Form.ShowDialog()
调用另一个表单之前在 Form1
中使用 this.Close()
,那么程序就会结束。如果我把它放在 ShowDialog
之后,那么它会保留在后台,直到我关闭 Form2
,此时程序结束。
如何在关闭当前打开的框架的同时生成 Form2
的副本?
编辑:我也尝试使用 .Show()
调用 Form2
,但新框架立即关闭。
When the autogenerated code for my program starts, it calls
Application.Run(new Form1());
and starts Form1
. I have another form I'd like to switch to and close Form1
at the same time. The problem is if I use this.Close()
in Form1
before I call the other form with Form.ShowDialog()
then the program ends. If I put it after ShowDialog
then it remains up in the background until I close Form2
, at which point the program ends.
How can I spawn a copy of Form2
while closing the currently opened frame at the same time?
Edit: I have tried calling Form2
with .Show()
as well, but the new frame closes instantly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下解决方案将按您的预期工作。
要尝试此示例代码,请在 Visual Studio 中创建一个新的 WinForms 应用程序(即文件 --> 新建项目,选择 Visual C# --> Windows 经典桌面并使用模板“Windows Forms App (.NET Framework)”),然后添加第二个nd表单。
确保两个表单分别命名为
Form1
和Form2
,然后在生成的解决方案中修改代码如下:这是应用程序的入口点,修改如下:
技巧是在要退出应用程序的位置使用不带参数的 Application.Run() 和 Application.Exit() 。
现在,当您运行应用程序时,
Form1
将打开。单击 X(右上角),Form1 将关闭,但会出现Form2
。再次单击X,表单将关闭(并退出应用程序)。您也可以创建一个按钮 Button1 来完成这项工作,而不是将
Form2
的启动放入 FormClosed 事件中,但在这种情况下,不要忘记关闭表单通过this.Close()
明确按钮所属的按钮:The following solution works as you expect.
To try this sample code, create a new WinForms application in Visual Studio (i.e. File --> New Project, select Visual C# --> Windows Classic Desktop and use the template "Windows Forms App (.NET Framework)"), then add a 2nd form.
Ensure the two forms are named as
Form1
andForm2
, then modify the code in the generated solution as follows:And this is the entry point of the application, modify it as follows:
The trick is to use Application.Run() without parameters and Application.Exit() at the point where you want to exit the application.
Now when you run the application,
Form1
opens up. Click on the X (upper right corner) and Form1 closes, butForm2
appears instead. Click on the X again and the form closes (and exits the application too).Instead of placing the launch of
Form2
into the FormClosed event, you could also create a button Button1 which does the job, but in that case don't forget to close the form to which the button belongs to viathis.Close()
explicitly:您需要调用
this.Hide()
使其不可见但仍然打开,而不是this.Close()
关闭它(并且看到它是主窗体的应用程序,也关闭该应用程序)。You need to call
this.Hide()
which makes it invisible but still open, instead ofthis.Close()
which closes it (and seeing as it is the main form of the application, closes the application too).发现这个问题和codeproject在同一谷歌。
作者基本上创建了一个顶级表单来管理他想要显示的表单之间的切换。
Found this question and a codeproject on the same google.
The author basically creates a top-level form that manages switching between the forms he wants to show.