Skip to content

Commit 3ee2521

Browse files
Merge pull request #122 from nullinside-development-group/feat/skip
fix: crash when skipping messages in deployed version
2 parents 3468329 + 688f441 commit 3ee2521

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

src/TwitchStreamingTools/Services/GlobalKeyPressService.cs

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ public class GlobalKeyPressService : IGlobalKeyPressService {
5656
/// <summary>
5757
/// The keystroke callback.
5858
/// </summary>
59-
private Action<Keybind>? s_onKeystroke;
59+
private static Action<Keybind>? s_onKeystroke;
6060

6161
/// <summary>
6262
/// Initializes a new instance of the <see cref="GlobalKeyPressService" /> class.
@@ -86,13 +86,18 @@ public bool IsModifier(Keys key) {
8686
/// The main loop which registers for keystrokes on the system and flushes the message buffer.
8787
/// </summary>
8888
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);
96101
}
97102
}
98103

@@ -103,7 +108,7 @@ private void Main() {
103108
/// <param name="wParam">The <seealso cref="KeyboardMessage" />.</param>
104109
/// <param name="lParam">The <seealso cref="KeyboardLowLevelHookStruct" />.</param>
105110
/// <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) {
107112
var keyboardEvent = Marshal.PtrToStructure<KeyboardLowLevelHookStruct>(lParam);
108113
var whatHappened = (KeyboardMessage)wParam;
109114
var key = (Keys)keyboardEvent.vkCode;
@@ -148,7 +153,7 @@ private int KeystrokeCallback(int nCode, IntPtr wParam, IntPtr lParam) {
148153
/// Logs the keystroke for debugging.
149154
/// </summary>
150155
/// <param name="keybind">The key pressed.</param>
151-
private void LogKey(Keybind keybind) {
156+
private static void LogKey(Keybind keybind) {
152157
LOG.Debug($"Key pressed: {keybind}");
153158
}
154159
}

0 commit comments

Comments
 (0)