Search code examples
c#.netmessageboxkeydown

Closing of a messagebox with space


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.


Solution

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