I have the following code to send virtual keypresses to a process given its pid
NSRunningApplication* app = [NSRunningApplication
runningApplicationWithProcessIdentifier: pid];
[app activateWithOptions: (NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps)];
event1 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)cg_key_code, true);
event2 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)cg_key_code, false);
CGEventPost(kCGHIDEventTap, event1);
CGEventPost(kCGHIDEventTap, event2);
The process that I wish to send keypresses to promptly comes to the front, as expected. But the problem is, the first keypress is going to the application which was at front before my application came front. When tested, [app isActive]
returns false for the first time. After the first key, everything goes fine.
Why is this happening? Even though I am posting the key event after getting my process to the front.