The Wayback Machine - http://web.archive.org/web/20080206205241/http://www.autohotkey.com:80/press/Bedienhilfe/

A translation from the German article in c't-magazine 3/2005 (p. 196-200) with friendly authorisation by Heise Publishing.

For 0,70 Euro you can download the original article at www.heise.de/kiosk/archiv/ct/2005/3/196

Translation by: Arne and toralf

Copyright 2005 Heise Publishing, Hannover, Germany, www.heise.de


Wolfgang Reszel

Bedienhilfe (operational help)

Simple automation of Windows and programs

The open-source tool AutoHotkey sends several tools into retirement. It unites hotkey and text macros and offers a scripting-language, which is more powerful than every batch-file and easier to learn than the Windows-Scripting-Host. Beginners are able to start fast because of the scripting-language, similar to BASIC, contains a macro-recorder and syntax-checker. Advanced users are pleased with functions for graphical interfaces and a compiler, creating *.exe-files, that can be run on other Computers.

It isn't possible to describe AutoHotkey in a few sentences. However, to get a little Impression of AutoHotkey, I'll present some of the scripts I have programmed for myself:

Screenshot Eject.ahk

Screenshot QCD.ahk

Eject.ahk

QCD.ahk

The source-code of these and some other scripts are available at ctmagazin.de.

AutoHotkey v1.0.22 was part of the c't software collection in issue 24/04. But you should always get the latest version, otherwise some examples will not work correctly; the author Chris Mallett is constantly extending the performance range.

On editorials deadline, v1.0.24 had been the latest version.

You can find all the download addresses at the end of the article in chapter: Soft-Links.

AutoHotkey is installed within a few seconds. If you like to launch files by mouse later, you should take care about this during installation (activate checkbox: "Enable drag & drop onto scripts"). On first start-up, AutoHotkey is asking, whether it shall create the file "Autohotkey.ini". It's safe to allow this, afterwards the file gets opened in Notepad.

For the time being, changes aren't necessary, you can just close it.

Now a small green H icon is placed in the System Tray. You can reach the necessary tool options by its context menu.

For working more efficiently you should create a working-directory for AutoHotkey scripts and set its path to the PATH environmental variable (configuration/system control/system/extended/environmental variables; edit the "PATH" entry and add the directories path at the end). Now you may reach your scripts via start/execute.

To create a new script: Move to your working-directory, right click and choose new/AutoHotkey Script and rename it with a *.ahk as extension.

Such files with *.ahk are connected with AutoHotkey and can be open and loaded immediately by double clicking them.

In this case, nothing will happen because the script doesn't contain any command.

By selecting "Edit script" in the context menu, the script is opened in Notepad exactly like every other script.

Screenshot MED Those who prefer a more comfortable editor will find some syntax highlighting scripts for some well-known editors in the folder Extras/Editors within the AutoHotkey directory. Even an automatic installation script is ready for MED, TextPad and EditPlus.

The colour syntax highlight makes getting started with AutoHotkey much easier because one can see whether a command was written wrong. However, those who don't like to work with notepad and who lack one of the supported editors may change the standard editor for editing scripts by drag n' drop it onto my script: "change standard editor.ahk", which is a component of the download package mentioned above. It changes the menu instruction "Edit script" correspondingly.

Hotstrings

One of the core functions of AutoHotkey is working with text modules.

These "Hotstrings" react to defined key combinations the user enters in a program of his/her choice or in one the developer defined. So abbreviations are easily converted to the extended form.

The key combination is placed between 2 colons each, and is followed by text that should be substituted in place of the abbreviation. You may enter the lines of the following example into a script file and then execute it by double-click.

After that the script is interpreted and executed by AutoHotkey.

::wkr::With kind regards{Enter}{Enter}

The greeting phrase is inserted automatically as soon as the key combination "wkr" is typed in an arbitrary program and followed by a final character, which may be the return key, a comma or a space. Within the definition, more parameters can be used. For example the letter "o" between the first two colons prevents the final character from being sent to the program.

