Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close winforms application with mainform hidden

I am trying to close my winforms application through the Form.Closing event, with a custom message (Do you want to exit yes/no). For this I have edited the onFormClosing event for every form in my c# project. Like so:

protected override void OnFormClosing(FormClosingEventArgs e)
{
    base.OnFormClosing(e);

    if (e.CloseReason == CloseReason.WindowsShutDown) return;

    // Confirm user wants to close
    switch (MessageBox.Show(this, "Are you sure you want to close?", "Closing", MessageBoxButtons.YesNo))
    {
    case DialogResult.No:
        e.Cancel = true;
        break;
    default:
        break;
    }        
}

When the user clicks Yes, I want to get the entire application to exit. However, I have a main form which functions as a loginform. When the user logs in, the mainform gets hidden and a different form displays.

So when the user clicks Yes, the entire application does not end, because of that hidden form. How can I make sure that the entire application gets shut down?

I have tried Application.Exit(), this fires the messagebox confirming the shutdown again, because it calls the OnFormClosing event.

like image 722
Matthijs Avatar asked Dec 23 '13 18:12

Matthijs


2 Answers

You can explicitly handle Application.Exit as its own reason:

protected override void OnFormClosing(FormClosingEventArgs e)
{
    base.OnFormClosing(e);

    if (e.CloseReason == CloseReason.WindowsShutDown
       || e.CloseReason == CloseReason.ApplicationExitCall) 
       return;

This would let you use Application.Exit() to shut down correctly in the handler. Alternatively, you could just close the main (hidden) form directly.

like image 62
Reed Copsey Avatar answered Nov 04 '22 09:11

Reed Copsey


Reeds solution is the best, if you want you could also try this:

System.Diagnostics.Process.GetCurrentProcess().Kill();
like image 1
Dominic B. Avatar answered Nov 04 '22 10:11

Dominic B.