Option-Click ASOC Menubar App

Hi folks,

Say I have a simple menubar app created with the following code:

use AppleScript version "2.5"
use framework "Foundation"
use framework "AppKit"
use scripting additions

property NSMenu : a reference to current application's NSMenu
property NSEvent : a reference to current application's NSEvent
property NSStatusBar : a reference to current application's NSStatusBar
property NSMenuItem : a reference to current application's NSMenuItem
property NSAlternateKeyMask : a reference to current application's NSAlternateKeyMask

property newMenu : class "NSMenu"
property statusItem : missing value

on createStatusItem()
	
	set statusBar to NSStatusBar's systemStatusBar
	set statusItem to statusBar's statusItemWithLength:-1.0
	
	statusItem's setTitle:"Menu Bar App"
	
	set newMenu to NSMenu's alloc()'s init()
	newMenu's setDelegate:me
	
	set menuItem1 to NSMenuItem's alloc()'s initWithTitle:"Menu Item 1" action:"action1:" keyEquivalent:""
	set menuItem2 to NSMenuItem's alloc()'s initWithTitle:"Menu Item 2" action:"action2:" keyEquivalent:""
	set menuItem3 to NSMenuItem's alloc()'s initWithTitle:"Menu Item 3" action:"action3:" keyEquivalent:""
	
	statusItem's setMenu:newMenu
	
	newMenu's addItem:menuItem1
	newMenu's addItem:menuItem2
	newMenu's addItem:menuItem3
	
	menuItem1's setTarget:me
	menuItem2's setTarget:me
	menuItem3's setTarget:me
	
end createStatusItem

my createStatusItem()

on action1:sender
	beep # example task
end action1:

on action2:sender
	beep # example task
end action2:

on action3:sender
	beep # example task
end action3:

I now want to be able to option-click on the menubar app title to quit the menubar app itself. I know it involves adding the following code somewhere:

if NSEvent's modifierFlags() is equal to (NSAlternateKeyMask as integer) then tell me to quit

But I haven’t been able to figure out exactly where to put it in the script to make it work. I’ve successfully achieved this with a menubar app that doesn’t have a menu (using “setAction:”), but one with a menu has got me flummoxed. Any help would be much appreciated. TIA.

—Storm

Thanks for your reply, Fredrik. I realise that I could just add a menu item that performs the quit action, but what I probably should have made clear in my initial question was that this menubar app would rarely be quit and so a dedicated menu item would be overkill. But on the rare occasion that I did need to quit the menubar app I was looking to just option-click on its title to do so.

—Storm

NSMenu has a delegate method menuWillOpen which is called right before the menu opens.

As you already connected the menu delegate just implement the method

on menuWillOpen:sender

Oh, that’s perfect, Stefan, and so simple too. Many thanks.

—Storm