I'm searching for a way to simulate keystrokes in OSX. I found another solution (Simulate keypress for system wide hotkeys) using Objective-C, but i need to do it with Swift. How can i adapt CGEventCreateKeyboardEvent?
相关问题
- “Zero out” sensitive String data in Swift
- SwiftUI: UIImage (QRCode) does not load after call
- Get the NSRange for the visible text after scroll
- UIPanGestureRecognizer is not working in iOS 13
- What does a Firebase observer actually do?
相关文章
- Using if let syntax in switch statement
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
- Is there a Github markdown language identifier for
- How can I vertically align my status bar item text
- Adding TapGestureRecognizer to UILabel in Swift
- Attempt to present UIAlertController on View Contr
- Swift - Snapshotting a view that has not been rend
I made this for a Swift 4 project, don't forget that App sandboxing will not allow an app to send keystrokes like this so it'll need to be turned off. This means your app would prohibited from the AppStore.
Working with Swift 3
Swift 3
For me the hexadecimal key values like: 0x124 didn't work, but simple UInt 124 did the trick!
A nice collection of keycodes can be found here! This copy-paste code snippet simulates a right arrow keypress. Change the key number for whatever you want to simulate:
Update: It doesn't work under macOS Mojave.
The code on that linked answer is fairly readily convertible to Swift code, however there are a handful of gotchas you will need to take care of along the way:
CGEventSourceCreate
takes aCGEventSourceStateID
, which is a typealiase for aUInt32
, but the constants such askCGEventSourceStateHIDSystemState
are defined asInt
, so you’ll have to cast them i.e.CGEventSourceStateID(kCGEventSourceStateHIDSystemState)
. Likewise withCGEventFlags
.CGEventSourceCreate
andCGEventCreateKeyboardEvent
return anUnmanaged<CGEventSource>
(orUnmanaged<CGEvent>
). The auto-generated Swift API for Core Graphics doesn’t know whether the returned objects need to be released by you or not so you need to check the API docs for these calls and then usetakeRetainedValue()
ortakeUnretainedValue()
accordingly on the returned value, to convert them into the underlying type you want to work with.Finally, they return implicitly unwrapped optionals, so you’ll need to decide if you want to check for nils or just live with the excitement of runtime explosions if they ever return one.
Given all that it’s pretty simple to turn the Objective-C in that answer demonstrating pressing Cmd-Space to Swift, I just tried pasting this into a scratch app and it worked fine:
(though I haven't checked the API docs for whether the retain is the correct thing to do or not)