Selecting a Unicode hex input source using AS

I’m trying to select a given keyboard from the Input Sources Menu using AS. Apple provides a keyboard shortcut to toggle between 2 keyboards, but no way to determine which keyboard has been selected (except by looking up at the Menu Bar).

I want to switch back and forth between a standard US keyboard and the Unicode Hex Input keyboard. The Unicode keyboard is added to the Input Sources Menu at Keyboard Preferences/Input Sources/ click “+” button to add a keyboard, scroll down to the very bottom of the left column and select “Others”, and then select Unicode Hex Input.

So I now have my 2 keyboards showing in the Menu, and I can set a keyboard shortcut (default is Ctl-Opt-Space) to toggle between them. This works fine to toggle the 2 keyboards, but still no way to determine which is active.

I tried using the following script to force a known state. I got the menu reference from UI Browser, and I think the reference is accurate because it “sort of” swaps the keyboards, but not quite.

activate application "SystemUIServer"
tell application "System Events"
	tell process "SystemUIServer"
		tell menu item "Unicode Hex Input" of menu 1 of menu bar item 5 of menu bar 1
			if ((it exists) and (it is enabled)) then perform action "AXPress"
		end tell
	end tell
end tell

If I have the US keyboard checked and run this script, nothing appears to happen. The US keyboard stays active and the US flag stays visible in the menu bar. If I then click on the flag it instantly switches over to the Hex keyboard icon, and the Hex keyboard item in the menu now has the check mark.

How can I make this work without needing to click on the menu?

You might have more luck using my BridgePlus library, which supports changing input sources. In fact, this manual page shows you half of what you need in the example:

https://www.macosxautomation.com/applescript/apps/BridgePlus_Manual/Pages/changeInputSourceTo_.html

You can get the library here:

https://www.macosxautomation.com/applescript/apps/Script_Libs.html

Thanks, Shane. That’s exactly what I was looking for. In fact, it’s much better than what I was looking for because it avoids all the gui scripting. And as a bonus, I find this trove of other gadgets in your library that I didn’t know I needed before. Thanks again.