简体   繁体   中英

Which message should I handle if I need to detect a keyboard shortcut?

Let's say I am looking for the keyboard short-cut Alt + C in my application. I believe I must not handle WM_KEYDOWN for various reasons, one being that it is for detecting non-system keys and does not tell you about the Alt key specifically. It has only a 1-bit flat to tell you if any extended key was pressed along with the virtual key.

I believe WM_CHAR is a more appropriate one for me here. My questions are:

a) Am I right in my assumption?

b) How do I get the character code from wParam and compare it with, say, Alt + C ?

You can use WM_SYSKEYDOWN and WM_SYSCHAR to detect the Alt keypress.

You have more information in this article .

a) No, WM_CHAR won't detect and alt press.

For general keyboard shortcut handling it'd better use Control.ProcessCmdKey override.

It is called as Keyboard Accelerators in Win32.

I don't have direct experience of Control.ProcessCmdKey but it looks like easy thing to do.

Example found by Google search: http://www.codeguru.com/columns/experts/article.php/c4639

protected override bool ProcessCmdKey( ref Message msg, 
                                       Keys keyData )
{
    // Check this key...
    bool bHandled = false;

    // Look up value
    Accelerators accel = Accelerators.Unspecified;
    if ( _accelHash.ContainsKey(AcceleratorKey(keyData)) )
    {
        accel = (Accelerators)_accelHash[key];

        switch ( accel )
        {
            case Accelerators.Home:
                DisplayHome();
                bHandled = true;
                break;

            case Accelerators.Save:
                Save();
                bHandled = true;
                break;

            case Accelerators.Print:
                Print();
                bHandled = true;
                break;

            case Accelerators.Logout:
                LogOut();
                bHandled = true;
                break;

            case Accelerators.Unspecified:
            default:
                break;

        } // switch
    } // if

    return bHandled;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM