LoginSignup
2

More than 3 years have passed since last update.

Swift:メニューバー(NSStatusBarButton)をクリックしたときの動作を左右クリックで分ける

Posted at
AppDelegate.swift
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
    var button: NSStatusBarButton!

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        button = statusItem.button!
        button.title = "🤔"
        button.action = #selector(clicked(_:))
        // ここで受け取るイベントを登録しておく
        button.sendAction(on: [.leftMouseDown, .rightMouseDown])
    }

    @objc func clicked(_ sender: NSStatusBarButton) {
        let event = NSApp.currentEvent!
        switch event.type {
        case .rightMouseUp:
            print("right click")
        case .leftMouseUp:
            print("left click")
        default:
            break
        }
    }
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2