Skip to content

Commit

Permalink
prevent held keys repeated event triggering and optimize key presses …
Browse files Browse the repository at this point in the history
…when they aren't listened
  • Loading branch information
Aytackydln committed Mar 21, 2024
1 parent 2b87a50 commit 8d999c8
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ private void Grid_KeyDown(object? sender, KeyEventArgs e)

private async void Control_Keybind_OnLoaded(object sender, RoutedEventArgs e)
{
(await InputsModule.InputEvents).KeyDown -= InputEventsKeyDown;
(await InputsModule.InputEvents).KeyDown += InputEventsKeyDown;
}

Expand Down
40 changes: 34 additions & 6 deletions Project-Aurora/Project-Aurora/Modules/Inputs/InputEvents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@ private nint Hook(IntPtr hwnd, uint msg, IntPtr wparam, IntPtr lparam)
/// <returns>if input should be interrupted or not</returns>
private bool DeviceOnKeyboardInput(RawKeyboard keyboardData)
{
if (HasNoListener())
{
return false;
}

try
{
var flags = keyboardData.Flags;
Expand All @@ -116,13 +121,9 @@ private bool DeviceOnKeyboardInput(RawKeyboard keyboardData)

var down = (flags & RawKeyboardFlags.Up) == 0;
SetModifierKeys(key, down);
if (down)
{
_pressedKeySequence.Add(key);
}
else
if (!ProcessKeyList(down, key))
{
_pressedKeySequence.RemoveAll(k => k == key);
return false;
}

PressedKeys = _pressedKeySequence.ToArray();
Expand All @@ -146,6 +147,33 @@ private bool DeviceOnKeyboardInput(RawKeyboard keyboardData)
}
}

private bool HasNoListener()
{
var noKeyDownListeners = KeyDown == null || KeyDown.GetInvocationList().Length == 0;
var noKeyUpListeners = KeyUp == null || KeyUp?.GetInvocationList().Length == 0;
return noKeyDownListeners && noKeyUpListeners;
}

private bool ProcessKeyList(bool down, Keys key)
{
if (down)
{
if (_pressedKeySequence.Contains(key))
{
// this key is already processed
return false;
}
_pressedKeySequence.Add(key);
}
else
{
var removed = _pressedKeySequence.Remove(key);
return removed; // return if key is removed
}

return true;
}

private void SetModifierKeys(Keys key, bool down)
{
switch (key)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public sealed class KeyRecorder : IDisposable
private readonly IInputEvents _inputEvents;
private string _recordingType = "";
private bool _isSingleKey;
private List<DeviceKeys> _recordedKeys = new();
private List<DeviceKeys> _recordedKeys = [];
public delegate void RecordingFinishedHandler(DeviceKeys[] resultingKeys);
public event RecordingFinishedHandler? FinishedRecording;

Expand Down

0 comments on commit 8d999c8

Please sign in to comment.