@@ -56,7 +56,7 @@ public class GlobalKeyPressService : IGlobalKeyPressService {
56
56
/// <summary>
57
57
/// The keystroke callback.
58
58
/// </summary>
59
- private Action < Keybind > ? s_onKeystroke ;
59
+ private static Action < Keybind > ? s_onKeystroke ;
60
60
61
61
/// <summary>
62
62
/// Initializes a new instance of the <see cref="GlobalKeyPressService" /> class.
@@ -86,13 +86,18 @@ public bool IsModifier(Keys key) {
86
86
/// The main loop which registers for keystrokes on the system and flushes the message buffer.
87
87
/// </summary>
88
88
private void Main ( ) {
89
- // Set a hook.
90
- s_hook = User32 . SetWindowsHookEx ( User32 . WindowsHookType . WH_KEYBOARD_LL , KeystrokeCallback , IntPtr . Zero , 0 ) ;
91
-
92
- unsafe {
93
- // Buffer the messages.
94
- User32 . MSG message ;
95
- while ( 0 != User32 . GetMessage ( & message , IntPtr . Zero , 0 , 0 ) ) { }
89
+ try {
90
+ // Set a hook.
91
+ s_hook = User32 . SetWindowsHookEx ( User32 . WindowsHookType . WH_KEYBOARD_LL , KeystrokeCallback , IntPtr . Zero , 0 ) ;
92
+
93
+ unsafe {
94
+ // Buffer the messages.
95
+ User32 . MSG message ;
96
+ while ( 0 != User32 . GetMessage ( & message , IntPtr . Zero , 0 , 0 ) ) { }
97
+ }
98
+ }
99
+ catch ( Exception ex ) {
100
+ LOG . Error ( "Failed to subscribe to Win32 windows hook" , ex ) ;
96
101
}
97
102
}
98
103
@@ -103,7 +108,7 @@ private void Main() {
103
108
/// <param name="wParam">The <seealso cref="KeyboardMessage" />.</param>
104
109
/// <param name="lParam">The <seealso cref="KeyboardLowLevelHookStruct" />.</param>
105
110
/// <returns>The next hook that should be called.</returns>
106
- private int KeystrokeCallback ( int nCode , IntPtr wParam , IntPtr lParam ) {
111
+ private static int KeystrokeCallback ( int nCode , IntPtr wParam , IntPtr lParam ) {
107
112
var keyboardEvent = Marshal . PtrToStructure < KeyboardLowLevelHookStruct > ( lParam ) ;
108
113
var whatHappened = ( KeyboardMessage ) wParam ;
109
114
var key = ( Keys ) keyboardEvent . vkCode ;
@@ -148,7 +153,7 @@ private int KeystrokeCallback(int nCode, IntPtr wParam, IntPtr lParam) {
148
153
/// Logs the keystroke for debugging.
149
154
/// </summary>
150
155
/// <param name="keybind">The key pressed.</param>
151
- private void LogKey ( Keybind keybind ) {
156
+ private static void LogKey ( Keybind keybind ) {
152
157
LOG . Debug ( $ "Key pressed: { keybind } ") ;
153
158
}
154
159
}
0 commit comments