I want to detect a key combination (e.g. Control-A
) in a Windows App. The KeyDown
event handler has information about the last key pressed. But how do I find out whether the Control key is pressed as well?
You can use CoreVirtualKeyStates.HasFlag(CoreVirtualKeyStates.Down)
to determine is the Ctrl key has been pressed, like this -
Window.Current.CoreWindow.KeyDown += (s, e) =>
{
var ctrl = Window.Current.CoreWindow.GetKeyState(VirtualKey.Control);
if (ctrl.HasFlag(CoreVirtualKeyStates.Down) && e.VirtualKey == VirtualKey.A)
{
// do your stuff
}
};
You can use AcceleratorKeyActivated event, irrespective of where the focus is it will always capture the event.
public MyPage()
{
Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated += AcceleratorKeyActivated;
}
private void AcceleratorKeyActivated(CoreDispatcher sender, AcceleratorKeyEventArgs args)
{
if (args.EventType.ToString().Contains("Down"))
{
var ctrl = Window.Current.CoreWindow.GetKeyState(VirtualKey.Control);
if (ctrl.HasFlag(CoreVirtualKeyStates.Down))
{
switch (args.VirtualKey)
{
case VirtualKey.A:
Debug.WriteLine(args.VirtualKey);
Play_click(sender, new RoutedEventArgs());
break;
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With