Mac: Send key event to background Window

為{幸葍}努か 提交于 2021-02-18 06:05:18

问题


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


回答1:


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);
        }
    }
}


来源:https://stackoverflow.com/questions/21878987/mac-send-key-event-to-background-window

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