Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

End Program After MessageBox is Closed

At the very beginning of my program, I am checking to see if I can initiate a connection with a device on COM6. If the device is not found, then I want to display a MessageBox and then completely end the program.

Here's what I have so far in the Main() function of the initial program:

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

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

When I try putting a Application.Exit(); after the MessageBox command, the MessageBox displays correctly when no device is detected, but when I close the MessageBox, Form1 still opens, but is completely frozen and won't let me close it or click any of the buttons that should give me an error anyways since the device is not connected.

I am just looking for away to kill the program completely after the MessageBox is displayed. Thanks.

SOLUTION: After using the return; method after the MessageBox closed the program quit just as I wanted when the device was not plugged it. However, when the device was plugged in, it still had issues reading after to test. This was something I hadn't discovered before, but it was a simple fix. Here is my fully working code:

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());
like image 841
Jacob Varner Avatar asked Jun 20 '13 19:06

Jacob Varner


1 Answers

Application.Exit tells your WinForms application to stop the message pump, therefore exiting the program. If you call it before you call Application.Run, the message pump never got to start in the first place, so it freezes.

If you want to terminate your program, no matter what state it is in, use Environment.Exit.

like image 85
Jan Dörrenhaus Avatar answered Oct 02 '22 22:10

Jan Dörrenhaus