CGEventPost - hold a key (shift)

为君一笑 提交于 2019-12-06 19:34:47

问题


I'm looking for a way to design a little panel with modifier keys on it (shift, command for example) and have to possibility to click on it like a virtual keyboard.

I'd like it to have this behavior :

  • click on the virtual key (shift).
  • the shift button holds, and keeps being pressed.
  • type something with my standard keyboard.
  • click another time on the virtual shift key to release it.

here is the code I'm using :

CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
CGEventRef shiftKeyDown = CGEventCreateKeyboardEvent(source, (CGKeyCode)56, YES);
CGEventRef shiftKeyUp = CGEventCreateKeyboardEvent(source, (CGKeyCode)56, NO);

CGEventPost(kCGAnnotatedSessionEventTap, shiftKeyDown);
CGEventPost(kCGAnnotatedSessionEventTap, shiftKeyUp);

CFRelease(shiftKeyUp);
CFRelease(shiftKeyDown);
CFRelease(source);

I can't find a way to keep it pressed until I click on it another time. I though "Push On Push Off" Button Cell type was the key but unfortunately no. :-)

any help ?

thanks in advance.


回答1:


A shift key virtually pressed that way, will get released automatically when followed by an event which doesn't contain a shift flag. This seems to be a limitation, or possibly a bug, considering the documentation sort of indicates otherwise: https://developer.apple.com/reference/coregraphics/cgevent/1456564-init#discussion

The only way I found to achieve what you are looking for, is to setup an event listener, and add the shift flag to every event which should be modified by the Shift key.

Example on how to listen to keyboard events: https://stackoverflow.com/a/31898592/1445812 (Swift)

Example on how to had the shift flag to intercepted events:

event?.flags.insert(.maskShift)

Hope this helps. If anyone knows how to do the same without having to add the flags to every event, please do tell.



来源:https://stackoverflow.com/questions/17773225/cgeventpost-hold-a-key-shift

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