Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if Modifier Key is Pressed in KeyRoutedEventArgs Event

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 ?

like image 595
Elmo Avatar asked Oct 21 '12 19:10

Elmo


2 Answers

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.

like image 66
AndrewS Avatar answered Oct 30 '22 04:10

AndrewS


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;
like image 31
Michael Sabin Avatar answered Oct 30 '22 04:10

Michael Sabin