你可以用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);
}
}
}
增加了一個說明性的例子。希望將事件發送到流程的特定窗口而不是特定的流程。 – Jason
@Jason您是否創建了必須接收事件的應用程序,或者是否想要使用任何應用程序? – Emmanuel
任何應用程序 – Jason