Pergunta

I subclassed NSWindows and implemented the keyDown: and keyUp: method like this:

- (void)keyDown:(NSEvent*)event
{
    NSLog(@"Down: '%@'", [event characters]);
    [super keyDown:event];
}

- (void)keyUp:(NSEvent*)event
{
    NSLog(@"Up: '%@'", [event characters]);
    [super keyUp:event];
}

If I pressed "W" key, it prints both my "Down" and "Up" correctly. But If I pressed Command+W combination, It prints ONLY the "Down" message, and windows' close action was not triggered. How should I do?

Foi útil?

Solução

Command-W is typically the key equivalent of a menu item. It is handled by the menu when it is told to -performKeyEquivalent:. The menu item sends its action method to its target. The action method is typically -performClose: and the target is usually the first responder.

So, the normal processing of Command-W does not use the window's -keyDown: or -keyUp: at all.

If you want to control whether the window closes, have the window delegate implement -windowShouldClose:. If you want to be notified when the window is about to close, implement -windowWillClose: in the window delegate or observe the NSWindowWillCloseNotification notification.

Regarding keyboard handling, a quirk of -[NSApplication sendEvent:] is that it just doesn't dispatch any key up event if the Command key was down. If for some reason you really need to see the key up event, you'll have to implement a custom subclass of NSApplication, configure your Info.plist to make sure it's used, and implement an override of -sendEvent:.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top