Shanti K
Shanti K

Reputation: 2918

Executing Keyboard Events from Daemon in Mac using CFEvents

I have the following code in a Daemon (Root Process) which simulates Keyboard events in OSX.

CGEventRef keyEvent = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)keyCode, keyDown);
CGEventPost(kCGHIDEventTap, keyEvent);
CFRelease(keyEvent);

When I am in User1 and the daemon is loaded into the Root context, the keyboard events get simulated fine. When i switch to User2, all the events except the Shift key get executed successfully. For some reason, the keyboard event for Shift key is executed in User1 though i am currently logged in to User2.

I have also tried with using the shift mask:

CGEventRef  event1 = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)keyCode, true);//'z' keydown event
CGEventSetFlags(event1, kCGEventFlagMaskShift);//set shift key down for above event
CGEventPost(kCGHIDEventTap, event1);//post event
CFRelease(event1);

This too works fine in the User1. When i switch to user2, and perform key events as shown above, it performs these events in the front most application in User1. The events for Shift key press or any key press with Shift mask go to the User1, and not the currently logged in User

Is there anyway I can ensure that the key board events are executed in the logged in user?

Upvotes: 3

Views: 250

Answers (1)

Michael Dautermann
Michael Dautermann

Reputation: 89509

After you create your keyEvent, set the modifier flags before posting it:

CGEventFlags flags = kCGEventFlagMaskShift;
CGEventSetFlags(keyEvent, modifierFlags);

Upvotes: 1

Related Questions