1

I have a MessageBox attached to the closing event of my form checking that the user wants to close the form.

When the event is triggered, the MessageBox should display, asking the user to select 'Yes' or 'No'. Instead, the MessageBox line is run but it is not displayed and the DialogResult is automatically set to 'No' with no user interaction.

I tried actively setting the DialogResult to 'Yes' beforehand and it still got set to 'No' with no user interaction, even though the MessageBoxDefaultButton is set to 'Yes' (Button1).

Can anybody identify what could be causing the MessageBox to be skipped?


private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    closeForm(e);
}

private void closeForm(FormClosingEventArgs e)
{
    DialogResult exityesno = MessageBox.Show("Are you sure you want to exit?", "Close", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);

    if (exityesno == DialogResult.Yes)
    {
        // close form
    }
    else if (exityesno == DialogResult.No)
    {
        e.Cancel = true;
    }
}
Pete
  • 41
  • 5
  • 1
    what happens if you ditch the method closeform and put the code in Form1_FormClosing - and have you paired it up with the event? – BugFinder Nov 07 '17 at 10:39
  • I haven't understood if the MessageBox is displayed but it always exits with DialogResult.No or if it isn't displayed at all. I made a try on a simple winform project and it works for me. – Simone Cifani Nov 07 '17 at 10:41
  • Please check event Form1_FormClosing is attached with your form... – andy Nov 07 '17 at 10:43
  • @BugFinder The event is paired to the form closing, I moved the code into the closing event and the same issue occurred. – Pete Nov 07 '17 at 10:45
  • @SimoneCifani The MessageBox isn't displaying at all and the dialog result is being set to No. The event is attached as when I debug I run through the event and can see the messagebox line being run but it doesn't display – Pete Nov 07 '17 at 10:46
  • @Pete Have you tried to put a breakpoint on MessageBox.Show(..) line and debug your app? – Simone Cifani Nov 07 '17 at 10:51
  • @SimoneCifani Yes that's how I noticed that it was being run but not being displayed, I initially thought it was being skipped altogether – Pete Nov 07 '17 at 10:55
  • 2
    Just for a check, try to remove the last two parameters in MessageBox.Show – Simone Cifani Nov 07 '17 at 11:03
  • @SimoneCifani oh damn, I'm not sure why but that worked. Thanks! edit: It's definitely something to do with MessageBoxOptions.DefaultDesktopOnly, still trying to work out why this is affecting it – Pete Nov 07 '17 at 11:19
  • @Pete it should be something related to your settings because I did a lot of tries and it always works for me, even with MessageBoxOptions.DefaultDesktopOnly set – Simone Cifani Nov 07 '17 at 13:06

0 Answers0