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.
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
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


tell application "System Events" set application "KeyboardViewer" to (keystroke "K" using control down)You cannot assign a keyboard shortcut in that manned, it's improper coding regardless of the fact that it compiles. Read the first part of my answer up to the code. – user3439894 Oct 25 '17 at 13:14