【问题标题】:End Program After MessageBox is ClosedMessageBox 关闭后结束程序
【发布时间】:2013-06-20 19:26:30
【问题描述】:

在我的程序的最开始,我正在检查是否可以启动与 COM6 上的设备的连接。如果没有找到设备,那么我想显示一个MessageBox,然后完全结束程序。

这是我到目前为止在初始程序的Main() 函数中的内容:

try
{
    reader = new Reader("COM6");
}
catch
{
    MessageBox.Show("No Device Detected", MessageBoxButtons.OK, MessageBoxIcon.Error)
}

Application.EnableVisualStyles();
Application.SetCompatibleRenderingDefault(false);
Application.Run(new Form1());

当我尝试在 MessageBox 命令后放置 Application.Exit(); 时,如果未检测到设备,MessageBox 会正确显示,但是当我关闭 MessageBox 时,Form1 仍然打开,但完全冻结,不会让我关闭它或由于设备未连接,请单击任何应该给我错误的按钮。

我只是想在显示 MessageBox 后完全杀死程序。谢谢。

解决方案: 在MessageBox 关闭后使用return; 方法后,程序在未插入设备时按我想要的方式退出。但是,当设备插入时,在测试后仍然存在读取问题。这是我以前没有发现的,但这是一个简单的修复。这是我的完整工作代码:

try
{
    test = new Reader("COM6");
    test.Dispose(); //Had to dispose so that I could connect later in the program. Simple fix.
}
catch
{
    MessageBox.Show("No device was detected", MessageBoxButtons.OK, MessageBoxIcon.Error)
    return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());

【问题讨论】:

    标签: c# winforms messagebox


    【解决方案1】:

    Application.Exit 告诉您的 WinForms 应用程序停止消息泵,从而退出程序。如果在调用 Application.Run 之前调用它,消息泵一开始就不会启动,所以它会冻结。

    如果你想终止你的程序,不管它处于什么状态,使用Environment.Exit

    【讨论】:

    • 可能不是我在这里需要的,但这对于了解我将来可能遇到的问题很有用。我一直在寻找那种“杀死所有”的代码。
    【解决方案2】:

    因为这是在Main() 例程中,所以只需返回:

    try
    {
        reader = new Reader("COM6");
    }
    catch
    {
        MessageBox.Show("No Device Detected", MessageBoxButtons.OK, MessageBoxIcon.Error)
        return; // Will exit the program
    }
    
    Application.EnableVisualStyles();
    //... Other code here..
    

    Main()返回将退出进程。

    【讨论】:

    • 这很简单。不过感谢您的帮助。
    • 这个答案应该添加更多解释为什么Application.Exit()没有像Jan Doerrenhaus解释的那样工作
    【解决方案3】:

    在顶部添加boolean 以确定操作是否完成。

    bool readerCompleted = false;
    try
    {
        reader = new Reader("COM6");
        readerCompleted = true;
    }
    catch
    {
        MessageBox.Show("No Device Detected", MessageBoxButtons.OK, MessageBoxIcon.Error)
    }
    
    if(readerCompleted)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleRenderingDefault(false);
        Application.Run(new Form1());
    }
    

    因为if语句后面没有代码,所以当布尔值为false时程序将关闭。

    您可以将这种逻辑应用到代码的任何其他部分,而不仅仅是 Main() 函数。

    【讨论】:

    • 这对我最初想要的有用,但现在当设备插入时程序将无法运行。我会玩一点,但感谢帮助我修复原版问题。
    【解决方案4】:

    您可以将 Application.Exit() 放在消息框代码之后
    catch
    {
    MessageBox.Show("No Device Detected", MessageBoxButtons.OK, MessageBoxIcon.Error")
    Application.Exit();
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      相关资源
      最近更新 更多