Dan*_*Dan 9 cocoa right-click nsstatusitem
我是一名.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];
}
Run Code Online (Sandbox Code Playgroud)
在我看来,解决方案将是openWin()函数中的if语句,以确定单击哪个按钮(或者如果按住ctrl)然后运行相应的代码或使菜单知道左右两侧点击.但是当我试图这样做时,这些都没有奏效.
提前致谢.
ugh*_*fhw 12
如果您对检测控件单击而不是右键单击感到满意,那么第一个代码块将执行您想要的操作.如果您确实需要右键单击检测,则必须在NSStatusItem中使用自定义视图而不是图像,并且第二个代码块将起作用.
简单方法:
- (void)openWin:(id)sender {
NSEvent *event = [NSApp currentEvent];
if([event modifierFlags] & NSControlKeyMask) {
[self openRightWindow:nil];
} else {
[self openLeftWindow:nil];
}
}
Run Code Online (Sandbox Code Playgroud)
自定义视图方法:
- (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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7396 次 |
| 最近记录: |