Reputation: 5043
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.
Upvotes: 4
Views: 4431
Reputation: 2417
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.
}
Upvotes: 0
Reputation: 6316
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))
{
....
}
Upvotes: 2
Reputation: 5043
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.
Upvotes: 1
Reputation: 14522
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;
}
Upvotes: 0