2014-02-19 60 views
7

我正在使用Quartz Event Services嚮應用程序發送鍵盤命令,但似乎它被設計爲僅發送到每個應用程序的最前面的窗口。在Windows中,您可以使用SendKeys API將關鍵事件發送到特定窗口。Mac:將鍵盤事件發送到背景窗口

我知道你可以使用AppleScripts定位特定的窗口併發送鍵盤命令,而不會將該窗口置於該應用程序的前臺,但是想知道是否有方法在C/Objective-C中以編程方式執行此操作。似乎功能在那裏,但找不到API的任何文檔。


****注**:無論是窗口是由我的應用程序創建一個窗口,它可能是這兩個應用程序是由相同的進程所擁有的*


: 下面,我可以將命令發送到前景窗口(Up-Goer五個文本編輯器),但不發送到藍色背景窗口(標準文本編輯器),而無需先將藍色窗口置於前面。你會認爲窗口切換是快速的,但實際上非常明顯。我如何做到這一點,以便在Windows之間複製擊鍵?

enter image description here

回答

6

你可以用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); 
     } 
    } 
} 
+0

增加了一個說明性的例子。希望將事件發送到流程的特定窗口而不是特定的流程。 – Jason

+0

@Jason您是否創建了必須接收事件的應用程序,或者是否想要使用任何應用程序? – Emmanuel

+0

任何應用程序 – Jason

相關問題