I’ve recently started using WPF for developing my applications. Now I’ve come to a point where I need some tips on good design when it comes to key combination handling.
This is what I’m using at the moment:
private void Grid_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.Modifiers == ModifierKeys.Control)
{
switch (e.Key)
{
case Key.Up: PreviousLine(); break;
case Key.Down: NextLine(); break;
case Key.Return: NextLine(); break;
}
}
else if (Keyboard.Modifiers == ModifierKeys.Shift)
{
switch (e.Key)
{
case Key.Return: PreviousLine(); break;
}
}
}
As you can imagine, this will start to get really ugly, really fast.
Do you have any tips which would improve the code?
IMVHO there is nothing too much wrong with what you are doing, as long as it is confined to the View.
The only thing to discuss is how to smooth out the testing of key states. How you structure this is largely over to personal preference, everyone will have a slightly different take on it. Although you don’t want endless
else ifstatements, or lots of duplicatedswitchstatements, and you don’t want the handler to be 1000 lines long.What about the following:
I created the
shiftPressedandctrlPressedbools so that i could eliminate the surroundingifstatement (and any duplication that goes with it) and use the ternary statement instead. For this to work, you will need to return a bool from yourNextLine()andPreviousLine()functions – that might seem stupid but they may not always be able to do what they should, i.e.NextLine()can return false if you are on the bottom row of the grid.