在我的程序一开始,我会检查是否能够与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());