且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-01 17:00:13

您可以使用 CGEventPostToPSN 来实现.此示例在后台时将"Q"向下键/向上键发送到TextEdit.

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