Search code examples
c#winformsmessagebox

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());

Solution

  • Since this is in the Main() routine, just return:

    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..
    

    Returning from Main() will exit the process.