Created
July 9, 2021 09:39
-
-
Save shunia/ddf39dc706630c82778ce1bd59145e37 to your computer and use it in GitHub Desktop.
MacOS send keystroke to background application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import CoreFoundation | |
// all keycodes: https://gist.github.com/swillits/df648e87016772c7f7e5dbed2b345066 | |
let KeyCode_R: UInt16 = 0x0F; | |
let KeyCode_N: UInt16 = 0x2D; | |
let src = CGEventSource(stateID: CGEventSourceStateID.hidSystemState) | |
let kspd = CGEvent(keyboardEventSource: src, virtualKey: KeyCode_R, keyDown: true) // space-down | |
let kspu = CGEvent(keyboardEventSource: src, virtualKey: KeyCode_R, keyDown: false) // space-up | |
// real PID-s from command 'ps -ax | grep {Application}' - e.g. for example 3 different processes | |
let pids = [ 69885 ]; | |
// send repeat with interval | |
let interval = 5.0; | |
var start = CFAbsoluteTimeGetCurrent(); | |
repeat { | |
if (CFAbsoluteTimeGetCurrent() - start >= interval) { | |
start = CFAbsoluteTimeGetCurrent(); | |
print("sending to pid: ", pids[0]); | |
kspd?.postToPid( pid_t(pids[0]) ); // convert int to pid_t | |
kspu?.postToPid( pid_t(pids[0]) ); | |
} | |
} while (true) | |
// send only once | |
// for i in 0 ..< pids.count { | |
// print("sending to pid: ", pids[i]); | |
// kspd?.postToPid( pid_t(pids[i]) ); // convert int to pid_t | |
// kspu?.postToPid( pid_t(pids[i]) ); | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment