If you're wanting to assign a keyboard shortcut to an AppleScript application, you'll need to do it as an Automator Service. However, one of the issues you'll run into, when Keyboard Viewer has focus is, it will eat the keyboard shortcut and not close Keyboard Viewer. You'd have to set focus away from Keyboard Viewer in order for the Automator Service to close Keyboard Viewer.
The following AppleScript code does that, providing you have not set focus to it after it opens or reset it elsewhere if you did.
tell application "System Events"
set activeApp to name of first application process whose frontmost is true and visible is true
if application "KeyboardViewer" is running then
quit application "KeyboardViewer"
activate application "KeyboardViewer"
tell application activeApp to activate
In Automator create a new Service workflow with the following setting:
- Service receives no input in any application
- Add a Run AppleScript action.
- Replace the default code with the code above.
- Click the Compile button (Hammer icon).
- Save it as e.g.: Toggle Keyboard Viewer
- In System Preferences > Keyboard > Services > Shortcuts > Services
- Find e.g. Toggle Keyboard Viewer and give it a shortcut.
- I gave it: ⌥⌘K
Note: Finding a keyboard shortcut that isn't already taken by another app can be a challenge. In this use case, any application that has focus when e.g. ⌥⌘K is pressed, it will go to the app's assigned command before it goes to the e.g.: Toggle Keyboard Viewer service. You might need to go to a four key keyboard shortcut, e.g.: ^⌥⌘K