AppleScript for locking the screen in Catalina

Is there a way to build an AppleScript for locking the screen? I want to add a Quick Action (and the relative button on the Touch Bar as described here)

This solution i.e.,

tell application "System Events" to tell process "SystemUIServer"
    tell (menu bar item 1 of menu bar 1 where description is "Keychain menu extra")
        click
        click menu item "Lock Screen" of menu 1
    end tell
end tell

does not work in Catalina. After allowing accessibility for Apple Script Editor from Security and privacy, I still get this error in automator:

Can’t get menu 1 of menu bar item 2 of menu bar 1 of application process "SystemUIServer". Invalid index.


You can use:

tell application "System Events" to keystroke "q" using {control down, command down}

You could also use the following instead:

tell application "System Events"
    set appName to (name of every application process whose frontmost is true and visible is true) as string
    click menu item "Lock Screen" of menu 1 of menu bar item "Apple" of menu bar 1 of application process appName
end tell

      Hint: Mouse over and horizontal/vertical scroll to see full code.

However, the first mentioned solution is more direct.


There already is a Screen Lock button for the Touch Bar natively !

Here is how to set up the Screen Lock button on Touch Bar:

  1. Go to the Apple menu and choose “System Preferences” and then go to “Keyboard”
  2. Under the “Keyboard” tab choose “Customize Control Strip” enter image description here
  3. Expand the Touch Bar and then drag the “Screen Lock” button into the touch bar screen (drag it down off the Mac display and it will pop up on the Touch Bar)

enter image description here

  1. Click on “Done” and exit out of Keyboard preferences, the Screen Lock button is now available on the Mac Touch Bar

enter image description here