-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathKeyUtils.swift
More file actions
45 lines (37 loc) · 1.19 KB
/
KeyUtils.swift
File metadata and controls
45 lines (37 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import CoreGraphics
import Foundation
func simulateJapaneseKanaKeyPress(waitTimeMs: Int) {
// Key code for japanese_kana on JIS keyboard
let keyCode: CGKeyCode = 104
// Create a keyboard event source
guard let eventSource = CGEventSource(stateID: .hidSystemState) else {
print("Failed to create event source")
return
}
// Simulate key down event
guard let keyDownEvent = CGEvent(
keyboardEventSource: eventSource,
virtualKey: keyCode,
keyDown: true
) else {
print("Failed to create key down event")
return
}
// Simulate key up event
guard let keyUpEvent = CGEvent(
keyboardEventSource: eventSource,
virtualKey: keyCode,
keyDown: false
) else {
print("Failed to create key up event")
return
}
// Post the key down event
keyDownEvent.post(tap: .cghidEventTap)
// Small delay to ensure the key down is processed before key up
let waitTime = waitTimeMs < 0 ? 50 : waitTimeMs
let waitTimeSeconds = Double(waitTime) / 1000.0
Thread.sleep(forTimeInterval: waitTimeSeconds)
// Post the key up event
keyUpEvent.post(tap: .cghidEventTap)
}