1

I am making this app, and I want to detect whether a shift key is being detected. My code is as follows:

override func keyDown(with event: NSEvent) {
    if (event.keyCode == Keycode.shift || event.keyCode == Keycode.shift){
        //do whatever when the shift key is pressed
        print("shift key is being pressed.")
    }
}

The struct is from this GitHub: github link here

I tried changing the key code to keyCode.q, and it works fine when q is pressed. It seems as if only the shift key isn't working, and I am not sure why. Any help would be appreciated. Thanks!

Note: When I type regularly, I know my shift key works.

Jerry Qian
  • 33
  • 1
  • 8
  • Shift is a key modifier. Try the solution from here: https://stackoverflow.com/questions/4640696/cocoa-nsevent-respond-to-the-shift-key – keji May 19 '19 at 14:14
  • I don't know any objective-c which is why I asked here. Like I couldn't understand objective c even if my life depended on it. :( – Jerry Qian May 19 '19 at 14:32

1 Answers1

1

You're looking for NSResponder.flagsChanged(with:)

Alexander
  • 59,041
  • 12
  • 98
  • 151
  • But once I press shift it is permanent. How would I change this so when shift is pressed, the do whatever is done, but when not, whatever happened is undone? – Jerry Qian May 19 '19 at 14:45
  • @JerryQian You inspect the `NSEvent.type` value to see if it's `.keyDown` or `.keyUp`. – Alexander May 19 '19 at 17:17