diff --git a/src/SoundType.Input/KeyboardHookService.cs b/src/SoundType.Input/KeyboardHookService.cs index dd27f07..be8c4ac 100644 --- a/src/SoundType.Input/KeyboardHookService.cs +++ b/src/SoundType.Input/KeyboardHookService.cs @@ -53,11 +53,13 @@ public void Stop() { if (_hookId == IntPtr.Zero) { + _pressedKeys.Clear(); return; } _ = _platform.Unhook(_hookId); _hookId = IntPtr.Zero; + _pressedKeys.Clear(); } private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) diff --git a/src/SoundType.Tests/KeyboardHookServiceTests.cs b/src/SoundType.Tests/KeyboardHookServiceTests.cs index 3a19527..0baf979 100644 --- a/src/SoundType.Tests/KeyboardHookServiceTests.cs +++ b/src/SoundType.Tests/KeyboardHookServiceTests.cs @@ -52,6 +52,26 @@ public void KeyPressed_MarksSecondKeydownAsRepeatUntilKeyup() }); } + [Fact] + public void Stop_ClearsPressedKeysSoRestartDoesNotMarkFreshKeydownAsRepeat() + { + FakeKeyboardHookPlatform platform = new(); + using KeyboardHookService service = new(platform); + List events = []; + service.KeyPressed += (_, e) => events.Add(e); + + service.Start(); + platform.Send(WmKeydown, AKey); + service.Stop(); + service.Start(); + platform.Send(WmKeydown, AKey); + + Assert.Collection( + events, + first => Assert.False(first.IsRepeat), + afterRestart => Assert.False(afterRestart.IsRepeat)); + } + private sealed class FakeKeyboardHookPlatform : IKeyboardHookPlatform { private KeyboardHookService.LowLevelKeyboardProc? _callback;