Quick Start Tutorials

29/07/2009 15:47

Tutorial and Overview

This brief introduction will help you start scripting your own macros and hotkeys right away.

Tutorial Contents

Creating a script

Each script is a plain text file containing commands to be executed by the program (AutoHotkey.exe). A script may also contain hotkeys and hotstrings, or even consist entirely of them. However, in the absence of hotkeys and hotstrings, a script will perform its commands sequentially from top to bottom the moment it is launched.

To create a new script:

  1. Open Windows Explorer and navigate to a folder of your choice.
  2. Pull down the File menu and choose New >> AutoHotkey Script (or New >> Text Document).
  3. Type a name for the file, ensuring that it ends in .ahk. For example: Test.ahk
  4. Right-click the file and choose Edit Script.
  5. On a new blank line, type the following:
    #space::Run www.google.com

The symbol # stands for the Windows key, so #space means holding down the Windows key then pressing the spacebar to activate a hotkey. The :: means that the subsequent command should be executed whenever this hotkey is pressed, in this case to go to the Google web site. To try out this script, continue as follows:

  1. Save and close the file.
  2. In Windows Explorer, double-click the script to launch it. A new tray icon appears.
  3. Hold down the Windows key and press the spacebar. A web page opens in the default browser.
  4. To exit or edit the script, right click its tray icon.

Note: Multiple scripts can be running simultaneously, each with its own tray icon. Furthermore, each script can have multiple hotkeys and hotstrings.

Launching a program or document

The Run command is used to launch a program, document, URL, or shortcut. Here are some common examples:

Run Notepad
Run C:\My Documents\Address List.doc
Run C:\My Documents\My Shortcut.lnk
Run www.yahoo.com
Run mailto:someone@somedomain.com

A hotkey can be assigned to any of the above examples by including a hotkey label. In the first example below, the assigned hotkey is Win+N, while in the second it is Control+Alt+C:

#n::Run Notepad
^!c::Run calc.exe

The above examples are known as single-line hotkeys because each consists of only one command. To have more than one command executed by a hotkey, put the first line beneath the hotkey definition and make the last line a return. For example:

#n::
Run http://www.google.com
Run Notepad.exe
return

If the program or document to be run is not integrated with the system, specify its full path to get it to launch:

Run %A_ProgramFiles%\Winamp\Winamp.exe

In the above example, %A_ProgramFiles% is a built-in variable. By using it rather than something like C:\Program Files, the script is made more portable, meaning that it would be more likely to run on other computers. Note: The names of commands and variables are not case sensitive. For example, "Run" is the same as "run", and "A_ProgramFiles" is the same as "a_programfiles".

To have the script wait for the program or document to close before continuing, use RunWait instead of Run. In the following example, the MsgBox command will not execute until after the user closes Notepad:

RunWait Notepad
MsgBox The user has finished (Notepad has been closed).

To learn more about launching programs -- such as passing parameters, specifying the working directory, and discovering a program's exit code -- click here.

Sending keystrokes and mouse clicks

Keystrokes are sent to the active (foremost) window by using the Send command. In the following example, Control+Alt+S becomes a hotkey to type a signature (ensure that a window such as an editor or draft e-mail message is active before pressing Win+S):

^!s::
Send Sincerely,{Enter}John Smith
return

In the above example, all characters are sent literally except {Enter}, which simulates a press of the Enter key. The next example illustrates some of the other commonly used special characters:

Send ^c!{tab}pasted:^v

The line above sends a Control+C followed by an Alt+Tab followed by the string "pasted:" followed by a Control+V. See the Send command for a complete list of special characters and keys.

Finally, keystrokes can also be sent in response to abbreviations you type, which are known as hotstrings. For example, whenever you type Btw followed by a space or comma, the following line will replace it with "By the way":

::btw::by the way


Mouse Clicks
: To send a mouse click to a window it is first necessary to determine the X and Y coordinates where the click should occur. This can be done with either AutoScriptWriter or Window Spy, which are included with AutoHotkey. The following steps apply to the Window Spy method:

  1. Launch Window Spy from the program's tray-icon menu or the Start Menu.
  2. Activate the window of interest either by clicking its title bar, alt-tabbing, or other means (Window Spy will stay "always on top" by design).
  3. Move the mouse cursor to the desired position in the target window and write down the mouse coordinates displayed by Window Spy (or press Shift-Alt-Tab to activate Window Spy so that the "frozen" coordinates can be copied and pasted).
  4. Apply the coordinates discovered above to the Click command. The following example clicks the left mouse button:
    Click 112, 223

To move the mouse without clicking, use MouseMove. To drag the mouse, use MouseClickDrag.

Activating and manipulating windows

To activate a window (make it foremost), use WinActivate. To detect whether a window exists, use IfWinExist or WinWait. The following example illustrates these commands:

IfWinExist Untitled - Notepad
{
    WinActivate
}
else
{
    Run Notepad
    WinWait Untitled - Notepad
    WinActivate
}

The above example first searches for any existing window whose title starts with "Untitled - Notepad" (case sensitive). If such a window is found, it is activated. Otherwise, Notepad is launched and the script waits for the Untitled window to appear, at which time it is activated. The above example also utilizes the last found window to avoid the need to specify the window's title to the right of each WinActivate.

Some of the other commonly used window commands are:

  • IfWinActive: Checks if the specified window is currently active.
  • WinWaitActive: Waits for the specified window to become active (typically used after sending a window-activating keystroke such as pressing Control-F for "Find").
  • WinClose: Closes the specified window.
  • WinMove: Moves and/or resizes the specified window.
  • WinMinimize, WinMaximize, WinRestore: Minimizes, maximizes, or restores the specified window, respectively.