Within a few minutes a professional writer can create an individual collection of text modules without which he soon wouldn't enjoy working anymore.

Step by Step to the first Script

However, AutoHotkey scripts are far more than the collection of key combinations. With the over 200 instructions, utilities can be programmed for which a fully-grown software development kit would otherwise be needed (along with a much greater expenditure of time).

Although the AutoHotkey script language isn't by far as powerfully as Delphi, Visual Basic & Co. but for most automating tasks it is completely sufficient.

The dialect is similar to BASIC, and therefore easily to learn. Each instruction with its parameters is written in a line of its own.

To increase the clarity, you may indent scripts with tabs or spaces arbitrarily, which for example is suitable for loops. Parameters are separated from the instruction and by other parameters, with few exceptions, by commas. Even though AutoHotkey ignores the case of variables, instructions and sub-routine identifiers, it is advisable to maintain consistency with a notation of your choice. For example, I have become accustomed to writing instructions with their first letter capitalized.

Make sure to comment your scripts. A comment is started with a semicolon such as in the following quite practical script, which assigns a key combination to a function:

; Windows-Key+i
#i::
   Run, iexplore.exe
Return

By the two colons at the end of the second line, AutoHotkey recognizes that it shall process a combination of keys. The pound sign symbol stands for the Windows key, followed by the letter for the other key, in this case the I key. The instructions which shall be executed when pressing the two keys then follow. Key combinations and sub-routines, which are analogous to those of others programming languages, are finished in AutoHotkey with return. A single colon indicates a normal sub-routine which isn't connected to a hotkey and can be jumped at with the instruction GoSub. After executing the sub-routine, the Interpreter continues the script, starting at the line after the GoSub instruction. The instructions of a hotkey can also be invoked with GoSub. Both forms of sub-routines may be distributed arbitrarily in the script, but may not be interlocked with each other.

The command Run executes a program along with optional parameters as if it had been entered at the Run dialog in the start menu. In the example above, Internet Explorer is launched; every other program can be launched just as well. Within the parameters of each AutoHotkey command, all leading and final spaces are ignored. However, to improve readability of the commands, a space should be placed after every comma. (As opposed to other programming languages, text that contains spaces should not be enclosed in quotes.)

Run supports some more parameters. The second parameter indicates the working directory and the third parameter states whether a program shall be started maximized, minimized or hidden. A variable name can be placed as a fourth parameter, in which the process number (ID) is will be stored. The Web browser is started maximized with the following instruction:

Run, iexplore.exe, Max

Optional parameters are simply left empty; AutoHotkey then assumes a standard value. In this example above, Internet Explorer isn't executed in a special working directory but instead in the working directory of the script itself.

Since hotkeys frequently include only a single command, there is also a simplified notation for this, where everything is contained on one line and the return isn't needed, allowing a clearer arrangement:

#i::Run, iexplore.exe ; Win-i
#g::Run, http://www.google.de ; Win-g
; and so on, and so on ...

Run is limited not only programs but also URLs and documents, which are then opened with the associated application in Windows. Next to conventional keys on the keyboard, mouse actions can also be captured and assigned to functions. The practical mouse wheel, found on most modern mice, can be used fantastically e.g. for a small script which system-wide varies the volume:

; Win+MouseWheel forward: Louder
#WheelUp::SoundSet, +1
; Win+MouseWheel backward: Lower
#WheelDown::SoundSet, -1
; Win+Numpad0: Volume on/off
#Numpad0::SoundSet, +1,, mute

The semicolon'd comments above again explain what exactly happens, and the pound sign symbol is used again: #WheelUp reacts if the mouse wheel is rolled up or forward while the Windows key is held down; #WheelDown behaves similarly when the wheel is rolled in the reversed direction; and #Numpad0 switches the sound output completely on or off again if the key combination Windows-0 (on the number pad) is pushed. The other modifier keys have symbols of their own: the Alt-key is equal to !, the Ctrl-key to ^ and Shift to +. To distinguish between the left and the right key, a < or > is put in front of them. Finally, SoundSet is used to vary the volume in the indicated steps.

