检测 Shift 键的 NSKeyUp

Detecting NSKeyUp of the Shift key

我正在使用它来检测我的应用程序上的击键...

[NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyDown
                                    handler:^NSEvent * (NSEvent * theEvent)

好的,我可以使用 theEvent 知道输入了哪些字符,并知道是否按下了换档键:

NSString *typedKey = theEvent.charactersIgnoringModifiers;
BOOL shiftDetected = [theEvent modifierFlags] & NSShiftKeyMask;

我的应用程序有一个显示一些按钮的界面,我允许使用键盘而不是点击按钮。该界面有 3 个按钮,特别是具有第二个功能。

例如:第一个按钮有 2 个功能,AB 但只有 A 标签显示在该按钮上。假设我指定字母 Q 是该按钮的键盘快捷键。如果用户按下 Q 函数 A 被执行。如果用户按下 Shift Q 则函数 B 被执行。

但这就是问题所在。我需要检测 Shift 的所有按下或释放,因为当用户按下 Shift 时,我必须将该按钮的标签从 A 更改为 B,所以用户知道现在该按钮将导致执行函数 B 而不是 A。就像键盘一样,在按住 Shift 时会从小写变为大写,并在释放 Shift 时变回小写。

我该怎么做?

我使用 addLocalMonitorForEvents 函数创建了一个简单的项目。请检查我的代码,它是 Swift 代码,但我认为它应该与 objective c.

相同
func applicationDidFinishLaunching(_ aNotification: Notification) {
    // Insert code here to initialize your application
    NSEvent.addLocalMonitorForEvents(matching: [.flagsChanged, .keyDown]) { (theEvent) -> NSEvent? in
        if theEvent.modifierFlags.contains(.shift) {
            if theEvent.keyCode == 56 { // this is Shif key
                print("Shift START!")
            }
            else {
                print("Shift pressed with keycode \(theEvent.keyCode)")
            }
        }
        else {
            if theEvent.keyCode == 56 { // this is Shif key
                print("Shift END!")
            }
            else {
                print("Normal keycode \(theEvent.keyCode)")
            }
        }
        return theEvent
    }
}

这是Objective c:

[NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskFlagsChanged|NSEventMaskKeyDown handler:^NSEvent * (NSEvent * theEvent) {
    if ([theEvent modifierFlags] & NSEventModifierFlagShift) {
        if (theEvent.keyCode == 56) { // this is Shif key
            NSLog(@"Shift START");
        }
        else {
            NSLog(@"Shift pressed with keycode %d", theEvent.keyCode);
        }
    }
    else {
        if (theEvent.keyCode == 56) { // this is Shif key
            NSLog(@"Shift END");
        }
        else {
            NSLog(@"Normal keycode %d", theEvent.keyCode);
        }
    }

    return theEvent;
}];

只需将此部分复制并粘贴到您的 AppDelegate 以进行快速测试。