gpt4 book ai didi

swift - 检测 NSStatusItem 上的左键和右键单击事件 (Swift)

转载 作者:行者123 更新时间:2023-11-30 10:33:03 26 4
gpt4 key购买 nike

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

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

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

最佳答案

你尝试过吗:

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

关于swift - 检测 NSStatusItem 上的左键和右键单击事件 (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58693541/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com