Completely variable

With variables, scripts get flexible. Besides predefined environmental variables and script properties, which can be used as a parameters for commands e.g. A_ComputerName or A_ScreenWidth, you may define your own variables, which is similar in conventional to Batch files: Variable_name = [contents]. Variables are always global, so they are available to all sub-routines and hotkeys throughout the script. Their names may consist of letters, numbers and the characters #, _, @, $, ?, [ and ]. A variable is automatically a string, e.g. with text contents (name = heise). To work with numeric variable, simply assign numbers (x = 30), AutoHotkey recognizes this automatically. Mathematical computations are still a little limited and require repetition at present: For each calculation, a separate command must be used, e.g.

Variable = 9
EnvAdd, Variable, 4
EnvMult, Variable, 3

To references a variable, e.g. process its content, enclose its name within percent signs: MsgBox, %variable%. Like in other languages, there are also commands to manipulate variables of course, for example StringLower which converts a string to lower case letters.

With the help of variables, example script 1 copies the word currently selected on the screen onto the clipboard and transmits it to the online translator leo.org – the dictionary is ready at the touch of a button. Beforehand, the previous contents of the clipboard get buffered (tmp = %Clipboard%) and restored again later (Clipboard = %tmp%). However, Clipboard is a system variable that can only handle texts. So another data type on the clipboard, e.g. a picture or a tone, is lost by the execution of this script. [Update: The ClipboardAll variable was recently added to avoid this limitation.]

Remote control

The simplest way to automate the system or an application involves the send command to transmit keystrokes to these. It transmits the keystrokes as if the user had typed them manually. The send command also plays an important role in the example just mentioned: It is used to imitate the key combination Ctrl-C for copying the highlighted word onto the clipboard. Since that key combination is recognized by nearly all Windows programs, the script's operation is independent of the program currently in foreground: Word processing, appointment book or spreadsheet analysis.

However, to execute a keyboard combination or a script only for a certain program, at first one must check whether that program is active. The following example provides a function for Internet Explorer to show the source text of a web page, which relies on the fact that Microsoft has not yet assigned Alt-F3 to any function. The script achieves this by "pressing" the Alt-key (menu call), the A key (menu view) and the Q key (for source text) one after the other: (A and Q are for German keyboard layout):

~!F3::
ifWinActive, ahk_class IEFrame
{
   Send, !aq
}
Return

The tilde (~) at the start of the keyboard combination Alt-F3 means that this is not intercepted but passed through, which prevents programs that already use Alt-F3 from stumbling. IfWinActive checks the name of the window class (ahk_class), which was previously discovered with the help of the "Window Spy" function in the Tray menu of AutoHotkey: By Shift-Alt-Tab for example one changes to the desired window to also learn from it the title, the position or the X and Y coordinates of the mouse pointer. To transmit a key combination not only to a window but to a determined part of a window, which is e.g. an entry field or a button (a "Control"), the command ControlSend can be used. A script which demonstrates the command in the interplay with the FTP client FileZilla is contained in the download package.

File system and registry

AutoHotkey cannot only manipulate programs but also windows, files and even the registry database. Example 2 deletes all files from the cache of the Internet Explorer, more exactly from the directory "Temporary Internet files" which are older than a week. Of course such a script could be assigned to a hotkey; however it is even better to put it in a separate script file which is invoked at every system start.

RegRead reads a value from the Registry – in this case, the path of the directory – and stores it in the variable tempInternetFiles. The script then passes through a loop in which the second parameter (0) means that only files shall be checked and the third one (1) defines that also files from the subdirectories are taken into account. The subtracting command EnvSub determines the age of the each file by deducting from the date today = %A_Now% (system variable) the date of the last modification A_LoopFileTimeModified. The command FileDelete within the If block finally deletes each file that is older than seven days. Blocks and loops start with { and end with }.

Niceties

