Luca Marconato Luca Marconato - 2 days ago 5
Swift Question

macOS detect if mouse button is down in KeyDown

In

keyDown(with event: NSEvent)
I can know if OPT, CMD, CTRL, Shift are pressed, with the following code

override func keyDown(with event: NSEvent) {
let shiftPressed = (event.modifierFlags.rawValue & NSEventModifierFlags.shift.rawValue != 0)
let commandPressed = (event.modifierFlags.rawValue & NSEventModifierFlags.command.rawValue != 0)
let optionPressed = (event.modifierFlags.rawValue & NSEventModifierFlags.option.rawValue != 0)
let controlPressed = (event.modifierFlags.rawValue & NSEventModifierFlags.control.rawValue != 0)
...


How can I detect if the left mouse button is up or down inside keyDown?

Answer

As you may notice, keyDown: tracks keyboard not mouse, so you need to track the mouse. Then :

Catch mouse events and track mouseDown:, set a flag inside it that you reset in mouseUp:, then test this flag in your keyDown:.

-----EDIT----

You may also poll the mouse (polling is not always a good idea anyway) with method pressedMouseButtons: of NSEvent.

Comments