Vous êtes sur la page 1sur 4

Home | Dow nload | Documentation | Changelog | Support | Forum | W iki

Search

Tutorial and Overview


This brief introduction w ill help you start scripting your ow n macros and hotkeys right aw ay.

Tutorial Contents
Creating a script
Launching a program or document
Sending keystrokes and mouse clicks
Activating and manipulating windows
Getting input from the user with MsgBox, InputBox, etc.
Using variables and the clipboard
Repeating a series of actions over and over
Manipulating files and folders
Overview of other features

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. How ever, in the absence of hotkeys and hotstrings, a script w ill perform its commands sequentially
from top to bottom the moment it is launched.
To create a new script:
1. Dow nload and install AutoHotkey.
2. Right-click an empty spot on your desktop or in a folder of your choice.
3. In the menu that appears, select New -> AutoHotkey Script. (Alternatively, select New -> Text Document.)
4. Type a name for the file, ensuring that it ends in .ahk. For example: Test.ahk
5. Right-click the file and choose Edit Script.
6. On a new blank line, type the follow ing:
#space::Run w w w .google.com
In the line above, the first character "#" stands for the W indow s key; so #space means holding dow n the W indow s key then pressing the
spacebar to activate the hotkey. The :: means that the subsequent command should be executed w henever this hotkey is pressed, in this case
to go to the Google w eb site. To try out this script, continue as follow s:
1. Save and close the file.
2. Double-click the file to launch it. A new icon appears in the taskbar notification area.
3. Hold dow n the W indow s key and press the spacebar. A w eb page opens in the default brow ser.
4. To exit or edit the script, right-click the green "H" icon in the taskbar notification area.
Notes:
Multiple scripts can be running simultaneously, each w ith its ow n icon in the taskbar notification area.
Each script can have multiple hotkeys and hotstrings.
To have a script launch automatically w hen you start your computer, create a shortcut in the Start Menu's Startup folder.

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 w w w .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 W in+N,
w hile in the second it is Control+Alt+C:

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

The above examples are know n 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://w w w .google.com
Run Notepad.exe
return

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

Run %A_ProgramFiles%\W inamp\W inamp.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 w ould 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 w ait for the program or document to close before continuing, use RunWait instead of Run. In the follow ing example, the
MsgBox command w ill not execute until after the user closes Notepad:

RunWait Notepad

converted by Web2PDFConvert.com
MsgBox The user has finished (Notepad has been closed).

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

Sending keystrokes and mouse clicks


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

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

In the above example, all characters are sent literally except {Enter}, w hich 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 follow ed by an Alt+Tab follow ed by the string "pasted:" follow ed 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, w hich are know n as hotstrings. For example, w henever you type Btw
follow ed by a space or comma, the follow ing line w ill replace it w ith "By the w ay":

::btw ::by the w ay

Mouse Clicks: To send a mouse click to a w indow it is first necessary to determine the X and Y coordinates w here the click should occur. This can
be done w ith either AutoScriptW riter or W indow Spy, w hich are included w ith AutoHotkey. The follow ing steps apply to the W indow Spy method:
1. Launch W indow Spy from a script's tray-icon menu or the Start Menu.
2. Activate the w indow of interest either by clicking its title bar, alt-tabbing, or other means (W indow Spy w ill stay "alw ays on top" by design).
3. Move the mouse cursor to the desired position in the target w indow and w rite dow n the mouse coordinates displayed by W indow Spy (or
on W indow s XP and earlier, press Shift-Alt-Tab to activate W indow Spy so that the "frozen" coordinates can be copied and pasted).
4. Apply the coordinates discovered above to the Click command. The follow ing example clicks the left mouse button:
Click 112, 223
To move the mouse w ithout clicking, use MouseMove. To drag the mouse, use MouseClickDrag.

Activating and manipulating windows


To activate a w indow (make it foremost), use W inActivate. To detect w hether a w indow exists, use IfW inExist or W inWait. The follow ing example
illustrates these commands:

IfW inExist Untitled - Notepad


{
W inActivate
}
else
{
Run Notepad
W inWait Untitled - Notepad
W inActivate
}