While AutoHotkey usually terminates scripts after the last instruction is executed, scripts which wait for a key combination or a key sequence remain permanent in memory. To grant this status to other scripts as well, simply insert a line at the beginning of the file with the contents #Persistent; if necessary, one can then terminate the script by specifying ExitApp. It should always be remembered that after changing a script – whether persistent or not – it has to be reloaded into memory, since otherwise it will continue to run with the old settings. One can take care of this by either double-click in Explorer or selecting the context menu instruction "Reload script". It's more comfortable to insert a routine in the script which automatically reloads it after every modification, see example 3. This is especially and enormously helpful during the programming and testing stage. Each loaded script is started as an independent process, which can be seen as an additional icon in the System Tray. Since each running script uses approximately between 2 and 3 MByte of working memory, where possible you should combine scripts that are supposed to be permanently active into one to save memory.

With a right click on its icon in the System Tray, the context menu of a script gets opened. In this context menu the script can be ended, edited, paused or stopped for a short time from processing keyboard combinations ("Suspend Hotkeys"). The instruction "Open" or a double-click on the icon fetches the real program interface of AutoHotkey to the foreground. In the view menu one can retrieve rather a lot useful information, which are very helpful for bug searching within a script, e.g. the last executed instructions, all variables and their contents, assigned keyboard combinations, as well as a list of the most recently pushed keys.

Screenshot AutoScriptWriter To save the annoying work of typing scripts, you can use AutoScriptWriter, which is included with AutoHotkey. It records all actions and puts them into the script language. It is an especially indispensable too for determining mouse positions. You will notice, though, that a script created by a recorder can seldom be used as-is; a little polishing is always necessary.

Drag, Drop & Exe

Parameters can be submitted to scripts on the command line or by Drag & Drop if the option was activated at installation.

The individual parameters are stored in the variables %1%, %2%, %3% and so on. The total number of incoming parameters is put into %0%. The following example copies all file names of a submitted directory onto the clipboard, which might be useful to print the contents of a freshly burned backup CD for its cover.

Copy this into a new script file:

SetWorkingDir, %1%
Loop, *.*, 1, 1
{
   All = %All%%A_LoopFileFullPath%`r`n
}
Clipboard = %All%

If you drag and drop the icon of a folder onto the script, the folder's path (which is in the variable %1%) is submitted directly to the Loop command – with the supplemented wild card *.*, which causes all files in the folder to be processed.

The two parameters that follow the *.* parameter specify that the script should include files in all subdirectories as well as the names of the subdirectories themselves. In the next line, each found file name is added to the variable All, along with a newline character (`r`n). At the end of the loop, the script copies the contents of the variable All onto the clipboard. Within the download package, you can find a more elaborate version of this script that integrates itself automatically into the context menu and is therefore always available.

By their very nature, compiled scripts (*.exe) always allow Drag & Drop. So by selecting "Compile script" in the context menu of a .ahk file, an EXE program is created, which can operate independently (without the need for AutoHotkey). A speed advantage isn't gained by compilation, however, since AutoHotkey converts each script to a fast executable Pseudo code upon launch.

Compiled scripts remain pleasantly small. The mentioned directory list coverts to approximately 180 Kbytes of disk space as an executable.

Pretty Outside

With AutoHotkey, attractive interfaces can be created for scripts. A set of commands allows dealing with standard dialogs. The example script 4 shows what one might look like. It imitates the run command shown in the Windows start menu.

Initially it displays an input box in a 240 x 110 pixel sized dialog field to prompt the user for an instruction to be run. If the user doesn't answer within ten seconds, the dialog is closed and the variable ErrorLevel is set to the value 2.

However, if the user clicks on "OK" or pushes Enter the ErrorLevel gets the value 0. An If statement checks the user's input by examining the contents of the submitted variable. If it isn't empty, a MsgBox asks the user for confirmation. Only if this is answered with "yes" (ErrorLevel = 0) will the script execute the entered instruction. The many commas for input box are unused command parameters; for example, with them it's possible to create a password field whose input is masked (hidden).

