Jorge Vega Sánchez
Jorge Vega Sánchez

Reputation: 7590

Capture modifier keys pressing ( Control, Alt, Shift o CMD )

I know how to detect key pressing. All keys except Control, Alt, Shift and CMD.

How can i detect when this keys are being pressed.

Thanks in advance.

Upvotes: 6

Views: 4489

Answers (2)

Laurent
Laurent

Reputation: 41

in

- (void) flagsChanged: (NSEvent *)theEvent

[theEvent keyCode] gives a number for CRTL, SHIFT, ALT, etc, so you only need to toggle a variable for those modifiers, set to 0 at start.

if you use OpenGL you may need to set:

-(BOOL) canBecomeKeyWindow

Upvotes: 4

goetz
goetz

Reputation: 916

If you want to detect these keys in something like a NSView object, have a look at the NSResponder class. When you overwrite a NSView class (or one of its sublcasses), you can overwrite keyDown:(NSEvent *)theEvent(Apple Documentation). When you call [theEvent modifierFlags], a NSUInteger bitfield is returned, which you can then evaluate.

For instance, with

if ([theEvent modifierFlags] & NSCommandKeyMask) {
   ...
}
you can check if the Command key is pressed.

See Apple's Cocoa Event-handling Guide, especially the section "Handling Key Events" for more information.

Upvotes: 4

Related Questions