https://qiita.com/uasi/items/546600ca60c1b131012c
https://qiita.com/asus4/items/a2517aed8dc7e4773c34
http://sonson.jp/blog/2006/04/04/macosx/
キーボードとマウス制御について色々を参考になりましたが、コードはObjective-Cばかりなので、今回はswiftの書き方についてまとめます。
#キーを押す
//キーダウン
func keyboardKeyDown(key: CGKeyCode) {
let source = CGEventSource(stateID: CGEventSourceStateID.hidSystemState)
let event = CGEvent(keyboardEventSource: source, virtualKey: key, keyDown: true)
event?.post(tap: CGEventTapLocation.cghidEventTap)
print("key \(key) is down")
}
//キーアップ
func keyboardKeyUp(key: CGKeyCode) {
let source = CGEventSource(stateID: CGEventSourceStateID.hidSystemState)
let event = CGEvent(keyboardEventSource: source, virtualKey: key, keyDown: false)
event?.post(tap: CGEventTapLocation.cghidEventTap)
print("key \(key) is released")
}
定義したらこんな風にすぐに使えます。
keyboardKeyDown(key: 0x60) //0x60はF5キーのコード
keyboardKeyUp(key: 0x60)
ちなみにmacの英字鍵盤のCGkeyCodeはこちら:
macos - Where can I find a list of Mac virtual key codes? - Stack Overflow
##コマンドなどを入れる場合は
let cmd_c_D = CGEventCreateKeyboardEvent(nil, 0x08, true); //0x08はCキー command+cを押す
CGEventSetFlags(cmd_c_D, CGEventFlags.MaskCommand);
CGEventPost(CGEventTapLocation.CGHIDEventTap, cmd-c-D);
let cmd_c_U = CGEventCreateKeyboardEvent(nil, 0x08, false); // command+cを離す
CGEventSetFlags(cmd_c_U, CGEventFlags.MaskCommand);
CGEventPost(CGEventTapLocation.CGHIDEventTap, cmd_c_U);
#マウスのクリック制御
//左のクリックダウン
guard let mouseDown = CGEvent(mouseEventSource: nil,
mouseType: .leftMouseDown,
mouseCursorPosition: CGPoint(x: 200, y: 300),
mouseButton: .left
) else {return}
mouseDown?.post(tap: .cghidEventTap)
//左のクリックアップ
guard let mouseUp = CGEvent(mouseEventSource: nil,
mouseType: .leftMouseUp,
mouseCursorPosition: CGPoint(x: 200, y: 300),
mouseButton: .left
) else {return}
mouseUp?.post(tap: .cghidEventTap)
#マウスの移動
func moveMouse(_ dx:CGFloat , _ dy:CGFloat){
//つい先のマウスの位置を獲得
var mouseLoc = NSEvent.mouseLocation
mouseLoc.y = NSHeight(NSScreen.screens[0].frame) - mouseLoc.y;
//新しい位置の計算
let newLoc = CGPoint(x: mouseLoc.x-CGFloat(dx), y: mouseLoc.y+CGFloat(dy))
print("moving \(dx) \(dy)")
//カーソルの移動
CGDisplayMoveCursorToPoint(0, newLoc)
}