how to identify if the MenuBarExtra in macos is hidden by the system

121 views Asked by At

I was reading this apple documentation for MenuBarExtra in macos and it states:

When necessary, the system hides menu bar extras to make room for app menus. Similarly, if there are too many menu bar extras, the system may hide some to avoid crowding app menus.

I am using Appkit implementation for MenuBarExtras and wanted to know, how to identify if the system has hidden/unhidden my menuBarExtra. Is there some event that is received when the system hides it?

1

There are 1 answers

0
jnpdx On

First, you'll need a reference to the NSWindow that holds that status item. You can get that like this:

statusItem.button?.window

Then, you'll want to listen to some NSNotifications related to that window. For example, we listen to:

NSWindow.didChangeScreenNotification
NSWindow.didMoveNotification
NSWindow.didResizeNotification
NSWindow.didChangeOcclusionStateNotification

Theoretically, only the last one should be required (https://developer.apple.com/documentation/appkit/nswindow/1419549-didchangeocclusionstatenotificat), actually, but we have some use cases for the others as well.

Then, upon receiving the notification, you can check the occlusion by doing:

window.occlusionState.contains(.visible)