February 1, 2021

AutoHotkey: Embed image in Script / Toggle Tray icon

In AutoHotkey, you can embed an image into a Script. I've been using this for example to be able to switch a script tray icon (see mute on/off) and still provide the script as single file, without any image files dependency.I explain here in this post how to do so.

Include image in AutoHotkey Script

This is already shared here in Jack's blog but I summarize it for me and maybe others.

Image2include.ahk


(As backup you can also get it from my github AHK repo here)

Run the script

It will open a GUI like shown below:

Select the image file and click on "Convert Image" and then "Show script" 
Ctrl+A and Ctrl+C to copy the script to your clipboard.

Paste this function (Ctrl+V) in your target AHK file. (I like to paste these functions at the bottom of the file.)

(You can delete the temporary previously generated script.)

Now to get the images in your script add a line like: 
Tray_Icon_On := "HBITMAP:*" . <The name of the function you've pasted>()

You can then add this line to set the tray icon:

Menu, Tray, Icon, %Tray_Icon_On% 

Toggle icon while clicking on the Tray icon

You can customize the mouse click callbacks on the script tray icon.

See detailed post here how to do this. (in work)

To access the Tray menu you need to run the code on the script level, not a subfunction.
That's why I have coded this part as a label and not as a function and use a GoSub from other functions to it (GoTo does not work out of a function).

I load the image files in the auto-execute script section.

See an example in the Mute PowerTool:  Mute.ahk

The part that change the icon is under the RefreshIcon label:
RefreshIcon:
If (G_IsOn="")
    G_IsOn := Mute_Get()
If (G_IsOn) {
    Menu, Tray, Icon, %Tray_Icon_On%
} Else {
    Menu, Tray, Icon, %Tray_Icon_Off%
}
return

To pass the status (On/Off) across functions and label I've made use of a super-global variable.

(I use the naming convention to start with the prefix G_ for them)

See also

Embed Images Directly In An Ahk Script (Jack's blog)

AutoHotkey: Customize Mouse click icons on Tray Icon

No comments:

Post a Comment