Simulating OPT (or other modifiers) with `CGEventCreateKeyboardEvent` `CGEventSetFlags` `CGEventPost`

谁都会走 提交于 2019-12-13 03:38:31

问题


I'm trying to simulate key-down and key-up for the OPT key on macOS.

    CGEventSourceRef source = CGEventSourceCreate( kCGEventSourceStateHIDSystemState );
    CGEventRef ev = CGEventCreateKeyboardEvent( source, keycode, is_down );
    // CGEventSetFlags( ev, NSEventModifierFlagOption );
    CGEventPost( kCGHIDEventTap, ev );
    CFRelease( ev );

... with is_down = true then false.

It works in most situations.

However, It does not match the native behaviour if I perform the following test:

I hover over a keyword (say CGEventRef) in XCode, and +OPT on my keyboard. The keyword backlights blue and the cursor becomes a ?. And if I move the mouse around the rectangle it stays highlighted.

Now I try exactly the same experiment with my synthetic OPT. Again the keyword backlights blue. But there is no cursor ?. And the moment I move my mouse the highlighting disappears.

So there is some very subtle distinction here.

What is the Operating System doing that I am not?

I considered that the mouse-move events might need to be informed that OPT modifier is down. So I created an EventTap to sort that. But still I cannot get the cursor to change.

I know that when a natural +OPT event occurs, a NSEventTypeFlagsChanged event fires. And in my simulated +OPT, no such event fires.

So I suppose it's possible that Xcode is tapping this event.

So how to fire an NSEventTypeFlagsChanged event?

来源:https://stackoverflow.com/questions/58673983/simulating-opt-or-other-modifiers-with-cgeventcreatekeyboardevent-cgeventse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!