How to correctly retrieve modifier keys in a WPF KeyDown event?
As there does not appear to be any modifier information in the event args you could keep track of the state yourself in some fields and handling both KeyUp
and KeyDown
to update them accordingly.
e.g.
private bool ctrl = false;private void This_KeyDown(object sender, KeyEventArgs e){ if (e.Key == Key.LeftCtrl) //or switch, also: `LeftCtrl` & `RightCtrl` are treated as separate keys ctrl = true; //etc..}private void This_KeyUp(object sender, KeyEventArgs e){ if (e.Key == Key.LeftCtrl) ctrl = false; //etc..}
Whether this is actually a good idea i cannot say...
If you want to handle key gestures i would suggest using dedicated methods like KeyBindings
they should only fire when the gesture happened. For other input you may also want to have a look at TextInput
which is more abstract and returns the text that the input is translated to.
sorry for this destructive answer but...
after a little bit of research it becomes clear to me...the event is called "KeyDown" not "KeyCombinationDown" so it is totally independent of any Modifiers pressed BEFORE...
Actually there is a right way for achieve your goal:Using the Commanding-Pattern.
You define a COMMAND (see google for WPF-Commanding) and add a KeyBinding to your application, where you define the key or the keys/key-combination which will fire up the command...
See the example here:http://msdn.microsoft.com/en-us/library/system.windows.input.keybinding.aspx
IMHO, this is the only way and semantically more elegant, too.
(if this pattern will not be working for you in GENERAL, you maybe have to use native api with pinvoke).
cheers.