2

I use the code below to create a MessageBox with dialogue. By default, the yes button has focus. If I press the Space key accidentally, the dialog understands that I selected Yes. I want that only if I press the return key to trigger the event. Is there a way to disable the Space key from submitting the answer?

DialogResult dialogResult = MessageBox.Show(sMsg, "Title", MessageBoxButtons.YesNo);
if(dialogResult == DialogResult.Yes)
{
   // do something
}
else if (dialogResult == DialogResult.No)
{
  // do something else
}                        
Nick_F
  • 1,103
  • 2
  • 13
  • 30

2 Answers2

1

Try this:

MessageBox.Show(this, "MessageText", "MessageCaption", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No, MessageBoxOptions.None);

the "MessageBoxResult.No" parameter is the default dialogue result value.

  • Thanks David. I used MessageBox.Show(sMsg, sTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2, MessageBoxOptions.ServiceNotification, false); and this changed the default button from Yes to No. However, I am interested to disable the space key from submitting any answer. I could make another form just for this MessageBox and handle the key events for each button, but this seems wasteful to me. – Nick_F Jan 07 '17 at 12:42
  • @Nick_F : Well it's easier to do that than to create a global keyboard hook to intercept the spacebar key (which is another, but harder, option). – Visual Vincent Jan 07 '17 at 12:52
  • 1
    @Nick_F : I've seen many questions in different forums over the years where they want to modify the behaviour of Windows dialogs. The answer is simply: It is not possible (or maybe more correctly: It is too hard for the regular developer). Therefore it is always better to create your own dialog when you want a different behaviour/look. – Visual Vincent Jan 07 '17 at 12:55
0

Visual Vincent clarified that it is better to create my own dialog form, instead of relying on MessageBox.Show().

Nick_F
  • 1,103
  • 2
  • 13
  • 30