How to close on screen keyboard from menu bar option “A” near the spotlight search via applescript for mojave, sierra, high sierra, el capitan [duplicate]

At least for Mojave for now.

Presented strictly as a proof of concept, the example AppleScript code shown below was tested and worked for me without issues as is under macOS Mojave 10.14.6 in Script Editor, under the following conditions:

  • In System Preferences > Keyboard> Keyboard:
    • [√] Show keyboard and emoji viewers in menu bar
  • In System Preferences > Keyboard> Input Source:
    • [√] Show Input menu in menu bar
  • In System Preferences > Accessibility > Keyboard > Accessibility Keyboard:
    • [ ] Enable Accessibility Keyboard
  • System Preferences > Security & Privacy > Privacy > Accessibility
    • [√] Script Editor
  • System Preferences > Language & Region:
    • Preferred languages:
    • English
    • English (US) — Primary
  • Keyboard Viewer was made visible by clicking the Show Keyboard Viewer menu item of the Input menu on the menu bar.

The following example AppleScript code hides the Keyboard Viewer if it's visible and the Hide Keyboard Viewer menu item exists on the Input menu on the menu bar by clicking it.

tell application "System Events"
    tell application process "SystemUIServer"
        tell menu bar 1
            if ((menu bar items whose description is "text input") exists) then
                if menu item "Hide Keyboard Viewer" of menu 1 of ¬
                    (menu bar items whose description is "text input") exists then
                    click (menu bar items whose description is "text input")
                    delay 0.2
                    click menu item "Hide Keyboard Viewer" of menu 1 of ¬
                        (menu bar items whose description is "text input")
                end if
            end if
        end tell
    end tell
end tell

Note: The example AppleScript code is just that and sans any included error handling does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.