【问题标题】:Make a NSAlert the topmost window?让 NSAlert 成为最顶层的窗口?
【发布时间】:2011-07-13 06:01:39
【问题描述】:

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

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

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

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

好的,所以如果出现问题,我需要显示警报。以下是我的做法:

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

当然我已经填写了按钮和其他文本。

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

看看窗口没有被选中?有没有办法在不改变我的整个应用程序窗口级别的情况下解决这个问题?谢谢!

【问题讨论】:

    标签: objective-c cocoa macos nsalert


    【解决方案1】:

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

    [[NSRunningApplication currentApplication] activateWithOptions:0];
    

    如果传递 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];
    }
    

    【讨论】:

    • 不幸的是,这样做仍然不能解决问题。
    • 你是在runModal调用之前还是之后添加的? runModal 块,因此您必须首先调用 NSRunningApplication 。查看更新的答案。
    • [NSApp activateIgnoringOtherApps:YES] 更短
    • 如果这仍然不适合您,请确保它是就在 [alert runModal]之前的行。
    【解决方案2】:

    如果你也想支持 10.5。你可以使用

    [[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
    

    【讨论】:

      【解决方案3】:

      强制应用程序移动到最前面是一个相当糟糕的主意。 人们可能更愿意使用专用的 NSPanel 属性“floatingPanel”让警报漂浮在所有内容上:

      NSPanel* panel = static_cast<NSPanel*>([alert window]);
      panel.floatingPanel = YES;
      

      【讨论】:

        猜你喜欢
        • 2015-06-08
        • 1970-01-01
        • 2013-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-06
        • 1970-01-01
        相关资源
        最近更新 更多