Search code examples
wpfxamlkeyboard-shortcutsbindingkey-bindings

Can I create a KeyBinding for a sequence of keys in WPF?


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?


Solution

  • 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...