WinForms - Setup a HotKey in a UserControl


The scenario is, you want to setup a hotkey of some action but don't want to (or can't) use a MenuStrip or other control that provides that functionality. The solution is to override the ProcessCmdKey function. You will be able to wire up either a single key or a combination or keys using this method. Here is a basic example:

VB.Net

Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
    Select Case keyData
        ' Shift + F5
        Case Keys.Control Or Keys.F5
            Call ButtonExecute_Click(Nothing, Nothing)
        Case Keys.F4
            ' Do something
    End Select

    Return MyBase.ProcessCmdKey(msg, keyData)
End Function

C#

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    switch (keyData) {
        // Shift + F5
        case Keys.Control | Keys.F5:
            ButtonExecute_Click(null, null);
            break;
        case Keys.F4:
            break;
        // Do something
    }
    return base.ProcessCmdKey(msg, keyData);
}

To note, this example specifically applies to Windows Forms (WinForm) applications. In the above example two different hot keys are set. F4 is wired up as a single hot key and also a key combination of the control key and F5 at the same time.