Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CGEventPost - hold a key (shift)

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.

like image 438
user2604306 Avatar asked Jul 21 '13 14:07

user2604306


1 Answers

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.

like image 128
aristidesfl Avatar answered Oct 17 '22 01:10

aristidesfl