Getting input from the user with MsgBox, InputBox, etc.

The following example displays a dialog with two buttons (YES and NO):

MsgBox, 4, , Would you like to continue?
IfMsgBox, No
    return
; Otherwise, the user picked yes.
MsgBox You pressed YES.

Use the InputBox command to prompt the user to type a string. Use FileSelectFile or FileSelectFolder to have the user select a file or folder. For more advanced tasks, use the Gui command to create custom data entry forms and user interfaces.

Tip: You may have noticed from the other examples that the first comma of any command may be omitted (except when the first parameter is blank or starts with := or =, or the command is alone at the top of a continuation section). For example:

MsgBox This is ok.
MsgBox, This is ok too (it has an explicit comma).

Using variables and the clipboard

A variable is an area of memory in which the script stores text or numbers. A variable containing only digits (with an optional decimal point) is automatically interpreted as a number when a math operation or comparison requires it.

With the exception of local variables in functions, all variables are global; that is, their contents may be read or altered by any part of the script. In addition, variables are not declared; they come into existence simply by using them (and each variable starts off empty/blank).

To assign a string to a variable, follow these examples:

MyVar1 = 123
MyVar2 = my string

To compare the contents of a variable to a number or string, follow these examples:

if MyVar2 = my string
{
    MsgBox MyVar2 contains the string "my string".
}
if MyVar1 >= 100
{
    MsgBox MyVar1 contains %MyVar1%, which is a number greater than or equal to 100.
}

In the MsgBox line above, notice that the second occurrence of MyVar1 is enclosed in percent signs. This displays the contents of MyVar1 at that position. The same technique can be used to copy the contents of one variable to another. For example:

MyVarConcatenated = %MyVar1% %MyVar2%

The line above stores the string "123 my string" (without the quotes) in the variable MyVarConcatenated.

To compare the contents of a variable with that of another, consider this example:

if (ItemCount > ItemLimit)
{
    MsgBox The value in ItemCount, which is %ItemCount%, is greater than %ItemLimit%.
}

Notice that the first line of the example above contains parentheses. The parentheses signify that the if-statement contains an expression. Without them, that line would be considered a "non-expression if-statement", and thus it would need percent signs around ItemLimit. Such if-statements are limited to a single comparison operator; that is, they cannot contain math operators or conjunctions such as "AND" and "OR".


Math
: To perform a math operation, use the colon-equal operator (:=) to assign the result of an expression to a variable as in the example below:

NetPrice := Price * (1 - Discount/100)

See expressions for a complete list of math operators.


Clipboard: The variable named Clipboard is special because it contains the current text on the Windows clipboard. Even so, it can be used as though it were a normal variable. For example, the following line would display the current contents of the clipboard:

MsgBox %clipboard%

To alter the clipboard, consider the following example, which replaces the current contents of the clipboard with new text:

clipboard = A line of text.`r`nA second line of text.`r`n

In the above, `r and `n (accent followed by the letter "r" or "n") are used to indicate two special characters: carriage return and linefeed. These two characters start a new line of text as though the user had pressed Enter.

To append text to the clipboard (or any other variable), follow this example:
clipboard = %clipboard% And here is the text to append.

See the clipboard and variables sections for more details.

Repeating a series of actions over and over

To perform something more than once consecutively, a loop is the answer. The following loop shows a MsgBox three times:

Loop 3
{
    MsgBox This window will be displayed three times.
}

You could also specify a variable after the word Loop, which is useful in situations where the number of iterations is determined somewhere inside the script:

Loop %RunCount%
{
    Run C:\Check Server Status.exe
    Sleep 60000  ; Wait 60 seconds.
}

In the above, the loop is performed the specified number of times unless RunCount contains 0, in which case the loop is skipped entirely.

A loop may also terminate itself when one or more conditions change. The following example clicks the left mouse button repeatedly while the user is holding down the F1 key:

$F1::  ; Make the F1 key into a hotkey (the $ symbol facilitates the "P" mode of GetKeyState below).
Loop  ; Since no number is specified with it, this is an infinite loop unless "break" or "return" is encountered inside.
{
    if not GetKeyState("F1", "P")  ; If this statement is true, the user has physically released the F1 key.
        break  ; Break out of the loop.
    ; Otherwise (since the above didn't "break"), keep clicking the mouse.
    Click  ; Click the left mouse button at the cursor's current position.
}
return

The example above is functionally identical to what is sometimes called a "while...do" loop. The phrase "while...do" refers to the fact that this loop does something repeatedly while certain condition(s) remain true. In this case, the loop continues clicking the left mouse button while the F1 key is being held down. When the user releases F1, the loop detects this and stops itself via the break command. Break causes execution to jump to the line after the loop's closing brace.

The examples shown above are general-purpose loops. For more specialized needs, consider one of the following loops:

File-reading/writing loop: Retrieves the lines in a text file, one at a time. This can be used to transform a file into a different format on a line-by-line basis. It can also be used to search for lines matching your criteria.

Files and folders loop: Retrieves the specified files or folders, one at a time. This allows an operation to be performed upon each file or folder that meets your criteria.

Parsing loop: Retrieves substrings from a string, one at a time. This allows a string such as "Red,Green,Blue" to be easily broken down into its three component fields.

Registry loop: Retrieves the contents of the specified registry subkey, one item at a time.

Manipulating files and folders

To add text to the end of a file (or create a new file), use FileAppend as shown in the following example. Note that it uses `n (linefeed) to start a new line of text afterward:

FileAppend, A line of text to append.`n, C:\My Documents\My Text File.txt

To overwrite an existing file, use FileDelete prior to FileAppend. For example:

FileDelete, C:\My Documents\My Text File.txt

Some of the other commonly used file and folder commands are:

Back