我有一个小 cocoa 应用程序,通常在后台运行(作为代理)。有时我希望能够弹出一个上下文菜单(此时没有窗口或其他可见的东西)。
因为我只针对雪豹,所以我尝试了以下方法:
if (windows) {
NSMenu *theMenu = [[[NSMenu alloc] initWithTitle:@"test"] autorelease];
[theMenu setShowsStateColumn:NO];
[theMenu setAutoenablesItems:NO];
for (id item in windows) {
NSString *labelText = @"some text";
NSMenuItem *theMenuItem = [[[NSMenuItem alloc] initWithTitle:labelText
action:@selector(menuItemSelected:)
keyEquivalent:@""] autorelease];
[theMenuItem setTarget:self];
[theMenuItem setRepresentedObject:item];
[theMenuItem setEnabled:YES];
[theMenuItem setImage:icon];
[theMenu addItem:theMenuItem];
}
[theMenu popUpMenuPositioningItem:nil atLocation:[NSEvent mouseLocation] inView:nil];
}
菜单弹出完美,但如果我用鼠标光标悬停这些项目,它们不会突出显示,我也无法单击它们。
menuItemSelected: 方法看起来像这样:
-(IBAction)menuItemSelected:(id)sender {
}
知道我做错了什么吗?
最佳答案
我怀疑窗口系统不认为您的应用程序处于事件状态,因此不会将鼠标事件发送到您创建的菜单。
作为实验,尝试在弹出菜单之前创建一个虚拟窗口。我将创建一个 NSPanel,可能使用样式 NSNonActivatingPanelMask。 makeKeyAndOrderFront:
你的窗口/面板,然后弹出菜单,看看会发生什么。
如果这有效,我会坚持使用该方法并隐藏窗口。
关于cocoa - NSMenu 不开始跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2843459/