views:

32

answers:

1

Is it possible to define key bindings in WPF for a sequence of key presses like the shortcuts in Visual Studio e.g. Ctrl+R, Ctrl+A is run all tests in current solution

As far as I can see I can only bind single key combinations like Ctrl+S using the element. Can I bind sequences using this or will I have to manually handle the key presses to do this?

+3  A: 

You need to create your own InputGesture, by overriding the Matches method.

Something like that:

public class MultiInputGesture : InputGesture
{
    public MultiInputGesture()
    {
        Gestures = new InputGestureCollection();
    }

    public InputGestureCollection Gestures { get; private set; }

    private int _currentMatchIndex = 0;

    public override bool Matches(object targetElement, InputEventArgs inputEventArgs)
    {
        if (_currentMatchIndex < Gestures.Count)
        {
            if (Gestures[_currentMatchIndex].Matches(targetElement, inputEventArgs))
            {
                _currentMatchIndex++;
                return (_currentMatchIndex == Gestures.Count);
            }
        }
        _currentMatchIndex = 0;
        return false;
    }
}

It probably needs a little more than that, like ignoring certain events (e.g. KeyUp events between KeyDown events shouldn't reset _currentMatchIndex), but you get the picture...

Thomas Levesque
Have done something very similar to what you suggest in the end, requires a bit more logic since an InputGesture gets every key press (i.e. includes pressing Ctrl, Shift, Alt etc) and you need to take care of the fact that if a user doesn't press the combination in quick succession they probably didn't mean to press it
RobV