Make NSAlert the topmost window?

I created the main window in my application to have the following settings:

[self setLevel:kCGDesktopWindowLevel + 1]; [self setCollectionBehavior: (NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; 

This is a very customizable window, similar to floats above the desktop.

It is also a menu application ( LSUIElement ).

Ok, so I need to display a warning if something is wrong. Here is how I do it:

 NSAlert *alert = [NSAlert alertWithMessageText:@"" defaultButton:@"" alternateButton:@"" otherButton:@"" informativeTextWithFormat:@""]; [alert runModal]; 

Of course, I typed buttons and other text.

Here is my problem: when my application is not currently a key application and this warning appears, it is not a key window. Like this:

enter image description here

See how the window is not selected? Is there any way around this without changing my app window level? Thanks!

+8
objective-c cocoa macos
source share
2 answers

Have you tried activating your application in code that displays a warning?

 [[NSRunningApplication currentApplication] activateWithOptions:0]; 

If passing 0 does not work, you can pass NSApplicationActivateIgnoringOtherApps as your option, but Apple recommends against it if it is really necessary (see the docs for NSRunningApplication).


Update:. You activate before starting the alert. This works for me in a new application with the LSUIElement suite:

 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { NSAlert *alert = [NSAlert alertWithMessageText: @"Blah" defaultButton: @"Blah" alternateButton: @"Blah" otherButton: @"Blah" informativeTextWithFormat: @"Blah"]; [[NSRunningApplication currentApplication] activateWithOptions:NSApplicationActivateIgnoringOtherApps]; [alert runModal]; } 
+9
source share

If you want to also support 10.5. you can use

 [[NSApplication sharedApplication] activateIgnoringOtherApps:YES]; 
+2
source share

All Articles