在 appkit 中禁用右键单击

Disabling right click in appkit

我目前正在我的 mouseDrag 函数中接受 nextEvent

    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
        }
    }

我只是想在此期间禁用右键单击。然而,在这个实现中,右键单击只是排队并在循环完成后被调用。

我怎样才能完全禁用右击注册?

尝试将 .rightMouseDown.rightMouseDragged 添加到匹配的掩码中。使 AppKit 显示上下文菜单的是 .rightMouseDown 事件。

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

您也可以考虑切换到 NSWindow.trackEvents(matching:timeout:mode:handler:) 而不是编写自己的循环:

    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
        }
    }

使用 trackEvents 让 AppKit 运行 主 运行 循环,因此定时器和观察者可以继续触发(如果它们被安排在 .eventTrackingRunLoopMode)。