Luca Marconato Luca Marconato - 1 year ago 128
Swift Question

macOS detect if mouse button is down in KeyDown


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 Source

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:.


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download