Unexpected NSWindow becomes key window

360 views Asked by At

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.

1

There are 1 answers

0
DanielGibbs On BEST ANSWER

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.