Question

I want to be able to tell when a modified key (Ctrl or Shift) is pressed or released.

Basically, users can perform multiple keystrokes with a modifier key pressed and I don't want to perform an action until after it is released (think Emacs with Ctrl + X + S).

I was trying to do this with PreviewKeyUp and PreviewKeyDown, but that seems to handle normal keys and not modifiers. I can tell if the modifier key is pressed or not once I am in the event, but I can't tell if the modifier key was released and re-pressed between events.

Was it helpful?

Solution 2

I just realized Key.LeftShift, etc. exist. So I can just set a flag when it is pressed and check that flag when a key is released.

OTHER TIPS

protected override void OnPreviewKeyDown(KeyEventArgs e)
{
    // I just picked that key for a sample
    case Key.Tab:
        if (Keyboard.IsKeyDown(Key.LeftShift) ||
            Keyboard.IsKeyDown(Key.RightShift))
        {
            DoMyStuff();
        }


    // Similar things for Ctrl:

       if (Keyboard.IsKeyDown(Key.LeftCtrl) ||
           Keyboard.IsKeyDown(Key.RightCtrl))
        {
            ....
        }

The easiest way would be doing this, whenever you want to get which modifiers are pressed.

var kb = new Microsoft.VisualBasic.Devices.Keyboard();

var alt = kb.AltKeyDown;
var ctrl = kb.CtrlKeyDown;
var shift = kb.ShiftKeyDown;

You can make a method out of it, so it will be easier to work with, like this:

using Microsoft.VisualBasic.Devices;

...

private static readonly Keyboard KEYBOARD = new Keyboard();

private static Keys GetPressedModifiers()
{
    var mods = Keys.None;

    if (KEYBOARD.AltKeyDown)
    {
        mods |= Keys.Alt;
    }

    if (KEYBOARD.CtrlKeyDown)
    {
        mods |= Keys.Control;
    }

    if (KEYBOARD.ShiftKeyDown)
    {
        mods |= Keys.Shift;
    }

    return mods;
}

You can do something like this in the KeyDown or PreviewKeydown event.

Here I am just taking an example of Shift + A:

if (e.Key == Key.A && Keyboard.Modifiers == ModifierKeys.Shift)
{
    // Do something.
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top