2011-07-18 51 views
2

我有一個自定義的NSWindow子類,用戶可以通過點擊一個按鈕來切換顯示。我還想讓窗口在關閉狀態時(例如用戶在窗口外面點擊)消失。NSWindow windowDidResignKey在重新顯示窗口後沒有被調用

我有一個委託實現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:都不會被調用。

回答

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]; 
     .... 
0

您是否嘗試過在切換方法中調用[attachedWindow makeFirstResponder:attachedWindow]?

+0

感謝sugg雖然這並不適合我。 – figelwump

0

如果要激活窗口而不

我加入以下行之前重新創建窗口固定這使用activateIgnoringOtherApps:你應該使用NSPanel與NSNonactivatingPanelMask:

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