Karlx Swanovski
Karlx Swanovski

Reputation: 2989

Cancel Application Exit

My application is closing when I press Alt + F4. How I will do to have a MessageBox to show first for confirmation before exiting and if No is response the applcation will not continue to close?

Upvotes: 2

Views: 6025

Answers (3)

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28588

On FormClosing() event add this code:

private void MyForm_Closing(object sender, CancelEventArgs e)
{
    if(MessageBox.Show("Are you sure want to exit the App?", "Test", MessageBoxButtons.YesNo) == DialogResult.No)
    {
      e.Cancel = true;
    }
}

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273804

In addition to the answers already posted here, don't be the dork that hangs the complete system:

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (e.CloseReason != CloseReason.UserClosing)
        {
           e.Cancel = false;
           return;
        }

        // other logic with Messagebox
        ...
    }

Upvotes: 8

Dan Puzey
Dan Puzey

Reputation: 34218

Handle the Form.Closing event, which takes a CancelEventArgs as parameter. In that handler, show your messagebox. If the user wishes to cancel, set the property .Cancel of the event args to true, like this:

private void Form1_Closing(object sender, CancelEventArgs e)
{
    var result = MessageBox.Show("Do you really want to exit?", "Are you sure?", MessageBoxButtons.YesNo);
    if (result == DialogResult.No)
    {
        e.Cancel = true;
    }
}

Upvotes: 4

Related Questions