![](/img/trans.png)
[英]What is the proper way to exit a WinForms application from static void Main() entry point
[英]What's the proper way to exit the application from WindowsFormsApplicationBase.OnCreateMainForm()?
让我们假设WindowsFormsApplicationBase.OnCreateMainForm()
出了点问题,如何从应用程序“轻轻地”退出? 我想像使用时一样按下退出按钮退出,所以我猜Environment.Exit()
不太适合,因为它会立即终止应用程序,并且可能不允许应用程序自行清理。
我的代码如下所示:
public class MyApp : WindowsFormsApplicationBase
{
public MyApp()
{
this.IsSingleInstance = true;
}
protected override void OnCreateSplashScreen()
{
this.SplashScreen = new splashForm();
}
protected override void OnCreateMainForm()
{
if(!do_something()) {
/* something got wrong, how do I exit application here? */
}
this.MainForm = new Form1(arg);
}
和我的Main()
函数:
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
new MyApp().Run(args);
}
我通过创建一个空窗体来立即解决该问题,该窗体立即在load事件处理程序中自行关闭。 这样可以避免NoStartupFormException
public partial class SelfClosingForm : Form
{
public SelfClosingForm()
{
InitializeComponent();
}
private void SelfClosingForm_Load(object sender, EventArgs e)
{
Close();
}
}
protected override void OnCreateMainForm()
{
...
if (error)
{
//this is need to avoid the app hard crashing with NoStartupFormException
this.MainForm = new SelfClosingForm();
return;
}
...
只需使用return
:
protected override void OnCreateMainForm()
{
if(!do_something())
{
return;
}
// This won't be executed if '!do_something()' is true.
this.MainForm = new Form1(arg);
}
这将退出当前线程,因此不会设置MainForm
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.