문제

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?

도움이 되었습니까?

해결책

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:.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top