The above example first searches for any existing w indow w hose title starts w ith "Untitled - Notepad" (case sensitive). If such a w indow is
found, it is activated. Otherw ise, Notepad is launched and the script w aits for the Untitled w indow to appear, at w hich time it is activated. The
above example also utilizes the last found w indow to avoid the need to specify the w indow 's title to the right of each W inActivate.
Some of the other commonly used w indow commands are:
IfW inActive: Checks if the specified w indow is currently active.
W inWaitActive: Waits for the specified w indow to become active (typically used after sending a w indow -activating keystroke such as
pressing Control-F for "Find").
W inClose: Closes the specified w indow .
W inMove: Moves and/or resizes the specified w indow .
W inMinimize, W inMaximize, W inRestore: Minimizes, maximizes, or restores the specified w indow , respectively.

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


The follow ing example displays a dialog w ith tw o buttons (YES and NO):

MsgBox, 4, , Would you like to continue?


IfMsgBox, No
return
; Otherw ise, 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 w hen the first parameter is
blank or starts w ith := 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 w hich the script stores text or numbers. A variable containing only digits (w ith an optional decimal point) is
automatically interpreted as a number w hen a math operation or comparison requires it.
W ith 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).

converted by Web2PDFConvert.com
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%, w hich 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" (w ithout the quotes) in the variable MyVarConcatenated.
To compare the contents of a variable w ith that of another, consider this example:

if (ItemCount > ItemLimit)


{
MsgBox The value in ItemCount, w hich 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.
W ithout them, that line w ould be considered a "non-expression if-statement", and thus it w ould 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 W indow s clipboard. Even so, it can be used as
though it w ere a normal variable. For example, the follow ing line w ould display the current contents of the clipboard:

MsgBox %clipboard%

To alter the clipboard, consider the follow ing example, w hich replaces the current contents of the clipboard w ith new text:

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

In the above, `r and `n (accent follow ed by the letter "r" or "n") are used to indicate tw o special characters: carriage return and linefeed. These
tw o 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, use a loop. The follow ing loop show s a MsgBox three times:

Loop 3
{
MsgBox This w indow w ill be displayed three times.
}

You could also specify a variable after the w ord Loop, w hich is useful in situations w here the number of iterations is determined somew here
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 w hich case the loop is skipped entirely.
A loop may also terminate itself w hen one or more conditions change. The follow ing example clicks the left mouse button repeatedly w hile the
user is holding dow n 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 w ith 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.
; Otherw ise (since the above didn't "break"), keep clicking the mouse.
Click ; Click the left mouse button at the cursor's current position.
}
return

In the example above, w hen the user releases the F1 key, 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.

converted by Web2PDFConvert.com
An alternate w ay to achieve the same effect is w ith a "w hile" loop:

$F1::
w hile GetKeyState("F1", "P") ; W hile the F1 key is being held dow n physically.
{
Click
}
return

The examples show n above are general-purpose loops. For more specialized needs, consider one of the follow ing loops:
File-reading/w riting 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 allow s 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 allow s a string such as "Red,Green,Blue" to be easily broken dow n 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 show n in the follow ing example. Note that it uses `n (linefeed) to start a
new line of text afterw ard:

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

To overw rite 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:
FileRead: Read the entire contents of a file into a variable.
File-reading Loop: Retrieve the lines in a text file, one by one.
IfExist: Determine w hether a file or folder exists.
FileSelectFile and FileSelectFolder: Display a dialog for the user to pick a file or folder.
FileDelete/FileRecycle: Delete/recycle one or more files. Use FileRemoveDir to delete an entire folder.
FileCopy/FileMove: Copy/move one or more files. Use FileCopyDir/FileMoveDir to copy/move an entire folder.
Files-and-folders Loop: Retrieve the files and folders contained in a folder, one at a time.
FileSetAttrib and FileSetTime: Change the attributes or timestamp of one or more files.
IniRead, IniW rite, and IniDelete: Create, access, and maintain standard-format INI files.
RegRead, RegW rite, RegDelete, and Registry Loop: Work w ith the W indow s registry.

Overview of other features


See the command list for an overview of every command.

Home | Dow nload | Documentation | Changelog | Support | Forum | W iki

converted by Web2PDFConvert.com

Vous aimerez peut-être aussi