在重新显示窗口后,不会调用NSWindow windowDidResignKey

时间:2011-07-18 18:16:01

标签: objective-c cocoa nswindow

我有一个自定义的NSWindow子类,用户可以通过单击按钮来切换显示。我还希望窗口在窗口重新启动按键状态时消失(例如,用户点击窗口外)。

我有一个实现windowDidResignKey:的委托,但我发现只有在窗口第一次调用密钥时才会调用此委托方法。

以下是我切换窗口显示的方法(通过用户操作或windowDidResignKey):

- (void) toggleWindowAtPoint:(NSPoint)point
{
    // Attach/detach window.
    if (!attachedWindow) 
    {
        attachedWindow = [[CustomWindow alloc] attachedToPoint:point];
        attachedWindow.delegate = self;
        [attachedWindow setLevel:NSMainMenuWindowLevel+1];  // show window in front of all other apps on desktop
        [attachedWindow makeKeyAndOrderFront:self];
    } 
    else 
    {
        attachedWindow.delegate = nil;
        [attachedWindow orderOut:self];
        [attachedWindow release];
        attachedWindow = nil;
    }    
}

这是我对windowDidResignKey的实现:

- (void) windowDidResignKey:(NSNotification *)note
{
    [self toggleWindowAtPoint:NSMakePoint(0, 0)];
}

我发现第一次显示自定义窗口时,会调用windowDidResignKey:。每次在此之后重新显示自定义窗口时,都不会调用windowDidResignKey:

3 个答案:

答案 0 :(得分:2)

问题在于,在某些情况下,调用[attachedWindow makeKeyAndOrderFront:self]后,自定义窗口实际上并未成为关键窗口。

我通过在重新创建窗口之前添加以下行来修复此问题:

[[NSApplication sharedApplication] activateIgnoringOtherApps:YES];

在上面的代码段的上下文中:

- (void) toggleWindowAtPoint:(NSPoint)point
{
   // Attach/detach window.
   if (!attachedWindow) 
   {
      [[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
      attachedWindow = [[CustomWindow alloc] attachedToPoint:point];
      ....

答案 1 :(得分:0)

您是否尝试在切换方法中调用[attachedWindow makeFirstResponder:attachedWindow]?

答案 2 :(得分:0)

如果要在不使用activateIgnoringOtherApps:的情况下激活窗口,则应使用带有NSNonactivatingPanelMask的NSPanel:

[[CustomPanel alloc] 
        initWithContentRect: NSZeroRect 
                  styleMask: NSNonactivatingPanelMask 
                    backing: NSBackingStoreBuffered 
                      defer: NO];