Search

Tuesday, February 05, 2008

Capture Combination Keys in Your Windows Forms Application

Often while writing a Windows application, it can be helpful to capture a combination of keys such as Ctrl-F1 or Alt-F2. This can be a requirement when showing/hiding some special option that you would not want available by default. So here is how to do just that. To accomplish this task, the "ProcessDialogKey" function needs to be overridden as follows:
protected override bool ProcessDialogKey(Keys keyData)
{
    // Declare a variable to keep track of the key modifiers (Ctrl,Alt,Shift,etc.)
    string modifiers = "";

    // Get the actual integer value of the keystroke
    int keyCode = (int)keyData;

    // Check to see if the control key is on
    if ((keyCode & (int)Keys.Control) != 0)
    {
        modifiers += "";
    }

    // Check to see if the alt key is on
    if ((keyCode & (int)Keys.Alt) != 0)
    {
        modifiers += "";
    }

    // Check to see if the shift key is on
    if ((keyCode & (int)Keys.Shift) != 0)
    {
        modifiers += "";
    }

    // Strip off the modifier keys
    keyCode = keyCode & 0xFFFF;

    // Attempt to convert the remaining bits to the enum name
    Keys key = (Keys)keyCode;

    if ((key != Keys.Menu) && (key != Keys.ControlKey) && (key != Keys.ShiftKey))
    {
        // If the user pressed the Ctrl-F1 combination
        if (key == Keys.F1 && modifiers == "")
        {
            // Do something special
        }
    }

    // Return control to the base function
    return base.ProcessDialogKey(keyData);
}
// //]]>