-4

Simple question but can't figure out how to do this.

I have a messagebox with just one single "OK" Button, which appears by catching invalid datatypes/formats on inputs.

I want that the "OK" Button will be pushed after pressing Space (and only Space)

I guess I need some sort of event, which checks if the space button is pressed (but only) on this messagebox. But somehow it sounds a bit to inconvinient for such a simple task.

Klunky
  • 15
  • 4
  • there is a keypress event. http://stackoverflow.com/questions/19076051/how-to-use-keypressevent-in-correct-way – Vijay Mar 31 '17 at 13:29
  • 1
    Is this the built-in Windows Forms MessageBox? – stuartd Mar 31 '17 at 13:31
  • 2
    The simple answer is that you can't. Not without creating your own `MessageBox` by using a `Form` which then handles the `KeyPress` event. – ThePerplexedOne Mar 31 '17 at 13:32
  • 1
    Space will click a button in windows as long as it is focused. – Dave Becker Mar 31 '17 at 13:41
  • 1
    Space will click a button, but you have to disable an Enter button click – GenZiy Mar 31 '17 at 14:36
  • *Only* space? No, you can't do that. Why is that necessary? Why does it have to be *only* the space bar? (Also, consider using some kind of in-place notification for invalid inputs, like an ErrorProvider control, rather than an intrusive message box. This makes for much better UX.) – Cody Gray - on strike Mar 31 '17 at 15:45
  • @CodyGray In fact I had a similar problem. Imagine a kiosk-ish something where the user inputs significant amount of data by typing a lot and not looking at the screen, or by scanning (potentially long) barcodes which are converted by the driver to keypresses. If you know the space is the only key that is guaranteed to not appear in such inputs, you very much want to make sure the other characters do not close your "Invalid input" message. – GSerg Apr 02 '17 at 19:05

1 Answers1

0

Well, guessing from your tags. I think you are talking about Window Forms in C#. Yes, there is a way to do that. But not as simple as a message box. All you have to do is:

  • Create a Form and Design it like a MessageBox
  • Override the PreviewKeydown event handler ( or overriding KeyPress event handler will also work)
  • And then match the case when Space key is pressed.

A Sample code is below to give you an idea:

switch (e.KeyCode)
{
    case Keys.Space:
       //Call The Event handler for Ok Button
        e.Handled = true;
        e.Suppressed = true;
        break;
}

(Note: You can also create new event handler for PreviewKeyDown Event instead of overriding. )

  • As you want to show it as a messagebox use ShowDialog() when showing the form instead of Show() method.
HN Learner
  • 544
  • 7
  • 19