在构造函数中的 MessageBox 调用上退出应用程序 [英] Exiting application on MessageBox call in constructor

查看:30
本文介绍了在构造函数中的 MessageBox 调用上退出应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在实际表单之前显示一个对话框(消息框),如果用户选择否,应用程序应该完全关闭.我正在尝试使用下面的代码,但即使单击否",表单也会显示!

I want to show a dialog (message box) before the actual form, and if user selects no, the application should completly be closed. I am trying to use the code below, but even after clicking on No the form will be shown!

public Form1()
{
    InitializeComponent();

    if (MessageBox.Show("Contiue or not", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.None, MessageBoxDefaultButton.Button1) == DialogResult.No)
        Application.Exit();
}

我也尝试过 this.Clsoe 但后来我对 Application.Run()

I also tried this.Clsoe but then I have an exepction on Application.Run()

有什么问题?知道这样做的最佳方法是什么吗?

What is the problem? Any idea what would be the best approach for doing so?

推荐答案

OnLoad 事件而不是构造函数中显示您的消息框,例如:

Show your messagebox in the OnLoad event instead of the constructor e.g.:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    if (MessageBox.Show("Contiue or not", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.None, MessageBoxDefaultButton.Button1) == DialogResult.No)
    {
        Application.Exit(); // or this.Close();
    }
}

Application.Exit() 在构造函数中不起作用,因为还没有任何表单,因此,没有消息泵可以停止.
另外 this.Close() 会引发错误,因为它会导致对表单的 Dispose() 的调用;在 Application.Run 之后立即尝试显示表单,但它已被处理并引发异常.

Application.Exit() doesn't work in the constructor because there isn't any form yet, so, no message pump to stop.
Also this.Close() raises an error because it causes the call of Dispose() on the form; immediately after Application.Run try to show up the form, but it is disposed and it throws an exception.

这篇关于在构造函数中的 MessageBox 调用上退出应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