Search code examples
swiftmacosappkitnsresponder

Disabling right click in appkit


I'm currently taking in a nextEvent within my mouseDrag function

    while true {
        guard let nextEvent = self.window?.nextEvent(matching: [.leftMouseDragged, .leftMouseUp, .rightMouseUp]) else {
            continue
        }
        switch nextEvent.type {
        case .leftMouseDragged:
            self.cursorUpdate(with: nextEvent)
            self.mouseDragged(with: nextEvent)

        case .rightMouseUp:
            continue

        default:
            self.mouseUp(with: nextEvent)
            return
        }
    }

And I'm just trying to disable right click for the duration. However, with this implementation the right clicks simply queue up and get called after the loop finishes.

How would I disable right clicks being registered at all?


Solution

  • Try adding .rightMouseDown and .rightMouseDragged to your matching mask. It is the .rightMouseDown event that makes AppKit display the context menu.

        guard let nextEvent = self.window?.nextEvent(matching: [.leftMouseDragged, .leftMouseUp, .rightMouseDown, .rightMouseDragged, .rightMouseUp]) else {
            continue
        }
    

    You might also consider switching to NSWindow.trackEvents(matching:timeout:mode:handler:) instead of writing your own loop:

        window.trackEvents(matching: [.leftMouseDragged, .leftMouseUp, .rightMouseDown, .rightMouseDragged, .rightMouseUp], timeout: NSEvent.foreverDuration, mode: .eventTrackingRunLoopMode) { (event, outStop) in
            guard let event = event else { return }
            switch event.type {
            case .rightMouseDown, .rightMouseDragged, .rightMouseUp: return
            case .leftMouseDragged:
                self.cursorUpdate(with: event)
                self.mouseDragged(with: event)
            case .leftMouseUp:
                self.mouseUp(with: event)
                outStop.pointee = true
            default:
                break
            }
        }
    

    Using trackEvents lets AppKit run the main run loop, so timers and observers can continue firing (if they are scheduled for .eventTrackingRunLoopMode).