如果按下了某个修饰符但没有其他修饰符,请检查NSEvent的modifierFlags [英] Check modifierFlags of NSEvent if a certain modifier was pressed but no other

查看:483
本文介绍了如果按下了某个修饰符但没有其他修饰符,请检查NSEvent的modifierFlags的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在NSEvent中尝试了 addLocalMonitorForEventsMatchingMask:handler:方法,并遇到了以下问题:如何找出

I just experimented with the addLocalMonitorForEventsMatchingMask:handler: method in NSEvent and came across the following question: How do I find out if only certain modifiers were pressed?

一个简短的例子来将这个问题设置为上下文:我想听快捷方式⌘ + W 。因此我写了以下代码:

A short example to set this question into context: I wanted to listen for the shortcut "⌘+W". Therefore I wrote the following code:

[NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask handler:^(NSEvent *theEvent) {
    if ([theEvent modifierFlags] & NSCommandKeyMask && [theEvent keyCode] == 13) {
        [self.window performClose:self];
    }
    return theEvent;
}];

这很好,但是即使按下更多的修饰键, ⌃ +⌘ + W或⇧ +⌃ +⌥ +⌘ + W。是否有办法规避这种情况?

This works well, however the shortcut will be triggered, even if more modifier keys are pressed, e.g. "⌃+⌘+W" or "⇧+⌃+⌥+⌘+W". Is there a way to circumvent this?

一个简单的解决方案是检查所有其他修饰键,并确保它们不被按下。这看起来很乏味和容易出错 - 除了它丑陋,因为它现在与一元&。此外,如果(由于某种原因)另一个修饰键添加到键盘布局,您可能会遇到麻烦。

A simple solution would be to check for all other modifier keys and ensure they are not pressed. This seems tedious and error prone - besides it's ugly enough as it is now with the unary "&". In addition you may get into trouble if (for some reason) another modifier key is added to keyboard layouts.

一如既往,我感谢任何建议。 >

As always I'm thankful for any recommendations.

推荐答案

我认为这样做:

// Mask out everything but the key flags
NSUInteger flags = [theEvent modifierFlags] & NSDeviceIndependentModifierFlagsMask;
if( flags == NSCommandKeyMask ){
    // Got it!
}

这篇关于如果按下了某个修饰符但没有其他修饰符,请检查NSEvent的modifierFlags的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