gpt4 book ai didi

cocoa :右键单击 NSStatusItem

转载 作者:行者123 更新时间:2023-12-03 16:05:07 35 4
gpt4 key购买 nike

我是一名 .Net 开发人员,需要将一个小项目移植到 Mac 中,所以我对 Objective C 几乎一无所知。事实上,下面的代码只是一堆捕获救命稻草和在黑暗中拍摄的代码。

尝试构建一个状态菜单程序,根据左键单击或右键单击/Ctrl+单击打开一个或另一个窗口。这是我所拥有的,它仅适用于左键单击(显然):

-(void) awakeFromNib{

NSBundle *bundle = [NSbundle mainBundle];

statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength] retain];
[statusImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"icon" ofType:@"png"]];
[statusItem setImage:statusImage];
[statusItem setToolTip:@"Program Name"];
[statusItem setHighlightMode:YES];
[statusItem setAction:@selector(openWin:)];
[statusItem setTarget: self];
}

-(void)openWin:(id)sender{
[self openLeftWindow:sender];
}

-(IBAction)openLeftWindow:(id)sender{
//Code to populate Left Click Window
[leftWindow makeKeyAndorderFront:nil];
}

-(IBAction)openRightWindow:(id)sender{
//Code to populate Right Click Window
[rightWindow makeKeyAndorderFront:nil];
}

在我看来,解决方案要么是 openWin() 函数中的 if 语句来确定单击了哪个按钮(或者如果按住 ctrl),然后运行适当的代码,要么让菜单知道左键和右键单击。但当我尝试这样做时,这些都不起作用。

提前致谢。

最佳答案

如果您对检测控制单击而不是右键单击感到满意,那么第一个代码块将执行您想要的操作。如果您确实需要右键单击检测,则必须在 NSStatusItem 中使用自定义 View 而不是图像,并且第二个代码块将起作用。

简单方法:

- (void)openWin:(id)sender {
NSEvent *event = [NSApp currentEvent];
if([event modifierFlags] & NSControlKeyMask) {
[self openRightWindow:nil];
} else {
[self openLeftWindow:nil];
}
}

自定义 View 方法:

- (void)awakeFromNib {
...
statusImage = ...
MyView *view = [MyView new];
view.image = statusImage;
[statusItem setView:view];
[statusItem setToolTip:@"Program Name"];
view target = self;
view action = @selector(openLeftWindow:);
view rightAction = @selector(openRightWindow:);
[view release];
//[statusImage release]; //If you are not using it anymore, you should release it.
}

MyView.h

#import <Cocoa/Cocoa.h>
@interface MyView : NSControl {
NSImage *image;
id target;
SEL action, rightAction;
}
@property (retain) NSImage *image;
@property (assign) id target;
@property (assign) SEL action, rightAction;
@end

MyView.m

#import "MyView.h"
@implementation MyView
@synthesize image, target, action, rightAction;
- (void)mouseUp:(NSEvent *)event {
if([event modifierFlags] & NSControlKeyMask) {
[NSApp sendAction:self.rightAction to:self.target from:self];
} else {
[NSApp sendAction:self.action to:self.target from:self];
}
}
- (void)rightMouseUp:(NSEvent *)event {
[NSApp sendAction:self.rightAction to:self.target from:self];
}
- (void)dealloc {
self.image = nil;
[super dealloc];
}
- (void)drawRect:(NSRect)rect {
[self.image drawInRect:self.bounds fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1];
}
@end

关于 cocoa :右键单击 NSStatusItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4565820/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com