Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mac: Send key event to background Window

Tags:

macos

keyboard

I am using Quartz Event Services to send key commands to applications, but it appears that it was designed to only sent to the front-most window for each application. In Windows, you can send a key event to a specific window using the SendKeys API.

I know that you can target specific windows using AppleScripts and send key commands without bringing that window to the foreground for that application, but wondering if there is a way to do this programmatically in C/Objective-C. Seems like the functionality is there, but cannot find any documentation for an API.


****Note**: Neither window is a window created by my application, and it may be that both applications are owned by the same process*


Example: Below, I can send commands to the foreground window (The Up-Goer Five Text Editor), but not to the blue background window (Standard Text editor) without first bringing the blue window to the front. You would think that Window switching programmatically is fast, but it is actually very noticeable. How do I do this, as to copy keystrokes between windows?

enter image description here

like image 583
Jason Avatar asked Feb 19 '14 11:02

Jason


1 Answers

You can do it with CGEventPostToPSN. This sample send 'Q' key down/key up to TextEdit, while it's in background.

// action when a button of the foreground application is clicked
// send 'Q' key down/key up to TextEdit
-(IBAction)sendQKeyEventToTextEdit:(id)sender
{
    // check if textEdit is running
     if ([[NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.TextEdit"] count])
    {
        // get TextEdit.app pid
        pid_t pid = [(NSRunningApplication*)[[NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.TextEdit"] objectAtIndex:0] processIdentifier];

        CGEventRef qKeyUp;
        CGEventRef qKeyDown;
        ProcessSerialNumber psn;

        // get TextEdit.app PSN
        OSStatus err = GetProcessForPID(pid, &psn);
        if (err == noErr)
        {
            // see HIToolbox/Events.h for key codes
            qKeyDown = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)0x0C, true);
            qKeyUp = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)0x0C, false);

            CGEventPostToPSN(&psn, qKeyDown);
            CGEventPostToPSN(&psn, qKeyUp);

            CFRelease(qKeyDown);
            CFRelease(qKeyUp);
        }
    }
}
like image 118
Emmanuel Avatar answered Nov 06 '22 04:11

Emmanuel