2011-05-21 3 views
3

Je suis en train d'envoyer entrer la clé d'une application de fond comme celui-ci:Envoi des frappes CGEvents aux applications fond

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

Il ne fonctionne pas, je pense qu'il est parce que l'application doit être le plus l'application avant de recevoir les frappes ? Ai-je raison? Si oui, y a-t-il un moyen pour que je puisse envoyer cet événement sans que l'application soit active en premier? Si non, alors qu'est-ce que je fais mal? Merci.

Répondre

3

Les applications en arrière-plan n'agissent pas sur les événements clés. Vous avez deux options pour que votre application les gère lorsqu'elle est en arrière-plan: Event Taps et +[NSEvent addLocalMonitorForEventsMatchingMask:]. L'option NSEvent est assez facile:

// 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]; 

mais vous êtes déjà monkeying autour de robinets d'événements, de sorte que vous pouvez juste vouloir aller dans cette voie.

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

Le rappel est simple. Voir Callbacks dans la référence Event Services pour plus d'informations.

Questions connexes