-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeyboardSimulator.swift
More file actions
20 lines (17 loc) · 930 Bytes
/
Copy pathKeyboardSimulator.swift
File metadata and controls
20 lines (17 loc) · 930 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import Cocoa
/// Posts synthetic keystrokes via CGEvent. Used to drive Cmd+A / Cmd+C / Cmd+V
/// against the currently focused text field of whatever app holds keyboard focus.
enum KeyboardSimulator {
/// Press-and-release `key` while holding `modifiers`.
/// Posts events to the HID event tap so they're indistinguishable from physical input.
static func press(_ key: KeyCode, modifiers: CGEventFlags = []) {
// A nil event source produces the most "physical" event — many apps that filter on
// event source treat tap-injected nil-source events as user input.
let down = CGEvent(keyboardEventSource: nil, virtualKey: key.rawValue, keyDown: true)
down?.flags = modifiers
down?.post(tap: .cghidEventTap)
let up = CGEvent(keyboardEventSource: nil, virtualKey: key.rawValue, keyDown: false)
up?.flags = modifiers
up?.post(tap: .cghidEventTap)
}
}