Simon
Simon

Reputation: 427

In the NsView, how to judge whether the user holding down the Shift key

Everybody is good, I in their own ViewController, I want to be able to determine whether to user is holding down the Shift key keyboard or the Command key.Please familiar friend told me that I should how to implement.Thank you very much!

Upvotes: 0

Views: 226

Answers (1)

pbodsk
pbodsk

Reputation: 6876

One way to solve this could be to use a local event monitor (described here).

This method monitors all events of the type you ask it to. So for instance you could use it to get notified of all keypresses like so:

NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
    self.keyDown(with: $0)
    return $0
}

This will give you instances of NSEvent every time a key is pressed (every time the key is pressed down actually, there is also a .keyUp which is triggered when the key is released).

The NSEvent class then has a set of ModifierFlags which you can query and see whether one or more of these modifiers has been pressed alongside the key. So, your keyDown method (which overrides the one from NSResponder) could do something like this:

override func keyDown(with event: NSEvent) {
    if event.modifierFlags.contains(.shift) {
        print("Shift pressed")
    }
    if event.modifierFlags.contains(.command) {
        print("Command pressed")
    }
    super.keyDown(with: event)
}

Complete Example

import Cocoa

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
            self.keyDown(with: $0)
            return $0
        }
    }

    override var representedObject: Any? {
        didSet {
            // Update the view, if already loaded.
        }
    }

    override func keyDown(with event: NSEvent) {
        if event.modifierFlags.contains(.shift) {
            print("Shift pressed")
        }
        if event.modifierFlags.contains(.command) {
            print("Command pressed")
        }
        super.keyDown(with: event)
    }
}

See Also

Hope that helps you.

Upvotes: 1

Related Questions