Sunteți pe pagina 1din 16

Frequently Asked Questions (FAQ)

If your question is not in the list below, check the community-driven FAQ on autoHotkey.net.
Language Syntax
When are quotation marks used with commands and their parameters?
When exactly are variable names enclosed in percent signs?
When should percent signs and commas be escaped?
Common Tasks
Why do some lines in my script never execute?
Why does my script run fine in XP but not in Vista or Windows 7 or 8?
Why is the Run command unable to launch my game or program?
How can the output of a command line operation be retrieved?
How can a script close, pause, or suspend other script(s)?
How can a repeating action be stopped without exiting the script?
How can performance be improved for games or at other times when the CPU is under
heavy load?
How can context sensitive help for AutoHotkey commands be used in any editor?
How to detect when a web page is finished loading?
How can dates and times be compared or manipulated?
Why don't Hotstrings, Send, and MouseClick work in certain games?
How can Winamp be controlled even when it isn't active?
How can MsgBox's button names be changed?
Hotkeys, Hotstrings, and Remapping
How do I put my hotkeys and hotstrings into effect automatically every time I start my
PC?
I'm having trouble getting my mouse buttons working as hotkeys. Any advice?
How can tab and space be defined as hotkeys?
How can keys or mouse buttons be remapped so that they become different keys?
How can a hotkey or hotstring be made exclusive to certain program(s)? In other words,
I want a certain key to act as it normally does except when a specific window is active.
How can a prefix key be made to perform its native function rather than doing nothing?
How can the built-in Windows shortcut keys, such as Win+U (Utility Manager) and
Win+R (Run), be changed or disabled?
My keypad has a special 000 key. Is it possible to turn it into a hotkey?
Language Syntax
When are quotation marks used with commands and their parameters?
Double quotes (") have special meaning only within expressions. In all other places, they are
treated literally as if they were normal characters. However, when a script launches a program or
document, the operating system usually requires quotes around any command-line parameter that
contains spaces, such as in this example: Run, Notepad.exe "C:\My Documents\Address
List.txt"
When exactly are variable names enclosed in percent signs?
Variable names are always enclosed in percent signs except in cases illustrated in bold below:
1) In parameters that are input or output variables: StringLen, OutputVar, InputVar
2) On the left side of an assignment: Var = 123abc
3) On the left side of traditional (non-expression) if-statements: If Var1 < %Var2%
4) Everywhere in expressions. For example:
If (Var1 <> Var2)
Var1 := Var2 + 100
When should percent signs and commas be escaped?
Literal percent signs must be escaped by preceding them with an accent/backtick. For example:
MsgBox The current percentage is 25`%. Literal commas must also be escaped (`,) except
when used in MsgBox or the last parameter of any command (in which case the accent is
permitted but not necessary).
When commas or percent signs are enclosed in quotes within an expression, the accent is
permitted but not necessary. For example: Var := "15%"
Common Tasks
Why do some lines in my script never execute?
Any lines you want to execute immediately when the script starts should appear at the top of the
script, prior to the first hotkey, hotstring, or Return. For details, see auto-execute section.
Also, a hotkey that executes more than one line must list its first line beneath the hotkey, not on
the same line. For example:
#space:: ; Win+Spacebar
Run Notepad
WinWaitActive Untitled - Notepad
WinMaximize
return
Why does my script run fine in XP but not in Vista or Windows 7 or 8?
A common problem when moving from XP to Vista or a later version of Windows is that
programs which are "elevated" (run as administrator) block hotkeys or refuse to be automated.
There are at least three workarounds:
Modify AutoHotkey.exe to enable interaction with administrative programs. This has
some drawbacks. For more information see
http://www.autohotkey.com/board/topic/70449-enable-interaction-with-
administrative-programs/
Run the script as administrator. Note that this also causes any programs launched by the
script to run as administrator.
Disable User Account Control (not recommended).
SoundGet, SoundSet, SoundGetWaveVolume and SoundSetWaveVolume have limited
functionality on Windows Vista and later -- they typically affect only the script itself. See the
Remarks section of SoundGet and SoundSet for workarounds.
Why is the Run command unable to launch my game or program?
Some programs need to be started in their own directories (when in doubt, it is usually best to do
so). For example:
Run, %A_ProgramFiles%\Some Application\App.exe, %A_ProgramFiles%\Some
Application
How can the output of a command line operation be retrieved?
Testing shows that due to file caching, a temporary file can be very fast for relatively small
outputs. In fact, if the file is deleted immediately after use, it often does not actually get written
to disk. For example:
RunWait %comspec% /c dir > C:\My Temp File.txt
FileRead, VarToContainContents, C:\My Temp File.txt
FileDelete, C:\My Temp File.txt
To avoid using a temporary file (especially if the output is large), consider using CmdRet or
StdoutToVar.
How can a script close, pause, or suspend other script(s)?
First, here is an example that closes another script:
DetectHiddenWindows On ; Allows a script's hidden main window to be
detected.
SetTitleMatchMode 2 ; Avoids the need to specify the full path of the file
below.
WinClose Script's File Name.ahk - AutoHotkey ; Update this to reflect the
script's name (case sensitive).
To suspend or pause another script, replace the last line above with one of these:
PostMessage, 0x111, 65305,,, Script's File Name.ahk - AutoHotkey ; Suspend.
PostMessage, 0x111, 65306,,, Script's File Name.ahk - AutoHotkey ; Pause.
How can a repeating action be stopped without exiting the script?
To pause or resume the entire script at the press of a key, assign a hotkey to the Pause command
as in this example:
^!p::Pause ; Press Ctrl+Alt+P to pause. Press it again to resume.
To stop an action that is repeating inside a Loop, consider the following working example, which
is a hotkey that both starts and stops its own repeating action. In other words, pressing the hotkey
once will start the Loop. Pressing the same hotkey again will stop it.
#MaxThreadsPerHotkey 3
#z:: ; Win+Z hotkey (change this hotkey to suit your preferences).
#MaxThreadsPerHotkey 1
if KeepWinZRunning ; This means an underlying thread is already running the
loop below.
{
KeepWinZRunning := false ; Signal that thread's loop to stop.
return ; End this thread so that the one underneath will resume and see
the change made by the line above.
}
; Otherwise:
KeepWinZRunning := true
Loop
{
; The next four lines are the action you want to repeat (update them to
suit your preferences):
ToolTip, Press Win-Z again to stop this from flashing.
Sleep 1000
ToolTip
Sleep 1000
; But leave the rest below unchanged.
if not KeepWinZRunning ; The user signaled the loop to stop by pressing
Win-Z again.
break ; Break out of this loop.
}
KeepWinZRunning := false ; Reset in preparation for the next press of this
hotkey.
return
How can performance be improved for games or at other times when the CPU is
under heavy load?
If a script's Hotkeys, Clicks, or Sends are noticeably slower than normal while the CPU is under
heavy load, raising the script's process-priority may help. To do this, include the following line
near the top of the script:
Process, Priority, , High
How can context sensitive help for AutoHotkey commands be used in any editor?
Rajat created this script.
How to detect when a web page is finished loading?
With Internet Explorer, perhaps the most reliable method is to use DllCall and COM as
demonstrated at www.autohotkey.com/forum/topic19256.html. On a related note, the contents
of the address bar and status bar can be retrieved as demonstrated at
www.autohotkey.com/forum/topic19255.html.
Older, less reliable method: The technique in the following example will work with MS
Internet Explorer for most pages. A similar technique might work in other browsers:
Run, www.yahoo.com
MouseMove, 0, 0 ; Prevents the status bar from showing a mouse-hover link
instead of "Done".
WinWait, Yahoo! -
WinActivate
StatusBarWait, Done, 30
if ErrorLevel
MsgBox The wait timed out or the window was closed.
else
MsgBox The page is done loading.
How can dates and times be compared or manipulated?
The EnvAdd command can add or subtract a quantity of days, hours, minutes, or seconds to a
time-string that is in the YYYYMMDDHH24MISS format. The following example subtracts 7 days
from the specified time: EnvAdd, VarContainingTimestamp, -7, days.
To determine the amount of time between two dates or times, see EnvSub, which gives an
example. Also, the built-in variable A_Now contains the current local time. Finally, there are
several built-in date/time variables, as well as the FormatTime command to create a custom
date/time string.
Why do Hotstrings, Send, and Click have no effect in certain games?
Some games use DirectInput exclusively. As a side-effect, they might ignore all simulated
keystrokes and mouse clicks. To work around this, try one of the following (or a combination):
Use SendPlay via: 1) the SendPlay command; 2) using SendMode Play; and/or 3) the
hotstring option SP.
Increase SetKeyDelay. For example:
SetKeyDelay, 0, 50
SetKeyDelay, 0, 50, Play
Try ControlSend, which might work in cases where the other Send modes fail.
How can Winamp be controlled even when it isn't active?
See Automating Winamp.
How can MsgBox's button names be changed?
Here is an example.
Hotkeys, Hotstrings, and Remapping
How do I put my hotkeys and hotstrings into effect automatically every time I
start my PC?
There is a folder in the Start Menu called Startup. If you put a shortcut to your script in that
folder, the script will launch automatically every time you start your PC. To create a shortcut:
1. Find the script file, select it, and press Control-C.
2. Right-click the Start button (typically at the lower left corner of the screen) and choose
"Explore All Users".
3. Navigate to the Startup folder inside the Programs folder.
4. From the menu bar, choose Edit -> Paste Shortcut. The shortcut to the script should now
be in the Startup folder.
I'm having trouble getting my mouse buttons working as hotkeys. Any advice?
Note that mouse hotkeys are not currently possible on Windows 95/98/Me. On other operating
systems, the left and right mouse buttons should be assignable normally (for example,
#LButton:: is the Win+LeftButton hotkey). Similarly, the middle button and the turning of the
mouse wheel should be assignable normally except on mice whose drivers directly control those
buttons.
The fourth button (XButton1) and the fifth button (XButton2) might be assignable if your mouse
driver allows their clicks to be seen by the system. If they cannot be seen -- or if your mouse has
more than five buttons that you want to use -- you can try configuring the software that came
with the mouse (sometimes accessible in the Control Panel or Start Menu) to send a keystroke
whenever you press one of these buttons. Such a keystroke can then be defined as a hotkey in a
script. For example, if you configure the fourth button to send Control+F1, you can then
indirectly configure that button as a hotkey by using ^F1:: in a script.
If you have a five-button mouse whose fourth and fifth buttons cannot be seen, you can try
changing your mouse driver to the default driver included with the OS. This assumes there is
such a driver for your particular mouse and that you can live without the features provided by
your mouse's custom software.
How can Tab and Space be defined as hotkeys?
Use the names of the keys (Tab and Space) rather than their characters. For example, #Space is
Win+Space and ^!Tab is Control+Alt+Tab.
How can keys or mouse buttons be remapped so that they become different keys?
This is described on the remapping page.
How can a hotkey or hotstring be made exclusive to certain program(s)? In other
words, I want a certain key to act as it normally does except when a specific
window is active.
The preferred method is #IfWinActive. For example:
#IfWinActive, ahk_class Notepad
^a::MsgBox You pressed Control-A while Notepad is active.
Windows 95/98/Me: Although the above method works, pressing Control-A in a window other
than Notepad will do nothing at all (not even its native function). To work around this, use:
$^a::Send ^a ; This hotkey must be listed first on Windows 9x. The $ prefix
allows it to "send itself".
#IfWinActive, ahk_class Notepad
^a::MsgBox You pressed Control-A while Notepad is active.
How can a prefix key be made to perform its native function rather than doing
nothing?
Consider the following example, which makes Numpad0 into a prefix key:
Numpad0 & Numpad1::MsgBox, You pressed Numpad1 while holding down Numpad0.
Now, to make Numpad0 send a real Numpad0 keystroke whenever it wasn't used to launch a
hotkey such as the above, add the following hotkey:
$Numpad0::Send, {Numpad0}
The $ prefix is needed to prevent a warning dialog about an infinite loop (since the hotkey "sends
itself"). In addition, the above action occurs at the time the key is released.
How can the built-in Windows shortcut keys, such as Win+U (Utility Manager)
and Win+R (Run), be changed or disabled?
Here are some examples.
My keypad has a special 000 key. Is it possible to turn it into a hotkey?
You can, but only if you're running Windows NT, 2000, XP, or beyond. This example script
makes the 000 key into an equals key. You can change the action by replacing the "Send, =" line
with line(s) of your choice.

Tutorial and Overview
This brief introduction will help you start scripting your own macros and hotkeys right away.
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. 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. Download 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.
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 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:
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 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 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 multiple hotkeys and hotstrings.
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
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 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 Window Spy, which is included
with AutoHotkey. The following steps apply to the Window Spy method:
1. Launch Window Spy from a script'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 on Windows XP and earlier, 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, use a loop. 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
In the example above, when 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.
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), 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:
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.
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, IniWrite, and IniDelete: Create, access, and maintain standard-format INI files.
RegRead, RegWrite, RegDelete, and Registry Loop: Work with the Windows registry.
Overview of other features
See the command list for an overview of every command.

S-ar putea să vă placă și