I have an M1 MacBook Pro and I often connect it to an external display. I would like to automatically unhide the dock and menu bar when my MacBook Pro is connected to the external display, and hide them when my MacBook Pro is not connected to the external display. I would like to accomplish this using AppleScript or anything else.
Here's what I tried.
-- Check if an external display is connected
tell application "System Events"
set displays to name of every desktop
end tell
if (count of displays) > 1 then
-- External display is connected, hide the Dock and menu bar
tell application "System Events"
set autohide of dock preferences to true
set UI elements enabled to true
end tell
else
-- External display is not connected, unhide the Dock and menu bar
tell application "System Events"
set autohide of dock preferences to false
set UI elements enabled to false
end tell
end if
The line set UI elements enabled to false
keeps throwing this: error "System Events got an error: Can’t set UI elements enabled of application to false." number -10006 from UI elements enabled of application
What is the syntax for writing such a script? Are there any built-in functions in macOS that can help me accomplish this task? Are there any third-party libraries or resources that could be helpful? How can I set up the script to run automatically when the external display is connected or disconnected? Is this even possible?