I'm trying to register some keys as Hot Keys that operate not just within global application scope, but are captured even when the application doesn't have focus. I'm very well aware of the fact that doing this is not a good idea, and have sufficient reason to be doing it anyway.
The application is written using MVVM and the MainWindow doesn't even have a code-behind file. If I did use a code-behind for this, I would need to tie into commands in my MainViewModel class file which serves as the DataContext for my MainWindow.
I've setup a test application using code-behind with this class written by Eric Ouellet and it works great. However, when I register a HotKey inside my MainViewModel, the Action - OnHotKeyHandler - never fires.
My stripped down code looks like this. It's VB.NET and the class I linked to above is C#, so I compiled it as a C# class library and set it in my references. I'm getting no error messages at any time and in the real code I'm not swallowing exceptions. My MainWindow is really bound to this class and debugs show that it's been instantiated.
Public Class MainViewModel
Private Shared _hotKeyF4 As GlobalHotKey.HotKey
Public Sub New()
_hotKeyF4 = New GlobalHotKey.HotKey(Key.F4, GlobalHotKey.KeyModifier.None, OnHotKeyHandler, True)
End Sub
Private Function OnHotKeyHandler() As Action(Of GlobalHotKey.HotKey)
Debug.Print("F4 was pressed") 'Never fires
End Function
End Class
If I can't make this particular class/method work, that's OK. All I need is some way to listen Globally (OS level) to keypresses inside a WPF MVVM application. C# code is fine as I will either convert it or compile it, whichever makes the most sense.
Note: Looks like I found a solution which was just recently written but I'm having some problems with it throwing unhandled exceptions if the HotKey I've chosen has already been assigned to something else.