Click here to monitor SSC

Damon Armstrong

Caffeine Induced Tirades about .NET and Life
And don't forget to check out my latest Simple-Talk articles
View Damon Armstrong's profile on LinkedIn      Add to Technorati Favorites      Add to Google     

Handling Hot Keys in a Windows Application

Published Monday, August 16, 2010 2:42 AM

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.

by Damon

Comments

No Comments
You need to sign in to comment on this blog
Latest articles
Checking Out SQL Backup Pro 7’s New Automatic Backup Verification
 Wouldn't it be great to offload the daily chore of checking the integrity of your production... Read more...

Chuck Lathrope: DBA of the Day
 Chuck Lathrope was a finalist for the Exceptional DBA of the Year award in 2009. We contacted him to... Read more...

Backups, What Are They Good For?
 Pixar recently confessed, in an engaging video, that Toy Story 2 was almost lost due to a bad backup,... Read more...

C# Async: What is it, and how does it work?
 The biggest new feature in C#5 is Async, and its associated Await (contextual) keyword. Anybody who is... Read more...

SQL Server 2012 AlwaysOn
 SQL Server AlwaysOn provides a high-availability and Disaster-recovery solution for SQL Server 2012. It... Read more...