开发者

How to get key value with Cocoa, regardless of focus on window or not

I want to get key va开发者_如何学JAVAlue with Cocoa when do not focus on window. If you know it, please teach me.


If I understand the question, you want to know when a key is pressed, even though your app/window is not the frontmost window?

If that's the case, you're looking at either using +[NSEvent addGlobalMonitorForEventsMatchingMask:handler:] (10.6+ only) or using a CGEventTap.


To use either addGlobalMonitorForEventsMatchingMask or CGEventTap, your application will need to be run as root. I've not been able to make the NSEvent method work for me, but the CGEventTap worked fined as root.

The advantages of the CGEventTap method are:

  • You receive all events, even those of you own application. (The other method doesn't send you your own events.)
  • You can tap events at various levels (before the window server, before the session server, etc.)
  • You can modify the events if desired.


I recently asked this question and used addGlobalMonitorForEventsMatchingMask, just as Dave Delong suggests, pointed out to me by @NSGod.

I had trouble figuring out the block syntax, though, so I'll quote from the code I posted to that answer:

      // register for keys throughout the device...
   [NSEvent addGlobalMonitorForEventsMatchingMask:NSKeyDownMask handler:^(struct NSEvent *event){

    NSString *chars = [[event characters] lowercaseString];
    unichar character = [chars characterAtIndex:0];

    NSLog(@"keydown globally! Which key? This key: %c", character);

    }];

The thing to keep in mind with blocks is that they are supplied directly to the method call. I have a more thorough description appended to my own question, but if you follow the above syntax and think of the block as a kind of 'inline delegate method' you should do just fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