如果按下了某个修改器但没有按下其他修改器,则检查 NSEvent 的修改器标志
我刚刚在 NSEvent 中尝试了 addLocalMonitorForEventsMatchingMask:handler:
方法,并遇到了以下问题:如何找出是否only某些修饰符压?
一个简短的例子来设置这个问题:我想听一下快捷键“⌘+W”。因此我编写了以下代码:
[NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask handler:^(NSEvent *theEvent) {
if ([theEvent modifierFlags] & NSCommandKeyMask && [theEvent keyCode] == 13) {
[self.window performClose:self];
}
return theEvent;
}];
这很好用,但是即使按下更多修饰键,例如“⌃+⌘+W”或“⇧+⌃+⌥+⌘+W”,快捷键也会被触发。有办法绕过这个吗?
一个简单的解决方案是检查所有其他修饰键并确保它们没有被按下。这看起来很乏味并且容易出错——而且它已经够丑陋的了,就像现在的一元“&”一样。此外,如果(由于某种原因)另一个修饰键被添加到键盘布局中,您可能会遇到麻烦。
一如既往,我感谢任何建议。
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?
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;
}];
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为这样就可以了:
向 SpaceDog 致敬 指出原始掩码名称已被弃用,
NSDeviceIndependentModifierFlagsMask
。I think this'll do it:
Hat tip to SpaceDog for pointing out the deprecation of the original mask name,
NSDeviceIndependentModifierFlagsMask
.Swift 5 版本
Swift 5 version
感谢 Apple,@JoshCaswell 的答案已经过时,因为 NSDeviceIndependentModifierFlagsMask 自 10.12 以来已被弃用。
他对新语法的回答更新为
NSDeviceIndependentModifierFlagsMask
已替换为NSEventModifierFlagDeviceIndependentFlagsMask
因为它带来了天壤之别......@JoshCaswell answer has been outdated thanks to Apple, because
NSDeviceIndependentModifierFlagsMask
has been deprecated since 10.12.His answer updated to the new syntax is
NSDeviceIndependentModifierFlagsMask
has been replaced withNSEventModifierFlagDeviceIndependentFlagsMask
because it makes a world of difference...也许更好...
Maybe even better...