0

在菜单上单击左右时,我使用此代码具有两种不同的行为。

单击左键然后单击右键 + cmd

如何以最简单的方式在不按 cmd + click 的情况下单击鼠标右键?

-(void)awakeFromNib {

NSImage *image = [NSImage imageNamed:@"menubar"];
NSImage *alternateImage = [NSImage imageNamed:@"menubar-white"];

statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
[statusItem setHighlightMode:YES];
[statusItem setImage:image];
[statusItem setAlternateImage:alternateImage];
[statusItem setAction:@selector(show)];
}


- (void)show {

NSLog(@"call show");

NSEvent *event = [NSApp currentEvent];
//Respond to the mouse click
if ([event modifierFlags] & NSCommandKeyMask) //Command
{
    NSLog(@"RIGHT");
    [statusItem setMenu:statusMenu];
}
else {
    NSLog(@"LEFT");
    //open window
}
}

菜单点击右键

谢谢你的帮助!

4

2 回答 2

6

我不同意亚伦。通常,您应该避免检查瞬时鼠标或键盘状态。自您实际应该响应的操作以来,它可能已经发生了变化。例如,如果用户左键单击然后释放鼠标按钮,+pressedMouseButtons则可能会0在您的代码开始调用它时返回。

相反,您应该检查触发当前处理的事件。对于左键单击,您将获得一个事件,其typeNSLeftMouseDown. 右键单击,您将获得NSRightMouseDown. 如果你已经知道你有某种鼠标点击事件并且由于某种原因不想检查它的类型,你可以检查它的buttonNumber属性。

实际上,是什么调用了您的-show方法?我希望您已经在某处实现了该NSResponder方法。-mouseDown:如果是这样,则对应于左键单击。如果用户右键单击,-rightMouseDown:则会调用不同的方法 ( )。因此,如果您想要不同的响应,通常应该对这两种方法进行不同的编码。

于 2013-05-01T05:10:02.190 回答
4

Inspect [NSEvent pressedMouseButtons] instead of the modifier flags. Let the system take care of deciding which button has been clicked. If you do it the way you're trying to do now you'll get weird behavior for users who are actually using multi-button mice.

You should be able to use something like this:

const NSUInteger pressedButtonMask = [NSEvent pressedMouseButtons];
const BOOL leftMouseDown = (pressedButtonMask & (1 << 0)) != 0;
const BOOL rightMouseDown = (pressedButtonMask & (1 << 1)) != 0;
于 2013-04-30T19:46:19.907 回答