4

I've got a WPF (prism) app, which uses a whole lot of other WPF assemblies and even win32 dlls containing other windows (wpf and win32).

When the user presses a function Key (F2-F12) I want to open spezific program functions.

Something like this:

RoutedCommand commandF4 = new RoutedCommand();
commandF4.InputGestures.Add(new KeyGesture(Key.F4));
Application.Current.MainWindow.CommandBindings.Add(new CommandBinding(commandF4, CallCommandF4));

The problem is: this does only work while the MainWindow has the focus. If I open a secondary WPF window (or a win32 window) the keybinding does not apply anymore.

Is there any way to add an applicationwide global hotkey for F4 (or some other key)?
Or at least a WPF-wide hotkey?

Sam
  • 28,421
  • 49
  • 167
  • 247
  • [Input focus can only be on one window at any point in time](http://msdn.microsoft.com/en-us/library/ms754010.aspx#focus). You could try catching the keybinding in the secondary window and use [messaging](http://www.google.com/search?q=mvvm+messaging) to communicate to the MainWindow that the key was pressed. Win32 window may require lower level keyboard hooks and the sort. – Jake Berger Jun 08 '11 at 19:03

1 Answers1

3

You can try I think to write a hook to keyboard and attached this hook to listen for keyboard messages from your application's thread.

This is really good example for inspiration: http://www.codeproject.com/KB/cs/globalhook.aspx.

Just take a note that if you use .Net 4.0 then when you will use SetWindowsHookEx instead of using

Assembly.GetExecutingAssembly().GetModules()[0]

as a hMod param, use:

Process.GetCurrentProcess().MainModule.BaseAddress
fxdxpz
  • 1,969
  • 17
  • 29