Adding an F5 Hotkey in C#

joe picture joe · Dec 26, 2009 · Viewed 16.6k times · Source

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?

Answer

John Knoeller picture John Knoeller · Dec 26, 2009

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;
}