检测 NSStatusItem 上的左键和右键单击事件 (Swift)
Detect left and right click events on NSStatusItem (Swift)
我正在构建一个状态栏应用程序,并希望根据用户是向左还是向右单击来调用不同的操作。这是我目前所拥有的:
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.rightMouseUp
到 NSEvent.EventType.rightMouseUp
的变化。
https://github.com/craigfrancis/datetime/blob/master/xcode/DateTime/AppDelegate.swift
更新: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
}
我正在构建一个状态栏应用程序,并希望根据用户是向左还是向右单击来调用不同的操作。这是我目前所拥有的:
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.rightMouseUp
到 NSEvent.EventType.rightMouseUp
的变化。
https://github.com/craigfrancis/datetime/blob/master/xcode/DateTime/AppDelegate.swift
更新: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
}