objective-c - 弹出菜单定位项 :atLocation:inView: hangs when switching to another application

标签 objective-c macos cocoa menu

我正在开发一个无停靠应用程序(LSUIElement true)。当用户单击相应的 NSStatusItem 或使用键盘快捷键时,应用程序会弹出一个菜单。

我的问题是,每当用户切换到另一个应用程序(使用 ⌘-TAB)而不先关闭菜单时,所有以编程方式弹出菜单的方法都会挂起。我尝试过 popUpMenuPositioningItem:atLocation:inView:popUpContextMenu:withEvent:forView: 以及 NSStatusItem 上的相应方法 (popUpStatusItemMenu: )。

如果用户使用 ESC 键关闭菜单,则一切正常,但如果用户切换到不同的应用程序,则上述方法永远不会返回(它们似乎同步运行,并在菜单关闭时返回)。应用程序不会崩溃,并且有一些技巧可以重新获得控制(调用 exposé,或单击弹出菜单的任何 NSStatusItem)。

如果应用程序具有停靠图标(即将 LSUIElement 设置为 false),问题就会消失。

这是使用键盘快捷键时弹出菜单的代码:

[mainMenu popUpMenuPositioningItem:[mainMenu itemAtIndex:0]
                        atLocation:[NSEvent mouseLocation]
                            inView:nil];

这是单击 NSStatusItem 时弹出菜单的代码:

- (void)mouseDown:(NSEvent *)event
{
    [statusItem popUpStatusItemMenu:[statusItem menu]];
}

mouseDown: 方法位于附加到 NSStatusItem 的自定义 NSView 中。

知道如何解决这个问题吗?

感谢您的帮助。

更新

该问题还与正在激活的应用程序有关(我在显示菜单之前使用[NSApp activateIgnoringOtherApps:YES];,或者在某些情况下无法使用键盘导航菜单)。

最佳答案

问题似乎是由于应用程序激活和 popUpMenu 发生在同一事件周期中造成的。我找到了一种解决方法,在this post中有更详细的描述。 .

总结一下,您需要首先激活应用程序(使用[NSApp activateIgnoringOtherApps:YES];),然后弹出菜单,确保这发生在新的事件周期中:您可以使用 NSTimer 触发菜单来实现此目的。

- (void) someMethod {
    // Some code
    [NSApp activateIgnoringOtherApps:YES];
    [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(showMenu) userInfo:nil repeats:NO];
    //Some other code
}

- (void) showMenu {
    // This will show the menu at the current mouse position
    [aMenu popUpMenuPositioningItem:[mainMenu itemAtIndex:0] atLocation:[NSEvent mouseLocation] inView:nil];
}

关于objective-c - 弹出菜单定位项 :atLocation:inView: hangs when switching to another application,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5521215/

相关文章:

iphone - 滑动以从 tableView 中删除记录

objective-c - UITextField 的初始键盘动画的超慢滞后/延迟

objective-c - 使用什么来代替 QTCaptureDevice?

objective-c - Cocoa 按钮在应用程序外部启动

iphone - 保留线程来监听委托(delegate)方法

ios - 如何解决 Objective C 中有符号与无符号类型不匹配的问题?

iphone - UIScrollview 类似动画的分页

linux - 递归获取它们所在的所有文件和目录

xcode - Mac App 无法在 Xcode 之外运行,库丢失了吗?使用库 ORSSerial

windows - 从 Mac OSX 和 Windows 卸载 Maven