关闭MessageBox后结束程序

6

在我的程序一开始,我会检查是否能够与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命令后放置一个时,当没有检测到设备时,MessageBox会正确显示,但是当我关闭MessageBox时,Form1仍然打开,但完全冻结,不会让我关闭它或单击任何应该给我错误的按钮,因为设备未连接。
我只是想找到一种方法,在显示MessageBox后完全终止程序。谢谢。
解决方案:在MessageBox关闭后使用方法,程序退出就像我想要的那样,当设备未插入时。然而,当设备插入后,它仍然存在读取问题进行测试。这是我之前没有发现的事情,但这是一个简单的修复。这是我的完整工作代码:
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());
4个回答

7

Application.Exit 告诉你的 WinForms 应用程序停止消息泵,从而退出程序。如果在调用 Application.Run 之前调用它,则消息泵根本没有启动,因此会冻结。

如果您想无论应用程序处于什么状态都要终止它,请使用 Environment.Exit


也许这不是我现在需要的,但对于我未来可能遇到的问题很有用。我一直在寻找那种“全部杀死”的代码。 - Jacob Varner

6

由于这是在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()函数返回将退出进程。


那很简单。不过还是谢谢你的帮助。 - Jacob Varner
这个答案应该更详细地解释为什么Application.Exit()没有像Jan Doerrenhaus所解释的那样起作用。 - King King

2
在顶部添加一个布尔类型的变量以确定操作是否已完成。
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语句后没有代码,所以当布尔值为假时程序将直接关闭。
你可以将这种逻辑应用到代码的任何其他部分,而不仅仅是Main()函数。

这对我最初想要的功能很有效,但现在当设备插入时程序无法运行。我会再试一下,但感谢您帮我修复最初的问题。 - Jacob Varner

0

在你的消息框代码后面加上Application.Exit()即可。
catch
{
MessageBox.Show("未检测到设备", MessageBoxButtons.OK, MessageBoxIcon.Error")
Application.Exit();
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接