Tutorial and Overview
This brief introduction will help you start scripting your own macros and
hotkeys right away.
Tutorial Contents
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
Creating a script
Each script is a plain text file containing commands to be executed by the program (AutoHotkey.exe). A script may also containhotkeysandhotstrings, 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:
Downloadand install AutoHotkey.
Right-click an empty spot on your desktop or in a folder of your choice.
In the menu that appears, selectNew -> AutoHotkey Script.
Type a name for the file, ensuring that it ends in.ahk. For example: Test.ahk
Right-click the file and choose Edit Script.
On a new blank line, type the following:
#space::Run www.google.com
In the line above, the first character "#" stands for the Windows key; so
#space means holding down the Windows key then pressing the spacebar to activate
the 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:
Save and close the file.
Double-click the file to launch it. A new icon appears in the taskbar
notification area.
Hold down the Windows key and press the spacebar. A web page opens in the
default browser.
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 with its own icon in
the taskbar notification area.
Each script can have multiplehotkeysandhotstrings.
To have a script launch automatically when you start your computer,create a shortcut in the Start Menu's Startup folder.
Launching a program or document
TheRuncommand 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 ahotkey 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 linebeneaththe hotkey definition and make the last line areturn. 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 abuilt-in variable. By using it rather than something likeC:\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, useRunWaitinstead of Run. In the following example, theMsgBoxcommand 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 -- clickhere.
Sending keystrokes and mouse clicks
Keystrokes are sent to the active (foremost) window by using theSendcommand. 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 theSendcommand for a complete list of special characters and keys.
Finally, keystrokes can also be sent in response to abbreviations you type, which are known ashotstrings. 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 Window Spy, which is included with AutoHotkey. The following steps apply to the Window Spy method:
Launch Window Spy from a script's tray-icon menu or the Start Menu.
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).
Move the mouse cursor to the desired position in the target window and write
down the mouse coordinates displayed by Window Spy (or on Windows XP and
earlier, press Shift-Alt-Tab to activate Window Spy so that the "frozen"
coordinates can be copied and pasted).
Apply the coordinates discovered above to theClickcommand. The following example clicks the left mouse button:
Click 112, 223
To move the mouse without clicking, useMouseMove. To drag the mouse, useMouseClickDrag.
Activating and manipulating windows
To activate a window (make it foremost), useWinActivate. To detect whether a window exists, useIfWinExistorWinWait. 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 thelast found windowto 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 theInputBoxcommand to prompt the user to type a string. UseFileSelectFileorFileSelectFolderto have the user select a file or folder. For more advanced tasks, use theGuicommand 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 acontinuation section). For example:
MsgBox This is ok.MsgBox,This is ok too (it has an explicit comma).
Using variables and the clipboard
Avariableis 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 infunctions, 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 ofMyVar1is enclosed in percent signs. This displays the contents ofMyVar1at 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 anexpression. 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 anexpressionto a variable as in the example below:
NetPrice := Price * (1 - Discount/100)
Seeexpressionsfor a complete list of math operators.
Clipboard: The variable namedClipboardis 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 theclipboardandvariablessections for more details.
Repeating a series of actions over and over
To perform something more than once consecutively, use aloop. The following loop shows aMsgBoxthree 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
In the example above, when the user releases the F1 key, the loop detects this and stops itself via thebreakcommand.Breakcauses execution to jump to the line after the loop's closing brace.
An alternate way to achieve the same effect is with a"while" loop:
$F1::while GetKeyState("F1", "P"); While the F1 key is being held down physically.{ Click}return
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), useFileAppendas 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, useFileDeleteprior 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 whether a file or folder exists.
FileSelectFileandFileSelectFolder: Display a dialog for the user to pick a file or folder.
FileDelete/FileRecycle: Delete/recycle one or more files. UseFileRemoveDirto delete an entire folder.
FileCopy/FileMove: Copy/move one or more files. UseFileCopyDir/FileMoveDirto copy/move an entire folder.
Files-and-folders Loop: Retrieve the files and folders contained in a folder, one at a time.
FileSetAttribandFileSetTime: Change the attributes or timestamp of one or more files.
IniRead,IniWrite, andIniDelete: Create, access, and maintain standard-format INI files.
RegRead,RegWrite,RegDelete, andRegistry Loop: Work with the Windows registry.
Overview of other features
See thecommand listfor an overview of every command.
网友评论