Farhad-Taran
Farhad-Taran

Reputation: 6512

how can I create a Message Box that captures user's response?

I am trying to view a message box. this should happen when the user tries to exit the program while there are child windows active. if there are no active child windows then the application should end. i have written some code but when the user clicks on NO, the message box immediately pops up again.if you have a better way of doing this please feel free to share, thank you.

private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
    {
        Form child = this.ActiveMdiChild;

        if(child != null)
        {
            DialogResult res = 
                MessageBox.Show( child.Name +
                "Do you want to exit?", "Exit",
                MessageBoxButtons.YesNo, MessageBoxIcon.Warning);


            if (res == DialogResult.No)
            {
                e.Cancel = true;

                child.Focus();

            }
            else if (res == DialogResult.Yes)
            {

                Application.Exit();

            }

        }
        else if (child == null)
        {
            Application.Exit();
        }   

    }

Upvotes: 3

Views: 12043

Answers (4)

Dialecticus
Dialecticus

Reputation: 16761

According to MSDN if there are child form who canceled closing then main form will have its e.Cancel already set to true. Also there's no need to call Application.Exit(), because after the main form closes the application should end. Try this:

private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
{
    Form child = this.ActiveMdiChild;

    if (child != null)
    {
        DialogResult res = 
            MessageBox.Show( child.Name +
            "Do you want to exit?", "Exit",
            MessageBoxButtons.YesNo, MessageBoxIcon.Warning);


        if (res == DialogResult.No)
        {
            e.Cancel = true;
            child.Focus();
        }
        else
        {
            e.Cancel = false;
        }
    }
}

Upvotes: 4

Alaa Jabre
Alaa Jabre

Reputation: 1883

else if (res == DialogResult.Yes)
            {

                Application.Exit();

            }

just remove this from your code code

Upvotes: 0

alfoks
alfoks

Reputation: 4624

It's because of the call to Application.Exit(). Why do you need it if it is the Main form anyway? You can filter this out by adding this check on the top of the function

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

Upvotes: 0

Jacek Gorgoń
Jacek Gorgoń

Reputation: 3214

Perhaps you're handling the FormClosing event multiple times. Can you paste code that adds MainWindow_FormClosing to the event?

Upvotes: 0

Related Questions