Mac:将关键事件发送到后台窗口

Jas*_*son 8 keyboard macos

我正在使用Quartz Event Services向应用程序发送关键命令,但似乎它被设计为仅发送到每个应用程序的最前面的窗口.在Windows中,您可以使用SendKeys API将键事件发送到特定窗口.

我知道您可以使用AppleScripts定位特定窗口并发送关键命令,而无需将该窗口带到该应用程序的前台,但想知道是否有办法在C/Objective-C中以编程方式执行此操作.似乎有功能,但无法找到API的任何文档.


****注意**:这两个窗口都不是我的应用程序创建的窗口,可能两个应用程序都归同一个进程所有*


示例:下面,我可以将命令发送到前景窗口(The Up-Goer Five Text Editor),但不能将命令发送到蓝色背景窗口(标准文本编辑器),而不先将蓝色窗口置于前面.你会认为Window编程方式很快,但它实际上非常引人注目.我如何做到这一点,以复制Windows之间的击键?

在此输入图像描述

Emm*_*uel 8

你可以做到CGEventPostToPSN.此示例向下发送'Q'键/键到TextEdit,而它在后台.

// 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Jason 所以,据我所知,没有公共 API 可以将事件发送到另一个进程的特定窗口(除非您自己创建了另一个应用程序并使用 `NSDistributedNotificationCenter` 实现了这个外部事件处理),但您仍然可以使用AppleScript 代码见 [NSAppleScript Class](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/nsapplescript_Class/Reference/Reference.html)。 (2认同)