Okay I have done it! Adding a global hotkey using WPF and VB.NET can be done by adding these references (Mainwindow.xmal.vb):
Imports System.Runtime.InteropServices
Imports System.Windows.Interop
Then adding the following to the Code behind:
<DllImport("User32.dll")> _
Private Shared Function RegisterHotKey(<[In]> hWnd As IntPtr, <[In]> id As Integer, <[In]> fsModifiers As UInteger, <[In]> vk As UInteger) As Boolean
End Function
<DllImport("User32.dll")> _
Private Shared Function UnregisterHotKey(<[In]> hWnd As IntPtr, <[In]> id As Integer) As Boolean
End Function
Private _source As HwndSource
Private Const HOTKEY_ID As Integer = 9000
Protected Overrides Sub OnSourceInitialized(e As EventArgs)
MyBase.OnSourceInitialized(e)
Dim helper = New WindowInteropHelper(Me)
_source = HwndSource.FromHwnd(helper.Handle)
_source.AddHook(AddressOf HwndHook)
RegisterHotKey()
End Sub
Protected Overrides Sub OnClosed(e As EventArgs)
_source.RemoveHook(AddressOf HwndHook)
_source = Nothing
UnregisterHotKey()
MyBase.OnClosed(e)
End Sub
Private Sub RegisterHotKey()
Dim helper = New WindowInteropHelper(Me)
Const VK_F10 As UInteger = &H79
Const MOD_CTRL As UInteger = &H2
' handle error
If Not RegisterHotKey(helper.Handle, HOTKEY_ID, MOD_CTRL, VK_F10) Then
End If
End Sub
Private Sub UnregisterHotKey()
Dim helper = New WindowInteropHelper(Me)
UnregisterHotKey(helper.Handle, HOTKEY_ID)
End Sub
Private Function HwndHook(hwnd As IntPtr, msg As Integer, wParam As IntPtr, lParam As IntPtr, ByRef handled As Boolean) As IntPtr
Const WM_HOTKEY As Integer = &H312
Select Case msg
Case WM_HOTKEY
Select Case wParam.ToInt32()
Case HOTKEY_ID
OnHotKeyPressed()
handled = True
Exit Select
End Select
Exit Select
End Select
Return IntPtr.Zero
End Function
Private Sub OnHotKeyPressed()
MsgBox("Hello world!")
End Sub
This is for Ctrl+F10. It can be changed by modifying the following according to Keycodes from here and Key modifiers from here. Just replace the 0x with &H.
Const VK_F10 As UInteger = &H79
Const MOD_CTRL As UInteger = &H2
Hope this helps someone. Credit goes to "max" from which the code was converted:
Global hotkeys in WPF working from every window