Handling Hot Keys in a Windows Application

I’m mostly a web developer, but there are occasions when I find myself developing WinForm or WPF applications.  On those occasions, I have often needed to handle key combinations that include the ALT, SHIFT, or CONTROL (CTRL) keys.  I also distinctly remember having to use the Win32 API to make that happen.  I think you may need the Win32 API if you want to handle a hot key regardless of which application has focus, but if you are only worried about the hot key when your application has focus, then there is a much simpler way that I found lingering out there on a message board.  All you have to do is override the ProcessCmdKey method in the System.Windows.Forms.Form class.  Then you can use pure .NET code to figure out which key combination is pressed and handle it accordingly:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    switch (keyData)
    {
        case Keys.Alt | Keys.C: 
            //Code for ALT+C Action
            break;

        case Keys.Ctrl | Keys.U:
            //Code for CONTROL+U Action

        case Keys.Alt | Keys.B
            //Code for ALT+B Action

    }
    return base.ProcessCmdKey(ref msg, keyData);
}

If you dig through the Keys enumeration you’ll find there is a ControlKey and an AltKey enumeration item.  These are for the actual keys themselves – they are not key modifiers.  So make sure you use Keys.Ctrl and Keys.Alt in the combination or else you will not get the desired results.