In addition to Solution 2, I want to explain how you can handle keyboard events on low level, which can be useful in some custom situations, which cannot be reduced to known "gestures". Besides, you need to understand the idea of reusing the handlers of different events.
Let's start from the "same event handler". You can use a regular (named, not anonymous) method to call in any handler. This way, you can call the same function in two or more different event handlers. It's better to make those functions abstracted from the events (event arguments, etc), make them purely semantic. Simple, isn't it?
Now, Ctrl-something key events can be handled as
KeyDown
event or any
UIElement
. However, it would make one problem. Probably, you want you Ctrl-key event to be handled in your form no matter when you hit those keys. If you have, say, a form and several controls on a form, any of those controls can grab the
keyboard focus. It this UI element does not handle the keyboard element, the event will be ignored.
How to sort it out? It's good to understand that events can be
routed using a
tunneling route or a
bubbling route. Please see:
http://msdn.microsoft.com/en-us/library/ms742806%28v=vs.110%29.aspx[
^].
This CodeProject article can also be used:
To bubble or tunnel basic WPF events[
^].
As you can see, in your case, it can be as simple as this: handle the event
PreviewKeyDown
of the form. For example:
PreviewKeyDown += (sender, eventArgs) => {
if (Keyboard.Modifiers != ModifierKeys.Control) return;
if (eventArgs.Key == Key.D)
CtrlDHandler();
if (eventArgs.Key == Key.O)
CtrlOHandler();
eventArgs.Handled = true;
};
Here, the methods
CtrlDHandler
and
CtrlOHandler
can be those very "semantic", "real" event handlers reused in other event handlers. Note the benefit of the anonymous even handlers I used. This way, you can free up those "real" handlers of all the unwanted and unused detail, such as
sender
and
eventArgs
. Now, these methods could be used in handlers associated with menu items, but it would be better to use
commands. Please see:
http://msdn.microsoft.com/en-us/library/ms752308%28v=vs.110%29.aspx[
^],
and for example:
http://www.wpf-tutorial.com/common-interface-controls/menu-control[
^],
http://www.skimedic.com/blog/post/2008/07/14/WPF-Menus-and-Commands.aspx[
^].
—SA