How can I detect that the Shift key has been pressed?

前端 未结 7 1074
甜味超标
甜味超标 2020-12-10 00:37

I have a NSView subclass and I would like it to react when the user presses the ⇧ Shift key. However, -[NSView keyDown:] (which I curren

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 01:26

    Here is an example, modified slightly from Matt Gemmell's ModKeyTest sample app. Create a basic Cocoa app with one button and hook up the button to an IBAction like this. Then try out your desired combination of keys. The docs are a bit fuzzy, but Matt's example is very clear and presents all you need to leverage this further from the docs.

    - (IBAction)myAction:(id)sender {
    NSUInteger flags = [[NSApp currentEvent] modifierFlags];
    if ((flags & NSCommandKeyMask) && (flags & NSAlternateKeyMask) && (flags & NSControlKeyMask)) {
        NSBeginInformationalAlertSheet(@"Modifier keys Command Option Control detected", nil, nil, nil, [NSApp mainWindow], self, nil, nil, nil,
                                       @"You sneaky thing!");
    }
    
    if ((flags & NSCommandKeyMask) && (flags & NSShiftKeyMask)) {
        NSBeginInformationalAlertSheet(@"Modifier keys Command Shift detected", nil, nil, nil, [NSApp mainWindow], self, nil, nil, nil,
                                       @"You sneaky thing!");
    }
    
    if ((flags & NSAlphaShiftKeyMask)) {
        NSBeginInformationalAlertSheet(@"Modifier keys Caps Lock detected", nil, nil, nil, [NSApp mainWindow], self, nil, nil, nil,
                                       @"You sneaky thing!");
    }
    if ((flags & NSFunctionKeyMask)) {
        NSBeginInformationalAlertSheet(@"Modifier keys fn detected", nil, nil, nil, [NSApp mainWindow], self, nil, nil, nil,
                                       @"You sneaky thing!");
    }
    

提交回复
热议问题