I want to get key value with Cocoa when do not focus on window. If you know it, please teach me.
-
I'm not sure how to do this in cocoa, but you'll have to query the keyboard directly. If you do not have focus, the keyboard keystroke messages won't be sent to you, unless you have a promiscuous mode of message interception. – EnabrenTane Jan 05 '11 at 22:55
-
OSX 10.6 allows you to register for keyboard events globally -- see Dave DeLong's answer and mine. – Chris Ladd Jan 21 '11 at 18:38
3 Answers
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
.

- 242,470
- 58
- 448
- 498
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.

- 31
- 1
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.

- 1
- 1

- 2,795
- 1
- 29
- 22