在macOS Sierra中使用Quartz事件模拟击键 [英] Simulate keystrokes with Quartz events in macOS Sierra
问题描述
我正在模拟macOS中的击键,并将其发送到活动的应用程序。我正在按照 https://stackoverflow.com/a/27487493/5600424 的方式进行操作,但是在Swift 3中。例如,发送 a:
I am simulating keystrokes in macOS, and sending them to the active application. I am doing it along the lines of https://stackoverflow.com/a/27487493/5600424 but in Swift 3. For example, to send an 'a':
let eventSource = CGEventSource(stateID: CGEventSourceStateID.hidSystemState)
let key: CGKeyCode = 0 // virtual key for 'a'
let eventDown = CGEvent(keyboardEventSource: eventSource, virtualKey: key, keyDown: true)
let eventUp = CGEvent(keyboardEventSource: eventSource, virtualKey: key, keyDown: false)
let location = CGEventTapLocation.cghidEventTap
eventDown.post(tap: location)
eventUp.post(tap: location)
这在OSX El Capitan(Swift 3,Xcode 8.0)上运行良好,但是在更新到macOs Sierra后停止了工作。应用程序本身处于活动状态时仍会收到按键,但是当其他应用程序处于活动状态时,事件似乎丢失了。我试图弄清楚发生了什么事而没有成功,并且该文档也无济于事。会得到任何帮助,谢谢!
This was working fine on OSX El Capitan (Swift 3, Xcode 8.0), but it stopped working after updating to macOs Sierra. The application itself still receives the keystroke when it's active, however when a different application is active the events seem lost. I have tried to figure out what is happening without success, and the documentation does not help. Any help would be appreciated, thanks!
推荐答案
问题中引用的代码正确运行,并且升级时其行为未更改从El Capitan到Sierra,与所声称的相反。
The code quoted in the question works correctly, and its behavior has not changed when upgrading from El Capitan to Sierra, contrary to what claimed.
其他应用程序未接收到击键,因为一旦应用程序进入后台,负责发送键盘的功能出于独立原因,不再调用具有上述代码的事件。
The keystrokes where not received by other applications because once the application was in the background, the function responsible for sending the keyboard events with the above code was not called anymore, for independent reasons.
这篇关于在macOS Sierra中使用Quartz事件模拟击键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!