Skip to content

Commit

Permalink
Use CGPostKeyboardEvent instead of CGEventPost
Browse files Browse the repository at this point in the history
For certain events (e.g. arrow keys) the modifier mask that is set on
the event (which includes the function key) does not seem to get cleared
on key up, which ruins all future events because their mask contains
those flags even though they shouldn't be active anymore. The deprecated
function doesn't seem to do this so use it for now until I can figure
out what is going on.

Fixes #11. (Or, at least, makes it significantly less annoying.)
  • Loading branch information
saagarjha committed Feb 8, 2024
1 parent f54aefc commit 0e8de40
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions macOS/Events.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,15 @@ actor EventDispatcher {
}

func injectKey(key: Key, down: Bool) {
let event = CGEvent(keyboardEventSource: nil, virtualKey: CGKeyCode(key.macOSCode), keyDown: down)!
event.post(tap: .cghidEventTap)
// FB13590408
if let CGPostKeyboardEvent {
_ = CGPostKeyboardEvent(0, CGKeyCode(key.macOSCode), down ? 1 : 0)
} else {
let event = CGEvent(keyboardEventSource: .init(stateID: .hidSystemState), virtualKey: CGKeyCode(key.macOSCode), keyDown: down)!
event.post(tap: .cghidEventTap)
}
}
}

// This is marked as deprecated and unavailable in Swift. Rude.
let CGPostKeyboardEvent = unsafeBitCast(dlsym(dlopen(nil, RTLD_LAZY), "CGPostKeyboardEvent"), to: (@convention(c) (CGCharCode, CGKeyCode, boolean_t) -> CGError)?.self)

0 comments on commit 0e8de40

Please sign in to comment.