Partition modifiers from Windows Form Keys

I am currently working on a project that is setting up hotkeys to perform actions. I have hotkey functionality, but I don’t want the hotkeys to be installed if the key consists only of modifiers. For example, Ctrl+ Fis a valid hotkey, but Ctrl+ is Altnot.

I tried several ways to remove modifier keys from the actual Keys enumeration object, and then check it on Keys.None to determine if it consists only of modifier keys. However, in practice this does not work so well.

I tried this method first:

private Keys StripModifiers(Keys Key)
{
    return Key & ~Keys.Modifiers;
}

This did not work because my Ctrl key calls the PreviewKeypress method with the KeyData property for LButton | ShiftKey | Control, which apparently does not fully capture the Keys.Modifiers bitmask.

I tried to write my own, more complex:

private Keys StripModifiers(Keys Key)
{
    return Key &
        ~Keys.Alt &
        ~Keys.CapsLock &
        ~Keys.Control &
        ~Keys.ControlKey &
        ~Keys.LControlKey &
        ~Keys.LMenu &
        ~Keys.LShiftKey &
        ~Keys.LWin &
        ~Keys.MButton &
        ~Keys.Menu &
        ~Keys.NumLock &
        ~Keys.RButton &
        ~Keys.RControlKey &
        ~Keys.RMenu &
        ~Keys.RShiftKey &
        ~Keys.RWin &
        ~Keys.Scroll &
        ~Keys.Shift &
        ~Keys.ShiftKey;
}

However, this did not work because pressing the A key, which simply raised an event with the KeyData 65 property, reduces it to Keys.None, so it is too restrictive.

At some point I am at a loss, has anyone ever encountered or solved this problem before?

+3
source share
1 answer

The source code is correct. You can make it more understandable with Key & Keys.KeyCode, but it will give the same result. Therefore, you need to use this method in the Options window:

private static IsValidShortcutKey(Keys key) {
    return (key & Keys.KeyCode) != Keys.None;
}

ProcessKeyPreview(). ProcessCmdKey() btw. , , , IsValidShortcutKey(). , , , . , Keys.ToString() , Keys, [Flags]. int, .

, . "", . IsValidShortcutKey().

, , . :

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
        if (keyData == keySelectedInConfig) {
            RunOperationSelectedInConfig();
            return true;
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }
+2

All Articles