Skip to content

GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.

bug(infra): prevent keybinding from firing when excess modifier keys are pressed (#86)

Albert Gouwsb7d6de92a632
diff --git a/GlazeWM.Infrastructure/WindowsApi/KeybindingService.cs b/GlazeWM.Infrastructure/WindowsApi/KeybindingService.cs
index 8edd074a..2c4ab0d1 100644
--- a/GlazeWM.Infrastructure/WindowsApi/KeybindingService.cs
+++ b/GlazeWM.Infrastructure/WindowsApi/KeybindingService.cs
@@ -31,6 +31,15 @@ namespace GlazeWM.Infrastructure.WindowsApi
/// </summary>
private readonly Dictionary<Keys, List<Keybinding>> _keybindingsByTriggerKey = new();
+ private readonly Keys[] _modifierKeys = new Keys[] {
+ Keys.LControlKey,
+ Keys.RControlKey,
+ Keys.LMenu,
+ Keys.RMenu,
+ Keys.LShiftKey,
+ Keys.RShiftKey
+ };
+
public void Start()
{
var thread = new Thread(() => CreateKeybindingHook())
@@ -120,6 +129,25 @@ namespace GlazeWM.Infrastructure.WindowsApi
if (longestKeybinding == null)
return CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
+ // Get modifier keys that aren't part of the key combination.
+ var modifierKeysToReject = _modifierKeys.Where(
+ (modifierKey) =>
+ !longestKeybinding.KeyCombination.Contains(modifierKey) &&
+ !longestKeybinding.KeyCombination.Contains(GetGenericKey(modifierKey))
+ );
+
+ var hasModifierKeysToReject = modifierKeysToReject.Any((modifierKey) =>
+ cachedKeyStates.ContainsKey(modifierKey)
+ ? cachedKeyStates[modifierKey]
+ : IsKeyDown(modifierKey)
+ );
+
+ // This makes sure that if you press Control+Alt+1, and you have a keybinding of Alt+1, that
+ // it doesn't fire. Even though that all the keys satisfy it, the event has too many keys,
+ // so it shouldn't fire.
+ if (hasModifierKeysToReject)
+ return CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
+
// Invoke the matched keybinding.
longestKeybinding.KeybindingProc();
@@ -127,6 +155,17 @@ namespace GlazeWM.Infrastructure.WindowsApi
return new IntPtr(1);
}
+ private static Keys GetGenericKey(Keys key)
+ {
+ return key switch
+ {
+ Keys.LMenu or Keys.RMenu => Keys.Alt,
+ Keys.LShiftKey or Keys.RShiftKey => Keys.Shift,
+ Keys.LControlKey or Keys.RControlKey => Keys.Control,
+ _ => key,
+ };
+ }
+
/// <summary>
/// Get whether the given key is down. Check alternate versions of modifier keys.
/// </summary>