Screenshot SmartGUI Creator The Gui command offers much more powerful and flexible possibilities. However, it would exceed the scope of this article to describe it. Nevertheless it's worthwhile to experiment with it when someday the prefabricated window command shouldn't suffice. Designing Gui interfaces is usefully supported by the also-free tool SmartGUI Creator [1].

The detailed help always delivers valuable details about all AutoHotkey commands and parameters, and kind support can be found in the Internet forum [2]. In his "Showcase" [3] the author provides some interesting scripts, which may reveal many tricks by looking at them – for example: one displays an On-Screen display for the volume if it's changed and another "rolls up" a window except for its title bar. Interested users will find a script under [4] that is enormously helpful when programming with AutoHotkey: It displays tool tips to guide you while you're typing commands, regardless of which text editor you're using.

In conclusion, I would like to mention the excellent support of the author. Only a few days after I had expressed some suggestions for improvement in the forum, an updated version in which the wishes were realized was ready. Some bugs were even removed on the same day. Such exemplary behaviour is seldom, and particularly pleasant for free software.

(se)

Literature

[1] SmartGUI Creator, www.autohotkey.com/forum/viewtopic.php?t=775

[2] AutoHotkey-Forum, www.autohotkey.com/forum/

[3] AutoHotkey Script-Showcase, www.autohotkey.com/docs/scripts/index.htm

[4] Intellisense II, www.autohotkey.com/forum/viewtopic.php?t=1371&highlight=intellisense


Soft-Link 0503196 (with original german scripts)


Download: the translated scripts (51 KByte)


Copyright 2005 Heise Publishing, Hannover, Germany, www.heise.de

The scripts from page 199

; Example 1 from page 199: translate the selected word at leo.org with Win+Ü

#ü::
   ; save clipboard
   tmp = %ClipboardAll%
   ; simulate Ctrl+C (=selection in clipboard)
   Send, ^c
   ; save the content of the clipboard in the variable word
   word = %Clipboard%
   ; restore old content of the clipboard
   Clipboard = %tmp%
   ; show the translation of the selected word by opening dict.leo.org in the standard-browser
   Run, http://dict.leo.org/?search=%word%&searchLoc=-1&relink=on&spellToler=std&sectHdr=on&tableBorder=1&cmpType=relaxed&lang=de
Return

; Example 2 from page 199: delete temporary internet files which are older than 7 days

; get the path of "temporary internet files" from the registry
RegRead, tempInternetFiles, HKEY_CURRENT_USER, Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders, Cache
; check all files in all subfolders
Loop, %tempInternetFiles%\*.*, 0, 1
{
   today = %A_Now% ; actual date and time
   ; calculate difference
   EnvSub, today, %A_LoopFileTimeModified%, days
   if today > 7 ; if older than 7 days
   {
      ; then delete the file
      FileDelete, %A_LoopFileFullPath%
   }
}

; Example 3 from page 199: useful enhancement for your script

; start every 300ms the subroutine SkriptAktualisierung
SetTimer, SkriptAktualisierung, 300
; Windows-F9: open the actual script in a text-editor
#F9::Run, C:\programme\editor\editor.exe %A_ScriptFullPath% ; Win+F9

; subroutine: reloads the script if it has been modified
SkriptAktualisierung:
   FileGetAttrib, attribs, %A_ScriptFullPath% ; attributes of the script-file
   ifInString, attribs, A ; archive-attribute set?
   {
      FileSetAttrib,-A, %A_ScriptFullPath% ; delete archive-attribute
      SplashTextOn,,, Updated script, ; message on screen
      Sleep, 500 ; wait 500 ms
      Reload ; reload script (message dissapears)
   }
Return

; Example 4 from page 199: "Run as"-Command

InputBox, varInput, Run as, Please enter command:,, 240, 110,,,, 10, charmap.exe
if ErrorLevel = 0 ; OK or Enter
{
   if varInput <> ; if input not empty
   {
      MsgBox, 36, safety question, Do you really want to start %varInput%?
      if ErrorLevel = 0 ; if the answer was yes
      {
         Run, %varInput% ; execute the command
      }
}

Copyright 2005 Heise Publishing, Hannover, Germany, www.heise.de