Krono
Krono

Reputation: 1362

C# Application Restart

I have a log-out option on my WinForms Application that uses this code:

    // restart the application once user click on Logout Menu Item
    private void eToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Application.Restart();
    }

Clicking the Log out option brings up the "are you sure" box with "Yes" or "No"

private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
    {
        //Double check if user wants to exit
        var result = MessageBox.Show("Are you sure you want to exit?", "Message",
        MessageBoxButtons.YesNo, MessageBoxIcon.Information);
        if (result == DialogResult.Yes)
        {
            e.Cancel = false;
        }
        else
        {
            e.Cancel = true;
        }
    }

, yes works no problem, but clicking "No" still restarts the application, how do i fix this?

Upvotes: 1

Views: 3902

Answers (2)

usamazf
usamazf

Reputation: 3215

Put the dialog box like this inside the MenuItem_Click:

// restart the application once user click on Logout Menu Item
private void eToolStripMenuItem_Click(object sender, EventArgs e)
{
    //Double check if user wants to exit
    var result = MessageBox.Show("Are you sure you want to exit?", "Message",
    MessageBoxButtons.YesNo, MessageBoxIcon.Information);
    if (result == DialogResult.Yes)
    {
        Application.Restart();
    }
}

Leave your FormClosing event empty:

private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
    {


    }

The other way of doing it would be if you absolutely want the dialog box to be implemented in the FormClosing event to override the OnFormClosing()

You can do this like this:

 protected override void OnFormClosing(FormClosingEventArgs e) {

        //Double check if user wants to exit
        var result = MessageBox.Show("Are you sure you want to exit?", "Message",
        MessageBoxButtons.YesNo, MessageBoxIcon.Information);
        if (result == DialogResult.Yes)
            e.Cancel = true;
            base.OnFormClosing(e);
    }

In this case also the FormClosing event will remain empty.

Upvotes: 3

Medo Medo
Medo Medo

Reputation: 1018

  DialogResult confirm = MessageBox.Show("confirm Exit?", "exit", MessageBoxButtons.YesNo);
            if (confirm==DialogResult.Yes)
                Application.Restart();
            else
            {
                //do some thing
            }

Upvotes: 2

Related Questions