This repository has been archived by the owner on Sep 9, 2020. It is now read-only.
/
KeyboardSimulator.swift
66 lines (56 loc) · 1.79 KB
/
KeyboardSimulator.swift
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//
// KeyboardSimulator.swift
// KeyboardSimulator
//
// Created by Naruki Chigira on 2018/07/03.
// Copyright © 2018年 Timers-inc. All rights reserved.
//
import Foundation
class KeyboardSimulator {
/// キーダウン
static func down(key: CGKeyCode) {
DispatchQueue.main.async {
let source = CGEventSource(stateID: CGEventSourceStateID.hidSystemState)
let event = CGEvent(keyboardEventSource: source, virtualKey: key, keyDown: true)
event?.post(tap: CGEventTapLocation.cghidEventTap)
}
}
/// キーアップ
static func up(key: CGKeyCode) {
DispatchQueue.main.async {
let source = CGEventSource(stateID: CGEventSourceStateID.hidSystemState)
let event = CGEvent(keyboardEventSource: source, virtualKey: key, keyDown: false)
event?.post(tap: CGEventTapLocation.cghidEventTap)
}
}
/// クリック
static func click(key: CGKeyCode) {
down(key: key)
up(key: key)
}
/// 他のキーを押しつつクリック
static func click(key: CGKeyCode, keepDowns: [CGKeyCode]) {
for keepDown in keepDowns {
down(key: keepDown)
}
waitEvent()
click(key: key)
for keepDown in keepDowns {
up(key: keepDown)
}
waitEvent()
}
/// キーイベントのシミュレート
static func simulate(event: KeyEvent) {
click(key: event.code, keepDowns: event.keepDowns)
}
/// 一連のキーイベントのシミュレート
static func simulate(events: [KeyEvent]) {
for event in events {
simulate(event: event)
}
}
private static func waitEvent() {
Thread.sleep(forTimeInterval: 1.0e-2)
}
}