0
Mapping WPF HotKeys to Actions

While sitting in the office the other day, we had the task of mapping wpf hotkeys to actions for our real time data application. Normally, in a WPF MVVM application, you could do the following in Xaml to assign a hotkey to a command:

<Window.InputBindings>
  <KeyBinding Command="Command2" Key="F2"/>
  <KeyBinding Command="Command1" Key="F1"/>
</Window.InputBindings>

However, to meet our specific requirements, we need to allow a set of hot keys to be loaded dynamically at runtime. For this, we are using MEF and an exported class that gets imported at runtime by the shell.

Here, we are using a dictionary to map each of our keys to an action.

/// <summary>
    /// This class is used to map hot keys to Actions.
    /// </summary>
    [Export(typeof(IHotKeyMapper))]
    public class HotKeyMapper :IHotKeyMapper
    {
        public Dictionary<Key, Action> HotKeyDictionary { get; private set; }

        public HotKeyMapper()
        {
            InitializeDictionary();
        }

        private void InitializeDictionary()
        {
            HotKeyDictionary = new Dictionary<Key, Action>
                                   {
                                       {Key.J,ShowMenuStubMethod },
                                       {Key.D,ShowMenuStubMethod },
                                       {Key.L,ShowMenuStubMethod },
                                       {Key.Y,ShowMenuStubMethod },
                                       {Key.F,ShowMenuStubMethod },
                                       {Key.C,ShowMenuStubMethod },
                                       {Key.T,ShowMenuStubMethod },
                                       {Key.H,ShowMenuStubMethod },
                                       {Key.V,ShowMenuStubMethod },
                                       {Key.O,ShowMenuStubMethod },
                                       {Key.K,ShowMenuStubMethod },
                                       {Key.R,ShowMenuStubMethod },
                                       {Key.E,ShowMenuStubMethod },
                                       {Key.Escape,ShowMenuStubMethod },
                                       {Key.F1,ShowMenuStubMethod },
                                       {Key.F2,ShowMenuStubMethod },
                                       {Key.Tab,ShowMenuStubMethod }
                                   };
        }

        public void ShowMenuStubMethod()
        {
            Dialog.Show("Menu Opened!");
        }
        
    }

Here, we subscribe to the imported HotKeyMapper and Invoke methods as the events are raised.

       

 void Shell_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (HotKeyMapper.HotKeyDictionary.ContainsKey(e.Key))
            {
                HotKeyMapper.HotKeyDictionary[e.Key].Invoke();
            }
        }

There may be more elegant ways to handle this, but this seemed to be a pretty neat idea.


Kick It on DotNetKicks.com
Marcell
Website