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!
Asked
Active
Viewed 199 times
1 Answers
1
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.

pbodsk
- 6,787
- 3
- 21
- 51
-
Thank you very much for the case, but this method does not monitor the Shift key and the Command key. Did you miss something? – Simon Jun 27 '17 at 13:23
-
@DivenLee I've changed from `.control` to `.command` and can now see the following: If I launch the app and press s for instance, nothing happens, if I press shift + s I can see "Shift pressed" in the console. If I press command + s I can see "Command pressed" in the console. Do you see the same behaviour? – pbodsk Jun 27 '17 at 13:31
-
I have already found the reason, this belongs to the flagsChanged rewritten, different events.Thank you very much for additional reference, then give me the answer.thank you – Simon Jun 27 '17 at 13:40