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?
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.