让NSAlert成为最顶层的窗口?

sud*_*-rf 9 macos cocoa objective-c nsalert

我在我的应用程序中创建了主窗口以进行这些设置:

[self setLevel:kCGDesktopWindowLevel + 1];
[self setCollectionBehavior:
     (NSWindowCollectionBehaviorCanJoinAllSpaces | 
      NSWindowCollectionBehaviorStationary | 
      NSWindowCollectionBehaviorIgnoresCycle)];
Run Code Online (Sandbox Code Playgroud)

这是一个非常自定义的窗口,可以在桌面上方浮动.

另外,它是一个菜单栏应用程序(LSUIElement).

好吧,所以如果出现问题,我需要显示警报.我是这样做的:

NSAlert *alert = [NSAlert alertWithMessageText:@"" 
                                 defaultButton:@"" 
                               alternateButton:@"" 
                                   otherButton:@"" 
                     informativeTextWithFormat:@""];
[alert runModal];
Run Code Online (Sandbox Code Playgroud)

我当然填写了按钮和其他文字.

这是我的问题:当我的应用程序当前不是关键应用程序,并且弹出此警报时,它不是关键窗口.像这样:

在此输入图像描述

看看窗口是如何选择的?有没有办法改变我的整个应用程序窗口级别?谢谢!

sku*_*kue 10

您是否尝试在显示警报的代码中激活您的应用程序?

[[NSRunningApplication currentApplication] activateWithOptions:0];
Run Code Online (Sandbox Code Playgroud)

如果传递0不起作用,您可以NSApplicationActivateIgnoringOtherApps作为选项传递,但除非确实有必要,Apple建议不要使用它(请参阅NSRunningApplication的文档).


更新:您在运行警报之前已激活.这对我来说适用于LSUIElement设置的新应用:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    NSAlert *alert = [NSAlert alertWithMessageText: @"Blah"
                                     defaultButton: @"Blah"
                                   alternateButton: @"Blah"
                                       otherButton: @"Blah"
                         informativeTextWithFormat: @"Blah"];

    [[NSRunningApplication currentApplication] activateWithOptions:NSApplicationActivateIgnoringOtherApps];
    [alert runModal];
}
Run Code Online (Sandbox Code Playgroud)

  • `[NSApp activateIgnoringOtherApps:YES]`更短 (3认同)