问题
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