Search code examples
vb.netformsmessagebox

Why is return from MessageBox.Show not "DialogResult.Cancel" when the close button is pressed?


I'm using the following code:

Dim Reply As DialogResult = MessageBox.Show("GOT IT!")
If Reply = DialogResult.OK Then '...` 

When I click the Close button (red "X" in corner) the condition looking for DialogResult.OK still evaluates to true and when I check the Reply variable's value at runtime after clicking the close button it is 1 {OK}.

From the documentation on MessageBox Class it says:

Displays a message window, also known as a dialog box, which presents a message to the user. It is a modal window, blocking other actions in the application until the user closes it. A MessageBox can contain text, buttons, and symbols that inform and instruct the user.

While I find the documentation on DialogBoxes a little convoluted and confusing, it appears to me (and i could be bery wrong) that the Close button should by default set the return to IDCancel which, I must assume is somehow parsed by the MessageBox class into DialogReturn.Cancel.

So why does MessageBox not show the return form the close button as DialogResult.Cancel??


This is all very confusing to me because it seems the MessageBox class is not consistent with other forms from within the same Systems.Windows.Forms namespace.

For instance, if we look at the documentation from the Form Class's .DialogResult method, it specifically tells us the return from the close button is DialogResult.Cancel:

When a form is displayed as a modal dialog box, clicking the Close button (the button with an X in the top-right corner of the form) causes the form to be hidden and the DialogResult property to be set to DialogResult.Cancel.


Solution

  • As already stated in the comments above, you could get IDCancel result when clicking the Close Red Button, only if you add a MessageBoxButtons enum that include the Cancel option For example MessageBoxButtons.OKCancel and others.

    The MessageBox.Show method is indeed a wrapper around the WinApi MessageBox function. You could see this wrapping looking at the reference sources

    The behavior of MessageBox.Show is different from the link that you have pointed. That one is relative to the WinForm engine and of course the behavior of the WinForm Form class is totally managed by the library to handle the scenarios presumed for a WinForm class.

    In the WinApi documentation you could find a subtle reference in the section about the Return value where they talks about the behavior when the cancel button is present. Then trial and error confirms this assumption.