I am trying to create a shortcut that toggles Keyboard Viewer with Automator. I have tried these both ways: this old one and and this one for Sierra
For both ways, there is a syntax error "Can't get application KeyboardViewer"
If i press the shortcut i assigned, it opens a window("Choose an application") with a list of apps
The scripts I have tried:
if application "KeyboardViewer" is running then
quit application "KeyboardViewer"
end if
activate application "KeyboardViewer"
-- wait until the window has been closed, then end the KeyboardViewer process
set numberOfWindows to 1
repeat until numberOfWindows = 0
delay 5
tell application "System Events"
tell process "KeyboardViewer"
set numberOfWindows to count windows
end tell
end tell
end repeat
quit application "KeyboardViewer"
and
on run
tell application "System Events"
set activeApp to name of first application process whose frontmost is true and visible is true
end tell
if application "KeyboardViewer" is running then
quit application "KeyboardViewer"
else
activate application "KeyboardViewer"
end if
tell application activeApp to activate
end run
Best Answer
This works for me on macOS Big Sur.
SIDENOTE: My reason for using the the do shell script "killall 'System Preferences'" command rather than tell application "System Preferences" to quit is... Let's say, for what ever reason, System Preferences.app is already activated (with, for example, window Sharing/ Remote Management/ Computer Settings open) but not visible or not front most or whatever. In Script Editor, you try to run tell application "System Preferences" to reveal anchor "SpeakableItems" of pane id "com.apple.preference.universalaccess" That command completes with no obvious errors but when you switch over to System Preferences, your "revealed anchor" is not revealed. Ok, no big deal, easy fix. I'll just insert a tell application "System Preferences" to quit command prior to the reveal anchorcommand. Running the updated code this time, you get a (userCanceledErr:-128) error. All of this hassle is because that secondary drop down window in System Preferences is open. In my opinion, the do shell script "killall 'System Preferences'" command seems to be the best solution.
Here is another option if you have the “Show Accessibility status in menu bar” checked in System Preferences/Accessibility. It's short, it's sweet, but it does use UI scripting.