I have a NSView
subclass and I would like it to react when the user presses the ⇧ Shift key. However, -[NSView keyDown:]
(which I currently override) isn't called when modifier keys alone are pressed.
How can I be notified when the Shift key has been pressed?
What do you do if the key press does not come as an event? For example, you want to test the state of the Shift key when the program starts up? The Shift key was pressed before the program started, and will not be released until after you test its state.
In Windows, you can easily get this with a call to
GetKeyState(VK_SHIFT)
. What is the macOS equivalent?in the apple's documentation :
You have to override the keydown method
with the following NSEvent modifier flags
Here is the code deals with key event with swift 3.0.1 tested on Xcode 8.2.1 and macOS 10.12.2
Checking for pressed:
Checking for release:
It should be noted, the NSLog function will only be called if SHIFT and then some other key is pressed.
Hope this helps!
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.
From the Cocoa event handling guide:
More details can be found here.
The documentation for NSResponder also states the following: