10

I'm making a windows app (WinForms) and would like my application to call a method when the user presses F5 - this should work no matter what the user is doing but they must be using the program - I don't want to use global hooks - any ideas?

joe
  • 101
  • 1
  • 1
  • 3

3 Answers3

19

Override the form's ProcessCmdKey on your main form and look for F5.

protected override bool ProcessCmdKey (ref Message msg, Keys keyData)
{
    bool bHandled = false;
    // switch case is the easy way, a hash or map would be better, 
    // but more work to get set up.
    switch (keyData)
    {
        case Keys.F5:
            // do whatever
            bHandled = true;
            break;
    }
    return bHandled;
}
tonycoupland
  • 4,127
  • 1
  • 28
  • 27
John Knoeller
  • 33,512
  • 4
  • 61
  • 92
  • 4
    You might want to add a **default** case in the switch so that and let the base class take a look at the key instead of just returning false: ` default: return base.ProcessCmdKey(ref msg, keyData);` – Guillaume LaHaye Oct 14 '15 at 01:13
4

If you have only one form that can have focus, you can set the KeyPreview property of that form to true and handle the KeyPress event.

The KeyPreview property will cause the form to receive all key presses, regardless which control on the form has the input focus.

Joey
  • 344,408
  • 85
  • 689
  • 683
4

Check out the Form.KeyPreview property, it will allow you to trap all KeyDown, KeyUp and KeyPress events at the form level before allowing them to be processed by individual elements.

MSDN Form.KeyPreview page

Aviad P.
  • 32,036
  • 14
  • 103
  • 124
  • This only works in the case of trivial apps that are a single form and one of the forms children always has focus. it's more like a hack that works most of the time than a solution. – John Knoeller Dec 26 '09 at 22:07