Shortcut Keys in WPF

So you release something, and the first thing the keyboard junkies tell you is they’d like shortcut keys. So first you try this:

private void Window_PreviewKeyUp(object sender, KeyEventArgs e)
{
if (e.KeyboardDevice.Modifiers == ModifierKeys.Control)
{
switch (e.Key)
{
case Key.Q:
quickTypeTabItem.Focus();
break;
case Key.O:
openTabItem.Focus();
break;
}
e.Handled = true;
}
}

This seems right, but it turns out that keyboard shortcuts don’t really work like this. What I mean is we don’t actually hold down control until after we’ve hit the letter key to trigger a keyboard shortcut.  I thought we did, but after test I realized I actually tend to release the control key and then quickly hit the letter. I never realized this until I implemented keyboard shortcuts in the manner above and then quickly found out it was unusable/annoying.

What you really want to use are KeyGestures.  KeyGestures get the timing and everything right.  This post talks about how you can set a KeyGesture and map it to a command in WPF http://www.switchonthecode.com/tutorials/wpf-tutorial-command-bindings-and-custom-commands

Leave a comment