Skip to content

fix: check current state before toggling on Windows#14

Open
fasuizu-br wants to merge 1 commit intorisoflora:mainfrom
fasuizu-br:fix/set-toggles-instead-of-setting
Open

fix: check current state before toggling on Windows#14
fasuizu-br wants to merge 1 commit intorisoflora:mainfrom
fasuizu-br:fix/set-toggles-instead-of-setting

Conversation

@fasuizu-br
Copy link
Copy Markdown

Summary

Closes #13

The set() method unconditionally sent a key press + release via keybd_event, which always toggled the lock key regardless of the requested state. The state parameter was completely ignored.

This meant:

  • enable() could turn a key OFF if it was already ON
  • disable() could turn a key ON if it was already OFF
  • set(key, Enabled) on an already-enabled key would disable it

Fix

Read the current state via GetKeyState before acting. Only send the toggle key event when the current state differs from the desired one — making set() idempotent, matching the behavior on macOS (IOHIDSetModifierLockState) and Linux (XkbLockModifiers).

Before

fn set(&self, key: LockKeys, state: LockKeyState) -> LockKeyResult {
    unsafe {
        let key = lock_key_to_vkkey!(key) as BYTE;
        keybd_event(key, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0);
        keybd_event(key, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
    }
    Ok(state) // state was never checked
}

After

fn set(&self, key: LockKeys, state: LockKeyState) -> LockKeyResult {
    let current = self.state(key)?;
    if current != state {
        unsafe {
            let key = lock_key_to_vkkey!(key) as BYTE;
            keybd_event(key, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0);
            keybd_event(key, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
        }
    }
    Ok(state)
}

Test plan

  • cargo check passes (macOS — Windows code behind cfg(windows))
  • Manual: on Windows, LockKey::new().enable(CapitalLock) when CapsLock is already ON → stays ON (no toggle)
  • Manual: LockKey::new().disable(CapitalLock) when CapsLock is already OFF → stays OFF (no toggle)

`set()` unconditionally sent a key press+release, which always toggled
the lock key regardless of the requested state. This meant `enable()`
could turn a key OFF if it was already ON, and `disable()` could turn
it ON if already OFF.

Now reads the current state via `GetKeyState` and only sends the toggle
event when the current state differs from the desired one.

Closes risoflora#13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

on Windows (not tested on other versions) set toggles the keybind

1 participant