Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I open an NSMenu programatically?

Like the title says, I want to automatically open the menu at certain intervals. Preferably from within the program itself, as I am sure I could do something manually with applescripts+cron, which I don't want to use.

I am talking about a menu/button/whatever from the OSX menubar. Just to be clear. No custom views, just a plain nsmenu.

like image 457
jontelang Avatar asked Nov 20 '25 22:11

jontelang


2 Answers

For opening an NSStatusItem menu, I found it easier to call the performClick method on the button belonging to the NSStatusItem. That way I didn't have to worry about properly passing an event or view to popUpContextMenu. Something like this:

statusItem.button?.performClick(nil)
like image 67
Ryan H Avatar answered Nov 22 '25 19:11

Ryan H


You can programatically show an NSMenu by calling:

[NSMenu popUpContextMenu:YOUR_MENU withEvent:MOUSE_EVENT forView:YOUR_VIEW]

To construct the event you can use NSEvent's +mouseEventWithType:location:modifierFlags:timestamp:windowNumber:context:eventNumber:clickCount:pressure:

Note: if your menu is an NSStatusItem menu, you will have to set the item's view to be able to popUp the menu.

like image 39
Guilherme Rambo Avatar answered Nov 22 '25 19:11

Guilherme Rambo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!