简体   繁体   中英

Unexpected NSWindow becomes key window

I have a main NSWindow in my application with a button. When the button is pressed it does something like the following:

NSWindow *newWindow = [NSWindow initWithContentRect:[screen frame] styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO];
[newWindow makeKeyAndOrderFront:self];
[self.previousWindow orderOut:self];

This works fine most of the time, but if I have a second window open (called the "other" window) and on another screen before I press the button, the following happens:

  1. My new window is created, made key, and ordered front.
  2. The previous window is ordered out.
  3. The "other" window is made key.

Looking at the stack trace I can see that the "other" window is being made key as the result of some notification being sent. This is not in my app so must be a Cocoa thing. Given that I am explicitly saying which window should be the key window, why is Cocoa ignoring that and changing it to something else? Is there a better way to do what I want?

This doesn't occur if all the windows are on the same screen.

Somewhat predictably this was fixed by swapping the order of the last two lines:

[self.previousWindow orderOut:self];
[newWindow makeKeyAndOrderFront:self];

I initially had concerns that doing things in this order in an application where applicationShouldTerminateAfterLastWindowClosed returns YES might cause the application to close prematurely but this does not seem to be the case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM