是否可以在macOS应用程序中观察模拟(非物理)键盘/鼠标事件?
我编写了不同的代码来模拟按键盘按键。
1示例:Swift
let keyDownEvent = CGEvent(keyboardEventSource: CGEventSource(stateID: CGEventSourceStateID.hidSystemState), virtualKey: virtualKey, keyDown: true)
keyDownEvent?.post(tap: CGEventTapLocation.cghidEventTap)
2示例:Obj-c / C ++
-(void)HIDPostAuxKey:(const UInt8)auxKeyCode {
__block NXEventData event;
__block kern_return_t kr;
__block IOGPoint loc = { 0, 0 };
// Key press event
__block UInt32 evtInfo = auxKeyCode << 16 | NX_KEYDOWN << 8;
bzero(&event, sizeof(NXEventData));
event.key.origCharSet = event.key.charSet = NX_ASCIISET;
event.compound.subType = NX_SUBTYPE_AUX_CONTROL_BUTTONS;
event.compound.misc.L[0] = evtInfo;
// event.key.repeat = true;
kr = IOHIDPostEvent( get_event_driver(), NX_SYSDEFINED, loc, &event, kNXEventDataVersion, 0, FALSE );
assert( KERN_SUCCESS == kr );
// Key release event
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 100);
dispatch_after(delay, dispatch_get_main_queue(), ^(void){
evtInfo = auxKeyCode << 16 | NX_KEYUP << 8;
bzero(&event, sizeof(NXEventData));
event.key.origCharSet = event.key.charSet = NX_ASCIISET;
event.compound.subType = NX_SUBTYPE_AUX_CONTROL_BUTTONS;
event.compound.misc.L[0] = evtInfo;
kr = IOHIDPostEvent( get_event_driver(), NX_SYSDEFINED, loc, &event, kNXEventDataVersion, 0, FALSE );
assert( KERN_SUCCESS == kr );
}); }
由于Apple取消了处理键盘按键的访问权限,如果macOS应用程序处于后台,则无法在“设置”中启用辅助功能,例如:
NSEvent.addGlobalMonitorForEvents(matching: [.keyDown, .keyUp]) { (event) in
debugPrint("any key button tapped")
}
现在不起作用。
我发现唯一可行的解决方案是IOKit,低级api https://stackoverflow.com/a/39834889/7141905,即使没有启用应用程序的可访问性,也会监听键盘/鼠标事件。
但这两种方式都不能观察/捕捉模拟键盘按下。它只能观察用户输入的物理事件。 Carbon Framework也不适合我的情况。
有关辅助功能要求的详细信息,请访问:https://github.com/KonsomeJona/OctoMouse#why-is-the-keystrokes-counter-not-working