Handling Hot Keys in a Windows Application

Comments 0

Share to social media

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.

Load comments

About the author

Damon Armstrong

See Profile

Damon Armstrong is a consultant with SystemwarePS in Dallas, Texas. He is also a blogger and author of Pro ASP.NET 2.0 Website Programming and SharePoint 2013 Essentials for Developers. He specializes in the Microsoft stack with a focus on web technologies like MVC, ASP.NET, JavaScript, and SharePoint. When not staying up all night coding, he can be found watching a bunch of kids, studying Biblical topics, playing golf, or recovering from staying up all night coding.