Write code for when the X is clicked on a message box in C#

1.7k views Asked by At

I writing an application in C# in Visual Studio 2017. I'm using Windows Forms App (.NET Framework). I have a MessageBox pop up with its default settings (only the OK button and the X in the top right corner). When the user selects "OK" the remaining code resumes. I want to write separate code to run when the user selects the X to close the message box. How can I tell if the user has clicked the X to close the message box?

I have tried using

DialogResult result = MessageBox.Show("Message here");
if(result != DialogResult.OK){
    //Do stuff here
} 

but even when the X is pressed, result still comes back as Dialog.OK.

What should I do?

Update

This code works fine

DialogResult result = MessageBox.Show("Message here", "MessageBoxTitle", MessageBoxButtons.OKCancel);
if(result != DialogResult.OK){
    //Do stuff here
} 

However, my message box now has an unnecessary Cancel button. Is there a way to achieve this with just the MessageBoxButtons.OK setting so that I avoid having the Cancel button?

2

There are 2 answers

1
Mark Phaedrus On BEST ANSWER

This is a limitation of the underlying Win32 MessageBox API.

The API does not provide a way to specify how the Close box works separately. Clicking the Close box (or pressing Escape) always returns the ID of the Cancel button if there is one, or the default button if there isn't.

And unfortunately, no, you can't try to cheat by setting the default button to a nonexistent button -- if you do that, the default will be reset to one of the existing buttons.

So if you want to handle the Close box in a more sophisticated way than that, you'll have to create your own dialog box rather than letting ::MessageBox do it for you.

0
Vlad DX On

In addition to the answer about Windows API.

System.Windows.Forms.MessageBox.Show("Message") internally calls private method System.Windows.Forms.ShowCore(...).

Method .Show(text) is defined in that way:

/// <summary>
///  Displays a message box with specified text.
/// </summary>
public static DialogResult Show(string text)
{
    return ShowCore(null, text, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, 0, false);
}

It means that .Show(text) is just a shorthand version of full method call. Therefore, you can achieve only those results that could be achieved by calling the actual .ShowCore(...) method.