Detect if Modifier Key is Pressed in KeyRoutedEventArgs Event
Asked Answered
B

5

15

I have the following code:

public void tbSpeed_KeyDown(object sender, KeyRoutedEventArgs e)
{
    e.Handled = !((e.Key >= 48 && e.Key <= 57) || (e.Key >= 96 && e.Key <= 105) || (e.Key == 109) || (e.Key == 189));
}

Is there any way to detect if any modifier key like shift is being pressed ?

Billbillabong answered 21/10, 2012 at 19:13 Comment(0)
L
22

Use GetKeyState. e.g.

var state = CoreWindow.GetForCurrentThread().GetKeyState(VirtualKey.Shift);
return (state & CoreVirtualKeyStates.Down) == CoreVirtualKeyStates.Down;

Note: For Alt, you would use VirtualKey.Menu.

Laoighis answered 22/10, 2012 at 11:22 Comment(0)
Q
7

For Win10 UWP I noticed that the CTRL and SHIFT keys were set at Locked state. So I did the following:

var shiftState = CoreWindow.GetForCurrentThread().GetKeyState(VirtualKey.Shift);
var ctrlState = CoreWindow.GetForCurrentThread().GetKeyState(VirtualKey.Control);

var isShiftDown = shiftState != CoreVirtualKeyStates.None;
var isCtrlDown = ctrlState != CoreVirtualKeyStates.None;
Quade answered 26/4, 2016 at 15:11 Comment(1)
It is actually even better to use the HasFlag method - CoreWindow.GetForCurrentThread().GetKeyState(VirtualKey.Shift).HasFlag( CoreVirtualKeyStates.Down ) - because this way you avoid the situation where the key is only locked but not actually pressed.Housewifely
H
2

For those looking for WinUI 3-specific approach (CoreWindow is not available there), use the InputKeyboardSource.GetKeyStateForCurrentThread method:

var state = InputKeyboardSource.GetKeyStateForCurrentThread(Windows.System.VirtualKey.Shift);
var isShiftPressed = state.HasFlag(Windows.UI.Core.CoreVirtualKeyStates.Down);
Housewifely answered 5/4, 2023 at 14:6 Comment(0)
S
0

You can try the following code

CoreVirtualKeyStates controlKeyState = Window.Current.CoreWindow.GetKeyState(VirtualKey.Control);
var  ctrl = (controlKeyState & CoreVirtualKeyStates.Down) == CoreVirtualKeyStates.Down;

CoreVirtualKeyStates shiftKeyState = Window.Current.CoreWindow.GetKeyState(VirtualKey.Shift);
var shift = (shiftKeyState & CoreVirtualKeyStates.Down) == CoreVirtualKeyStates.Down;
Skerry answered 23/10, 2012 at 9:34 Comment(0)
B
-1

Bitwise AND the Modifiers property of Keyboard with Shift Key -

bool isShiftKeyPressed = (Keyboard.Modifiers & ModifierKeys.Shift)
                         == ModifierKeys.Shift;

Try this too-

bool isShiftKeyPressed = (ModifierKeys & Keys.Shift) == Keys.Shift;

OR

Control.ModifierKeys == Keys.Shift
Bergman answered 21/10, 2012 at 19:16 Comment(1)
I hate comments that are so vague as to be misleading. What @Billbillabong should have said is, that code is perfectly fine and dandy, except the Keyboard class is not available under UWP.Pseudohemophilia

© 2022 - 2024 — McMap. All rights reserved.