Getting Menu Bar Height

Hi folks,

Can anyone tell me why the following script works when run in Script Editor or when saved as an application, but does nothing when run from the macOS Script Menu (regardless of macOS version)? And if so, how can I fix it? TIA.

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

set theMenuBar to current application's NSApp's mainMenu()
set theMenuBarHeight to (theMenuBar's menuBarHeight) as integer

display alert "The menu bar height is " & theMenuBarHeight & " pixels."

stormyhamster. I don’t know why your script does not work when run from the Script menu. However, on my Sonoma computer, the following does work when run from the Script menu.

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

set theMenuBarHeight to current application's NSMenu's menuBarHeight() as integer
display alert "The menu bar height is " & theMenuBarHeight & " pixels."

That’s perfect. Thank you, peavine.

—Storm

1 Like

Storm. I’m glad that helped.

Before reading Storm’s original post, I wasn’t aware there was a menuBarHeight property, and I would have used the approach shown below. I ran timing tests and both approaches took about 0.4 millisecond to run. So, just for the sake of brevity, the NSMenu approach seems best.

use framework "AppKit"
use framework "Foundation"
use scripting additions

set menuHeight to getMenuHeight() --> 24

on getMenuHeight()
	set theScreen to current application's NSScreen's mainScreen()
	set {{x1, y1}, {w1, h1}} to theScreen's frame()
	set {{x2, y2}, {w2, h2}} to theScreen's visibleFrame()
	return (h1 - h2 - y2 - 1) as integer
end getMenuHeight

BTW, the point of origin of the visibleFrame property is the lower-left corner of the screen, and the x and y coordinates are zero-based, which is the reason for the calculations at the end of the getMenuHeight handler.