Question

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?

Was it helpful?

Solution

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 if statements, or lots of duplicated switch statements, and you don't want the handler to be 1000 lines long.

What about the following:

private void Grid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    bool shiftPressed = Keyboard.Modifiers == ModifierKeys.Shift;
    bool ctrlPressed = Keyboard.Modifiers == ModifierKeys.Control;

    switch (e.Key)
    {
        case Key.Up:
            e.Handled = ctrlPressed ? PreviousLine() : false; 
            break;
        case Key.Down:
            e.Handled = ctrlPressed ? NextLine() : false; 
            break;
        case Key.Return:
            e.Handled = ctrlPressed ? NextLine() : shiftPressed ? PreviousLine() : false; 
            break;
    }
    e.Handled = false;
}

I created the shiftPressed and ctrlPressed bools so that i could eliminate the surrounding if statement (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 your NextLine() and PreviousLine() 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top