2011-05-21 60 views
3

我想送回車鍵一個後臺程序是這樣的:發送CGEvents擊鍵後臺應用

CGEventRef a = CGEventCreateKeyboardEvent(eventSource, 36, true); 
CGEventRef b = CGEventCreateKeyboardEvent(eventSource, 36, false); 
CGEventPostToPSN(&psn, a); 
CGEventPostToPSN(&psn, b); 

它不工作,我認爲這是因爲應用程序必須是最前面的應用接收按鍵?我對嗎?如果是這樣,那麼無論如何,我可以發送此事件而無需首先激活該應用程序?如果不是,那麼我做錯了什麼? 謝謝。

回答

3

背景中的應用程序不會對關鍵事件起作用。您有兩種選擇讓您的應用在後臺處理:Event Taps+[NSEvent addLocalMonitorForEventsMatchingMask:]。該NSEvent選項是很容易的:

// A block callback to handle the events 
NSEvent * (^monitorHandler)(NSEvent *); 
monitorHandler = ^NSEvent * (NSEvent * theEvent){ 
    NSLog(@"Got a keyDown: %d", [theEvent keyCode]); 
    // The block can return the same event, a different 
    // event, or nil, depending on how you want it to be 
    // handled later. In this case, being in the background, 
    // there won't be any handling regardless. 
    return theEvent; 
}; 

// Creates an object that we don't own but must keep track of to 
// remove later (see docs). Here, it is placed in an ivar. 
monitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask 
               handler:monitorHandler]; 

但你已經與周圍的水龍頭事件瞎搞,所以你可能只想走這條路。

// Creates an object that must be CFRelease'd when we're done 
CFMachPortRef tap = CGEventTapCreateForPSN(myOwnPSN, 
             kCGTailAppendEventTap, 
             kCGEventTapOptionDefault, 
             kCGEventKeyDown, 
             myEventTapCallback, 
             NULL); 

該回調很簡單。有關信息,請參閱Event Services參考中的Callbacks