【问题标题】:Detect left and right click events on NSStatusItem (Swift)检测 NSStatusItem (Swift) 上的左右点击事件
【发布时间】:2016-08-17 14:39:35
【问题描述】:

我正在构建一个状态栏应用,并希望根据用户是单击左还是右来调用不同的操作。这是我目前所拥有的:

var statusItem = NSStatusBar.system().statusItem(withLength: -1)
statusItem.action = #selector(AppDelegate.doSomeAction(sender:))

let leftClick = NSEventMask.leftMouseDown
let rightClick = NSEventMask.rightMouseDown

statusItem.button?.sendAction(on: leftClick)
statusItem.button?.sendAction(on: rightClick)

func doSomeAction(sender: NSStatusItem) {
    print("hello world")
}

我的函数没有被调用,我找不到我们的原因。感谢您的帮助!

【问题讨论】:

    标签: swift nsstatusitem nsevent nsstatusbar


    【解决方案1】:

    你试过了吗:

    button.sendAction(on: [.leftMouseUp, .rightMouseUp])
    

    然后查看doSomeAction()函数中按下了哪个鼠标按钮?

    所以它看起来像......

    let statusItem = NSStatusBar.system().statusItem(withLength: NSSquareStatusItemLength)
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {
    
        if let button = statusItem.button {
            button.action = #selector(self.doSomeAction(sender:))
            button.sendAction(on: [.leftMouseUp, .rightMouseUp])
        }
    
    }
    
    func doSomeAction(sender: NSStatusItem) {
    
        let event = NSApp.currentEvent!
    
        if event.type == NSEvent.EventType.rightMouseUp {
            // Right button click
        } else {
            // Left button click
        }
    
    }
    

    感谢 @dbrownjave 注意到 Swift 4 从 NSEventType.rightMouseUpNSEvent.EventType.rightMouseUp 的变化。

    https://github.com/craigfrancis/datetime/blob/master/xcode/DateTime/AppDelegate.swift

    【讨论】:

    • 这确实有效,但似乎只喜欢.rightMouseUp,而不喜欢.rightMouseDown
    • 您是否也更改了button.sendAction 行?
    • 哇!在sendAction 中更改,不在声明中!工作得很好,谢谢 x)
    • 我将如何使用 NSEventMask.scrollWheel 做到这一点?
    • 如何才能在右键单击项目时打开上下文菜单?我读到 popUpStatusItemMenu 已被弃用,我无法理解如何在 Swift 4 中做到这一点......
    【解决方案2】:

    更新:SWIFT 4

    我已经更新了(Craig Francis)的答案

    func doSomeAction(sender: NSStatusItem) {
    
        let event = NSApp.currentEvent!
    
        if event.type == NSEvent.EventType.rightMouseUp{
            // Right button click
        } else {
            // Left button click
        }
    

    【讨论】:

    • 您能否再补充一点,说明此代码为何有效以及它如何解决问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多