Autohotkey Tutorial S
Autohotkey Tutorial S
Search
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.
2.
3.
4.
Run
Run
Run
Run
Run
Notepad
C:\My Documents\Address List.doc
C:\My Documents\My Shortcut.lnk
www.yahoo.com
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.
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 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.
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.
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.
-- Home --
Mouse remapping: To remap the mouse instead of the keyboard, use the same approach. For example:
MButton::Shift
XButton1::LButton
Makes the fourth mouse button behave like the left mouse button.
RAlt::RButton
Makes the right Alt key behave like the right mouse button.
Makes Capslock become a Control key. To retain the ability to turn Capslock on and off, also add the remapping +Capslock::Capslock
(this toggles Capslock on and off when you hold down the shift key and press Capslock).
Makes the right Alt key become the Apps key (which is the key that opens the context menu).
RCtrl::RWin
Makes the right Control key become the right Windows key.
Ctrl::Alt
Makes both Control keys behave like an Alt key. However, see alt-tab issues.
^x::^c
Makes Control-X produce Control-C. It also makes Control-Alt-X produce Control-Alt-C, etc.
RWin::Return
You can try out any of these examples by copying them into a new text file such as "Remap.ahk", then launching the file.
See the Key List for a complete list of key and mouse button names.
Remarks
The directives #IfWinActive/Exist can be used to make selected remappings active only in the windows you specify. For example:
#IfWinActive ahk_class Notepad
a::b ; Makes the 'a' key send a 'b' key, but only in Notepad.
#IfWinActive ; This puts subsequent remappings and hotkeys in effect for all windows.
Remapping a key or button is "complete" in the following respects:
Holding down a modifier such as Control or Shift while typing the origin key will put that modifier into effect for the destination key. For example, b::a
would produce Control-A if you press Control-B.
Capslock generally affects remapped keys in the same way as normal keys.
The destination key or button is held down for as long as you continue to hold down the origin key. However, some games do not support remapping; in
such cases, the keyboard and mouse will behave as though not remapped.
Remapped keys will auto-repeat while being held down (except keys remapped to become mouse buttons).
Although a remapped key can trigger normal hotkeys, it cannot trigger mouse hotkeys or hook hotkeys (use ListHotkeys to discover which hotkeys are "hook").
For example, if the remapping a::b is in effect, pressing Ctrl-Alt-A would trigger the ^!b hotkey only if ^!b is not a hook hotkey. If ^!b is a hook hotkey, you can
define ^!a as a hotkey if you want Ctrl-Alt-A to perform the same action as Ctrl-Alt-B. For example:
a::b
^!a::
^!b::
ToolTip You pressed %A_ThisHotkey%.
return
If SendMode is used in the auto-execute section (top part of the script), it affects all remappings. However, since remapping uses Send {Blind} and since the
SendPlay mode does not fully support {Blind}, some remappings might not function properly in SendPlay mode (especially Control, Shift, Alt, and Win). To work
around this, avoid SendPlay in auto-execute section when you have remappings; then use the command SendPlay vs. Send in other places throughout the
script. Alternatively, you could translate your remappings into hotkeys (as described below) that explicitly call SendEvent vs. Send.
When a script is launched, each remapping is translated into a pair of hotkeys. For example, a script containing a::b actually contains the following two hotkeys
instead:
*a::
SetKeyDelay -1 ; If the destination key is a mouse button, SetMouseDelay is used instead.
Send {Blind}{b DownTemp} ; DownTemp is like Down except that other Send commands in the script won't assume "b" should stay down during their Send.
return
*a up::
SetKeyDelay -1 ; See note below for why press-duration is not specified with either of these SetKeyDelays.
Send {Blind}{b Up}
return
However, the above hotkeys vary under the following circumstances:
1. When the source key is LCtrl and the destination key is an Alt key, the line Send {Blind}{LAlt DownTemp} is replaced by Send {Blind}{LCtrl Up}{LAlt
DownTemp}. The same is true if the source is RCtrl, except that {RCtrl up} is used.
2. When a keyboard key is being remapped to become a mouse button (e.g. RCtrl::RButton), the hotkeys above use SetMouseDelay in place of
SetKeyDelay. In addition, the first hotkey above is replaced by the following, which prevents the keyboard's auto-repeat feature from generating repeated
mouse clicks:
*RCtrl::
SetMouseDelay -1
if not GetKeyState("RButton") ; i.e. the right mouse button isn't down yet.
Send {Blind}{RButton DownTemp}
return
Note that SetKeyDelay's second parameter (press duration) is omitted in the hotkeys above. This is because press-duration does not apply to down-only or uponly events such as {b down} and {b up}. However, it does apply to changes in the state of the Shift/Ctrl/Alt/Win keys, which affects remappings such as a::B
or a::^b. Consequently, any press-duration a script puts into effect via its auto-execute section will apply to all such remappings.
Although a pair of keys cannot be directly remapped to single key (e.g. it's invalid to write a & c::b), this effect can be achieved by explicitly adding the up and
down hotkeys from the example higher above: simply replace *a:: with a & c::, and replace *a up:: with a & c up::
Since remappings are translated into hotkeys as described above, the Suspend command affects them. Similarly, the Hotkey command can disable or modify a
remapping. For example, the following two commands would disable the remapping a::b.
Hotkey, *a, off
Hotkey, *a up, off
Alt-tab issues: If you remap a key or mouse button to become an Alt key, that key will probably not be able to alt-tab properly. A possible work-around is to add
the hotkey *Tab::Send {Blind}{Tab} -- but be aware that it will likely interfere with using the real Alt key to alt-tab. Therefore, it should be used only when you
alt-tab solely by means of remapped keys and/or alt-tab hotkeys.
In addition to the keys and mouse buttons on the Key List page, the source key may also be a virtual key (VKnn) or scan code (SCnnn) as described on the
special keys page. The same is true for the destination key except that it may optionally specify a scan code after the virtual key. For example,
sc01e::vk42sc030 is equivalent to a::b on most keyboard layouts.
To disable a key rather than remapping it, make it a hotkey that simply returns. For example, F1::return would disable the F1 key.
The following keys are not supported by the built-in remapping method:
The mouse wheel (WheelUp/Down/Left/Right).
Pause and Break as destination keys (since they match the names of commands).
Curly braces {} as destination keys. Instead use the VK/SC method; e.g. x::+sc01A and y::+sc01B
A percent sign (%) as a destination key. Instead use the VK/SC method.
"Return" as a destination key. Instead use "Enter".
Related Topics
List of keys and mouse buttons
GetKeyState
Remapping a joystick
Win (Windows logo key). In v1.0.48.01+, for Windows Vista and later, hotkeys that include the Windows key (e.g. #a) will wait
for the Windows key to be released before sending any text containing an "L" keystroke. This prevents the Send within such a
hotkey from locking the PC. This behavior applies to all sending modes except SendPlay (which doesn't need it) and blind mode.
Alt
Control
Shift
&
An ampersand may be used between any two keys or mouse buttons to combine them into a custom hotkey. See below for
details. Such hotkeys are ignored (not activated) on Windows 95/98/Me.
<
Use the left key of the pair. e.g. <!a is the same as !a except that only the left Alt key will trigger it. This symbol is ignored on
Windows 95/98/ME.
>
Use the right key of the pair. This symbol is ignored on Windows 95/98/ME.
AltGr (alternate graving). If your keyboard layout has an AltGr key instead of a right-Alt key, this series of symbols can usually be
used to stand for AltGr (requires Windows NT/2k/XP or later). For example:
<^>!
Wildcard: Fire the hotkey even if extra modifiers are being held down. This is often used in conjunction with remapping keys or
buttons. For example:
*#c::Run Calc.exe ; Win+C, Shift+Win+C, Ctrl+Win+C, etc. will all trigger this hotkey.
*ScrollLock::Run Notepad ; Pressing Scrolllock will trigger this hotkey even when modifer key(s) are down.
This symbol is ignored on Windows 95/98/ME.
When the hotkey fires, its key's native function will not be blocked (hidden from the system). In both of the below examples, the
user's click of the mouse button will be sent to the active window:
On Windows NT4/2k/XP or later: The $ prefix forces the keyboard hook to be used to implement this hotkey, which as a sideeffect prevents the Send command from triggering it. The $ prefix is equivalent to having specified #UseHook somewhere above
the definition of this hotkey.
On Windows 95/98/Me: The hotkey is disabled during the execution of its thread and re-enabled afterward. As a side-effect, if
#MaxThreadsPerHotkey is set higher than 1, it will behave as though set to 1 for such hotkeys.
The word UP may follow the name of a hotkey to cause the hotkey to fire upon release of the key rather than when the key is
pressed down. The following example remaps LWin to become LControl:
*LWin::Send {LControl Down}
*LWin Up::Send {LControl Up}
"Up" can also be used with normal hotkeys as in this example: ^!r Up::MsgBox You pressed and released Ctrl+Alt+R. It also
works with combination hotkeys (e.g. F1 & e Up::)
UP
Limitations: 1) "Up" does not work with joystick buttons; 2) "Up" requires Windows NT4/2000/XP or later; and 3) An "Up" hotkey
without a normal/down counterpart hotkey will completely take over that key to prevent it from getting stuck down. One way to
prevent this is to add a tilde prefix (e.g. ~LControl up::)
On a related note, a technique similar to the above is to make a hotkey into a prefix key. The advantage is that although the
hotkey will fire upon release, it will do so only if you did not press any other key while it was held down. For example:
LControl & F1::return ; Make left-control a prefix by using it in front of "&" at least once.
LControl::MsgBox You released LControl without having used it to modify any other key.
(See the Key List for a complete list of keyboard keys and mouse/joystick buttons)
Multiple hotkeys can be stacked vertically to have them perform the same action. For example:
^Numpad0::
^Numpad1::
MsgBox Pressing either Control+Numpad0 or Control+Numpad1 will display this message.
return
A key or key-combination can be disabled for the entire system by having it do nothing. The following example disables the right-side
Windows key:
RWin::return
Context-sensitive Hotkeys
The directives #IfWinActive/Exist can be used to make a hotkey perform a different action (or none at all) depending on the type of window
that is active or exists. For example:
#IfWinActive, ahk_class Notepad
^a::MsgBox You pressed Ctrl-A while Notepad is active. Pressing Ctrl-A in any other window will pass the Ctrl-A keystroke to that window.
#c::MsgBox You pressed Win-C while Notepad is active.
#IfWinActive
#c::MsgBox You pressed Win-C while any window except Notepad is active.
Numpad0 & Numpad1::MsgBox You pressed Numpad1 while holding down Numpad0.
Numpad0 & Numpad2::Run Notepad
In the above example, Numpad0 becomes a prefix key; but this also causes Numpad0 to lose its original/native function when it is pressed
by itself. To avoid this, a script may configure Numpad0 to perform a new action such as one of the following:
Numpad0::WinMaximize A ; Maximize the active/foreground window.
Numpad0::Send {Numpad0} ; Make the release of Numpad0 produce a Numpad0 keystroke. See comment below.
The presence of one of the above hotkeys causes the release of Numpad0 to perform the indicated action, but only if you did not press any
other keys while Numpad0 was being held down.
Numlock, Capslock, and Scrolllock: These keys may be forced to be "AlwaysOn" or "AlwaysOff". For example: SetNumlockState
AlwaysOn
Overriding Explorer's hotkeys: Windows' built-in hotkeys such as Win-E (#e) and Win-R (#r) can be individually overridden simply by
assigning them to an action in the script. See the override page for details.
Substitutes for Alt-Tab: Hotkeys can provide an alternate means of alt-tabbing. For example, the following two hotkeys allow you to alttab with your right hand:
RControl & RShift::AltTab ; Hold down right-control then press right-shift repeatedly to move forward.
RControl & Enter::ShiftAltTab ; Without even having to release right-control, press Enter to reverse direction.
For more details, see Alt-Tab.
#IfWinActive/Exist.
By means of the Hotkey command, hotkeys can be created dynamically while the script is running. The Hotkey command can also modify,
disable, or enable the script's existing hotkeys individually.
Joystick hotkeys do not currently support modifier prefixes such as ^ (Control) and # (Win). However, you can use GetKeyState to mimic
this effect as shown in the following example:
Joy2::
if not GetKeyState("Control") ; Neither the left nor right Control key is down.
return ; i.e. Do nothing.
MsgBox You pressed the first joystick's second button while holding down the Control key.
return
There may be times when a hotkey should wait for its own modifier keys to be released before continuing. Consider the following example:
^!s::Send {Delete}
Pressing Control-Alt-S would cause the system to behave as though you pressed Control-Alt-Delete (due to the system's aggressive
detection of Ctrl-Alt-Delete). To work around this, use KeyWait to wait for the keys to be released; for example:
^!s::
KeyWait Control
KeyWait Alt
Send {Delete}
return
If a hotkey label like #z:: produces an error like "Invalid Hotkey", your system's keyboard layout/language might not have the specified
character ("Z" in this case). Try using a different character that you know exists in your keyboard layout.
A hotkey label can be used as the target of a Gosub or Goto. For example: Gosub ^!s
One common use for hotkeys is to start and stop a repeating action, such as a series of keystrokes or mouse clicks. For an example of this,
see this FAQ topic.
Finally, each script is quasi multi-threaded, which allows a new hotkey to be launched even when a previous hotkey subroutine is still
running. For example, new hotkeys can be launched even while a MsgBox is being displayed by the current hotkey.
Alt-Tab Hotkeys
Each Alt-Tab hotkey must be a combination of two keys, which is typically achieved via the ampersand symbol (&). In the following example,
you would hold down the right Alt key and press J or K to navigate the alt-tab menu:
RAlt & j::AltTab
RAlt & k::ShiftAltTab
AltTab and ShiftAltTab are two of the special commands that are only recognized when used on the same line as a hotkey. Here is the
complete list:
AltTab: If the alt-tab menu is visible, move forward in it. Otherwise, display the menu (only if the hotkey is an "&" combination of two keys;
otherwise, it does nothing).
ShiftAltTab: Same as above except move backward in the menu.
AltTabAndMenu: If the alt-tab menu is visble, move forward in it. Otherwise, display the menu.
AltTabMenuDismiss: Close the Alt-tab menu.
To illustrate the above, the mouse wheel can be made into an entire substitute for Alt-tab. With the following hotkeys in effect, clicking the
middle button displays the menu and turning the wheel navigates through it:
MButton::AltTabMenu
WheelDown::AltTab
WheelUp::ShiftAltTab
To cancel a hotkey-invoked Alt-tab menu without activating the selected window, use a hotkey such as the following. It might require
adjustment depending on: 1) the means by which the alt-tab menu was originally displayed; and 2) whether the script has the keyboard
hook installed.
LCtrl & CapsLock::AltTab
!MButton:: ; Middle mouse button. The ! prefix makes it fire while the Alt key is down (which it is if the alt-tab menu is visible).
IfWinExist ahk_class #32771 ; Indicates that the alt-tab menu is present on the screen.
Send !{Escape}{Alt up}
return
Currently, all special Alt-tab actions must be assigned directly to a hotkey as in the examples above (i.e. they cannot be used as though they
were commands). Also, the presence of the alt-tab menu can be detected via IfWinExist ahk_class #32771
Custom alt-tab actions can also be created via hotkeys. In the following example, you would press F1 to display the menu and advance
forward in it. Then you would press F2 to activate the selected window (or press Escape to cancel):
*F1::Send {Alt down}{tab} ; Asterisk is required in this case.
!F2::Send {Alt up} ; Release the Alt key, which activates the selected window.
~*Escape::
IfWinExist ahk_class #32771
Send {Escape}{Alt up} ; Cancel the menu without activating the selected window.
return
Command List
Click on a command name for details. Commands in
are the most commonly used.
large font
Command
Description
{ ... }
A pair of braces denotes a block. Blocks are typically used with functions, Else,
Loop, While-loop, and IF-commands.
AutoTrim
Determines whether "Var1 = %Var2%" statements omit spaces and tabs from
the beginning and end of Var2.
BlockInput
Disables or enables the user's ability to interact with the computer via keyboard
and mouse.
Break
Click
Clicks a mouse button at the specified coordinates. It can also hold down a
mouse button, turn the mouse wheel, or move the mouse.
ClipWait
Continue
Skips the rest of the current loop iteration and begins a new one. Valid inside any
kind of loop.
Control
ControlClick
ControlFocus
ControlGet
ControlGetFocus
Retrieves which control of the target window has input focus, if any.
ControlGetPos
ControlGetText
ControlMove
ControlSend /
ControlSendRaw
ControlSetText
CoordMode
Sets coordinate mode for various commands to be relative to either the active
window or the screen.
Critical
DetectHiddenText
DetectHiddenWindows
DllCall()
Drive
DriveGet
DriveSpaceFree
Edit
Else
EnvAdd
Sets a variable to the sum of itself plus the given value (can also add or subtract
time from a date-time value). Synonymous with: var += value
EnvDiv
Sets a variable to itself divided by the given value. Synonymous with: var /=
value
EnvGet
EnvMult
Sets a variable to itself times the given value. Synonymous with: var *= value
EnvSet
EnvSub
Sets a variable to itself minus the given value (can also compare date-time
values). Synonymous with: var -= value
EnvUpdate
Notifies the OS and all running applications that environment variable(s) have
changed.
Exit
Exits the current thread or (if the script is not persistent and contains no
hotkeys) the entire script.
ExitApp
FileAppend
Writes text to the end of a file (first creating the file, if necessary).
FileCopy
FileCopyDir
Copies a folder along with all its sub-folders and files (similar to xcopy).
FileCreateDir
Creates a folder.
FileCreateShortcut
FileDelete
FileInstall
Includes the specified file inside the compiled version of the script.
FileGetAttrib
FileGetShortcut
Retrieves information about a shortcut (.lnk) file, such as its target file.
FileGetSize
FileGetTime
FileGetVersion
FileMove
FileMoveDir
Moves a folder along with all its sub-folders and files. It can also rename a folder.
FileRead
FileReadLine
Reads the specified line from a file and stores the text in a variable.
FileRecycle
FileRecycleEmpty
FileRemoveDir
Deletes a folder.
FileSelectFile
Displays a standard dialog that allows the user to open or save file(s).
FileSelectFolder
FileSetAttrib
Changes the attributes of one or more files or folders. Wildcards are supported.
FileSetTime
Changes the datetime stamp of one or more files or folders. Wildcards are
supported.
FormatTime
GetKeyState
Gosub
Jumps to the specified label and continues execution until Return is encountered.
Goto
GroupActivate
Activates the next window in a window group that was defined with GroupAdd.
GroupAdd
GroupClose
GroupDeactivate
Similar to GroupActivate except activates the next window not in the group.
GUI
Creates and manages windows and controls. Such windows can be used as data
entry forms or custom user interfaces.
GuiControl
GuiControlGet
HideAutoItWin, On|Off
Hotkey
if
if (expression)
IfEqual/IfNotEqual
IfExist / FileExist()
IfGreater/IfGreaterOrEqual
Compares a variable to a value. Synonymous with: if var > value | if var >=
value
IfInString / InStr()
IfLess/IfLessOrEqual
Compares a variable to a value. Synonymous with: if var < value | if var <=
value
IfMsgBox
Checks which button was pushed by the user during the most recent MsgBox
command.
IfWinActive /
IfWinNotActive
IfWinExist /
IfWinNotExist
ImageSearch
IniDelete
IniRead
IniWrite
Input
Waits for the user to type a string (not supported on Windows 9x: it does
nothing).
InputBox
KeyHistory
Displays script info and a history of the most recent keystrokes and mouse
clicks.
KeyWait
LeftClick
LeftClickDrag
ListHotkeys
Displays the hotkeys in use by the current script, whether their subroutines are
currently running, and whether or not they use the keyboard or mouse hook.
ListLines
ListVars
Loop (normal)
Retrieves the lines in a text file, one at a time (performs better than
FileReadLine).
Loop (registry)
Retrieves the contents of the specified registry subkey, one item at a time.
Menu
Creates, deletes, modifies and displays menus and menu items. Changes the
tray icon and its tooltip. Controls whether the main window of a compiled script
can be opened.
MouseClick
Clicks or holds down a mouse button, or turns the mouse wheel. NOTE: The Click
command is generally more flexible and easier to use.
MouseClickDrag
Clicks and holds the specified mouse button, moves the mouse to the destination
coordinates, then releases the button.
MouseGetPos
Retrieves the current position of the mouse cursor, and optionally which window
and control it is hovering over.
MouseMove
MsgBox
Displays the specified text in a small window containing one or more buttons
(such as Yes and No).
OnExit
OnMessage()
Specifies a function to call automatically when the script receives the specified
message.
OutputDebug
Pause
PixelGetColor
PixelSearch
PostMessage
Process
Progress
Random
RegExMatch()
RegExReplace()
RegDelete
RegRead
RegWrite
RegisterCallback()
Creates a machine-code address that when called, redirects the call to a function
in the script.
Reload
Replaces the currently running instance of the script with a new one.
RepeatEndRepeat
Return
RightClick
RightClickDrag
Run
RunAs
Specifies a set of user credentials to use for all subsequent uses of Run and
RunWait. Requires Windows 2000/XP or later.
RunWait
Send / SendRaw /
SendInput /
SendPlay
SendMessage
SendMode
Makes Send synonymous with SendInput or SendPlay rather than the default
(SendEvent). Also makes Click and MouseMove/Click/Drag use the specified
method.
SetBatchLines
SetCapslockState
Sets the state of the Capslock key. Can also force the key to stay on or off.
SetControlDelay
Sets the delay that will occur after each control-modifying command.
SetDefaultMouseSpeed
Sets the mouse speed that will be used if unspecified in Click and
MouseMove/Click/Drag.
SetFormat
Sets the format of integers and floating point numbers generated by math
operations.
SetKeyDelay
Sets the delay that will occur after each keystroke sent by Send or ControlSend.
SetMouseDelay
Sets the delay that will occur after each mouse movement or click.
SetNumlockState
Sets the state of the Numlock key. Can also force the key to stay on or off.
SetScrollLockState
Sets the state of the Scrolllock key. Can also force the key to stay on or off.
SetStoreCapslockMode
SetTimer
SetTitleMatchMode
SetWinDelay
Sets the delay that will occur after each windowing command, such as
WinActivate.
SetWorkingDir
Shutdown
Sleep
Sort
SoundBeep
SoundGet
Retrieves various settings from a sound device (master mute, master volume,
etc.)
SoundGetWaveVolume
SoundPlay
SoundSet
Changes various settings of a sound device (master mute, master volume, etc.)
SoundSetWaveVolume
SplashImage
SplashTextOn
SplashTextOff
SplitPath
Separates a file name or URL into its name, directory, extension, and drive.
StatusBarGetText
StatusBarWait
StringCaseSense
Determines whether string comparisons are case sensitive (default is "not case
sensitive").
StringGetPos /
InStr()
StringLeft
StringLen /
StrLen()
StringLower
StringMid /
SubStr()
StringReplace
StringRight
StringSplit
StringTrimLeft
StringTrimRight
StringUpper
Suspend
SysGet
Thread
Sets the priority or interruptibility of threads. It can also temporarily disable all
timers.
ToolTip
Transform
TrayTip
Creates a balloon message window near the tray icon. Requires Windows
2000/XP or later.
UrlDownloadToFile
Var = value
Var := expression
VarSetCapacity()
While-loop
WinActivate
WinActivateBottom
WinClose
WinGetActiveStats
WinGetActiveTitle
WinGetClass
WinGet
Retrieves the specified window's unique ID, process ID, process name, or a list of
its controls. It can also retrieve a list of all windows matching the specified
criteria.
WinGetPos
WinGetText
WinGetTitle
WinHide
WinKill
WinMaximize
WinMenuSelectItem
Invokes a menu item from the menu bar of the specified window.
WinMinimize
WinMinimizeAll
WinMinimizeAllUndo
WinMove
WinRestore
WinSet
Makes a variety of changes to the specified window, such as "always on top" and
transparency.
WinSetTitle
WinShow
WinWait
WinWaitActive
WinWaitClose
WinWaitNotActive
#AllowSameLineComments
Only for AutoIt v2 (.aut) scripts: Allows a comment to appear on the same line
as a command.
#ClipboardTimeout
Changes how long the script keeps trying to access the clipboard when the first
attempt fails.
#CommentFlag
Changes the script's comment symbol from semicolon to some other string.
#ErrorStdOut
Sends any syntax error that prevents a script from launching to stdout rather
than displaying a dialog.
#EscapeChar
Changes the script's escape character (for example: backslash vs. accent).
#HotkeyInterval
#HotkeyModifierTimeout
Affects the behavior of hotkey modifiers: CTRL, ALT, WIN, and SHIFT.
#Hotstring
#IfWinActive /
#IfWinExist
#Include
Causes the script to behave as though the specified file's contents are present at
this exact position.
#InstallKeybdHook
#InstallMouseHook
#KeyHistory
Sets the maximum number of keyboard and mouse events displayed by the
KeyHistory window. You can set it to 0 to disable key history.
#MaxHotkeysPerInterval
#MaxMem
#MaxThreads
#MaxThreadsBuffer
Causes some or all hotkeys to buffer rather than ignore keypresses when their
#MaxThreadsPerHotkey limit has been reached.
#MaxThreadsPerHotkey
#NoEnv
#NoTrayIcon
#Persistent
Keeps a script permanently running (that is, until the user closes it or ExitApp is
encountered).
#SingleInstance
#UseHook
Forces the use of the hook to implement all or some keyboard hotkeys.
#WinActivateForce
Skips the gentle method of activating a window and goes straight to the forceful
method.
Scripts
Table of Contents
Introduction
The Top of the Script (the Auto-execute Section): This portion executes automatically when the script starts.
Escape Sequences: When to use `% and `, to indicate a literal percent sign or comma.
Comments in Scripts: The use of semicolon and the symbols /*...*/ to add remarks to a script.
Splitting a Long Line into a Series of Shorter Ones: This can improve a script's readability and maintainability.
Convert a Script to an EXE (ahk2exe): Convert a .ahk script into a .exe file that can run on any PC.
Passing Command Line Parameters to a Script: The variables %1%, %2%, etc. contain the incoming parameters.
Debugging a Script: How to find the flaws in a misbehaving script.
Portability of AutoHotkey.exe: Having a copy of AutoHotkey.exe is enough to execute any .ahk file.
Installer Options: How to do unattended/silent installations or uninstallations.
Introduction
Each script is a plain text file containing lines 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.
The program loads the script into memory line by line, and each line may be up to 16,383 characters long. During loading, the
script is optimized and validated. Any syntax errors will be displayed, and they must be corrected before the script can run.
Escape Sequences
AutoHotkey's default escape character is accent/backtick (`), which is at the upper left corner of most English keyboards. Using
this character rather than backslash avoids the need for double blackslashes in file paths.
Since commas and percent signs have special meaning in the AutoHotkey language, use `, to specify a literal comma and `% to
specify a literal percent sign. One of the exceptions to this is MsgBox, which does not require commas to be escaped. Another
exception is commas in the last parameter of any command: they do not need to be escaped. See #EscapeChar for a complete
list of escape sequences.
Certain special characters are also produced by means of an escape sequence. The most common ones are `t (tab), `n
(linefeed), and `r (carriage return).
Tip: 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:
Comments in Scripts
Scripts can be commented by using a semicolon at the beginning of a line. For example:
; This entire line is a comment.
Comments may also be added to the end of a command, in which case the semicolon must have at least one space or tab to its
left. For example:
Run Notepad ; This is a comment on the same line as a command.
In addition, the /* and */ symbols can be used to comment out an entire section, but only if the symbols appear at the beginning
of a line as in this example:
/*
MsgBox, This line is commented out (disabled).
MsgBox, This one too.
*/
Since comments are ignored when a script is launched, they do not impact performance or memory utilization.
The default comment character (semicolon) can be changed to some other character or string via #CommentFlag.
(
A line of text.
By default, the hard carriage return (Enter) between the previous line and this one will be written to the file as a linefeed (`n).
By default, the tab to the left of this line will also be written to the file (the same is true for spaces).
By default, variable references such as %Var% are resolved to the variable's contents.
), C:\My File.txt
In the examples above, a series of lines is bounded at the top and bottom by a pair of parentheses. This is known as a
continuation section. Notice that the bottom line contains FileAppend's last parameter after the closing parenthesis. This practice
is optional; it is done in cases like this so that the comma will be seen as a parameter-delimiter rather than a literal comma.
The default behavior of a continuation section can be overridden by including one or more of the following options to the right of
the section's opening parenthesis. If more than one option is present, separate each one from the previous with a space. For
example: ( LTrim Join| %
Join: Specifies how lines should be connected together. If this option is omitted, each line except the last will be followed by a
linefeed character (`n). If the word Join is specified by itself, lines are connected directly to each other without any characters in
between. Otherwise, the word Join should be followed immediately by as many as 15 characters. For example, Join`s would
insert a space after each line except the last (`s indicates a literal space -- it is a special escape sequence recognized only by
Join). Another example is Join`r`n, which inserts CR+LF between lines. Similarly, Join| inserts a pipe between lines. To have the
final line in the section also ended by a join-string, include a blank line immediately above the section's closing parenthesis.
LTrim: Omits spaces and tabs at the beginning of each line. This is primarily used to allow the continuation section to be
indented. Also, this option may be turned on for multiple continuation sections by specifying #LTrim on a line by itself. #LTrim is
positional: it affects all continuation sections physically beneath it. The setting may be turned off via #LTrim Off.
RTrim0 (RTrim followed by a zero): Turns off the omission of spaces and tabs from the end of each line.
Comments (or Comment or Com or C) [v1.0.45.03+]: Allows semicolon comments inside the continuation section (but not
/*..*/). Such comments (along with any spaces and tabs to their left) are entirely omitted from the joined result rather than
being treated as literal text. Each comment can appear to the right of a line or on a new line by itself.
% (percent sign): Treats percent signs as literal rather than as variable references. This avoids the need to escape each percent
sign to make it literal. This option is not needed in places where percent signs are already literal, such as auto-replace hotstrings.
, (comma): Treats commas as delimiters rather than as literal commas. This rarely-used option is necessary only for the commas
between command parameters because in function calls, the type of comma does not matter. Also, this option transforms only
those commas that actually delimit parameters. In other words, once the command's final parameter is reached (or there are no
parameters), subsequent commas are treated as literal commas regardless of this option.
` (accent): Treats each backtick character literally rather than as an escape character. This also prevents commas and percent
signs from being explicitly and individually escaped. In addition, it prevents the translation of any explicitly specified escape
sequences such as `r and `t.
Remarks
Escape sequences such as `n (linefeed) and `t (tab) are supported inside the continuation section except when the accent (`)
option has been specified.
When the comment option is absent, semicolon and /*..*/ comments are not supported within the interior of a continuation
section because they are seen as literal text. However, comments can be included on the bottom and top lines of the section. For
example:
FileAppend, ; Comment.
; Comment.
( LTrim Join ; Comment.
; This is not a comment; it is literal. Include the word Comments in the line above to make it a comment.
), C:\File.txt ; Comment.
As a consequence of the above, semicolons never need to be escaped within a continuation section.
A continuation section cannot produce a line whose total length is greater than 16,383 characters (if it tries, the program will
alert you the moment the script is launched). One way to work around this is to do a series of concatenations into a variable. For
example:
Var =
(
...
)
Var = %Var%`n ; Add more text to the variable via another continuation section.
(
...
)
FileAppend, %Var%, C:\My File.txt
Since a closing parenthesis indicates the end of a continuation section, to have a line start with literal closing parenthesis,
precede it with an accent/backtick: `).
A continuation section can be immediately followed by a line containing the open-parenthesis of another continuation section.
This allows the options mentioned above to be varied during the course of building a single line.
The piecemeal construction of a continuation section by means of #Include is not supported.
Debugging a Script
Commands such as ListVars and Pause can help you debug a script. For example, the following two lines, when temporarily
inserted at carefully chosen positions, create "break points" in the script:
ListVars
Pause
When the script encounters these two lines, it will display the current contents of all variables for your inspection. When you're
ready to resume, un-pause the script via the File or Tray menu. The script will then continue until reaching the next "break point"
(if any).
It is generally best to insert these "break points" at positions where the active window does not matter to the script, such as
immediately before a WinActivate command. This allows the script to properly resume operation when you un-pause it.
The following commands are also useful for debugging: ListLines, KeyHistory, and OutputDebug.
Portability of AutoHotkey.exe
The file AutoHotkey.exe is all that is needed to launch any .ahk script. The only exception is Windows NT4, which requires a copy
of psapi.dll (from the AutoHotkey folder) for any script that uses the Process command.
Installer Options
To silently install AutoHotkey into the default directory (which is the same directory displayed by non-silent mode), pass the
parameter /S to the installer (/S must be capitalized). For example:
AutoHotkey104307_Install.exe /S
A directory other than the default may be specified via the /D parameter (in the absence of /S, this changes the default directory
displayed by the installer). For example:
AutoHotkey104307_Install.exe /S /D=C:\Program Files\AutoHotkey
To silently uninstall AutoHotkey, pass the parameter /S to the uninstaller. For example:
"C:\Program Files\AutoHotkey\uninst.exe" /S
Script Showcase
See this page for some useful scripts.
Ending Characters
Unless the asterisk option is in effect, you must type an ending character after a hotstring's abbreviation to trigger it. Ending characters initially consist of the following: -()[]
{}':;"/\,.?!`n `t (note that `n is Enter, `t is Tab, and there is a plain space between `n and `t). This set of characters can be changed by editing the following example, which sets
the new ending characters for all hotstrings, not just the ones beneath it:
#Hotstring EndChars -()[]{}:;'"/\,.?!`n `t
Options
A hotstring's default behavior can be changed in two possible ways:
1. The #Hotstring directive, which affects all hotstrings physically beneath that point in the script. The following example puts the C and R options into effect:
#Hotstring c r
2. Putting options inside a hotstring's first pair of colons. The following example puts the C and * options into effect for a single hotstring:
:c*:j@::john@somedomain.com ; Case sensitive and "ending character not required".
The list below describes each option. When specifying more than one option using the methods above, spaces optionally may be included between them.
* (asterisk): An ending character (e.g. space, period, or enter) is not required to trigger the hotstring. For example:
:*:j@::jsmith@somedomain.com
The example above would send its replacement the moment you type the @ character. When using the #Hotstring directive, use *0 to turn this option back off.
? (question mark): The hotstring will be triggered even when it is inside another word; that is, when the character typed immediately before it is alphanumeric. For example, if
:?:al::airline is a hotstring, typing "practical " would produce "practicairline ". Use ?0 to turn this option back off.
B0 (B followed by a zero): Automatic backspacing is not done to erase the abbreviation you type. Use a plain B to turn backspacing back on after it was previously turned off. A
script may also do its own backspacing via {bs 5}, which sends 5 backspaces. Similarly, it may send left-arrow keystrokes via {left 5}. For example, the following hotstring produces
<em></em> and moves the caret 5 places to the left (so that it's between the tags):
:*b0:<em>::</em>{left 5}
C: Case sensitive: When you type an abbreviation, it must exactly match the case defined in the script. Use C0 to turn case sensitivity back off.
C1: Do not conform to typed case. Use this option to make auto-replace hotstrings case insensitive and prevent them from conforming to the case of the characters you actually
type. Case-conforming hotstrings (which are the default) produce their replacement text in all caps if you type the abbreviation in all caps. If you type only the first letter in caps,
the first letter of the replacement will also be capitalized (if it is a letter). If you type the case in any other way, the replacement is sent exactly as defined. When using the
#Hotstring directive, C0 can be used to turn this option back off, which makes hotstrings conform again.
Kn: Key-delay: This rarely-used option sets the delay between keystrokes produced by auto-backspacing or auto-replacement. Specify the new delay for n; for example, specify k10
to have a 10ms delay and k-1 to have no delay. The exact behavior of this option depends on which sending mode is in effect:
SI (SendInput): Key-delay is ignored because a delay is not possible in this mode. The exception to this is when SendInput is unavailable, in which case hotstrings revert to
SendPlay mode below (which does obey key-delay).
SP (SendPlay): A delay of length zero is the default, which for SendPlay is the same as -1 (no delay). In this mode, the delay is actually a PressDuration rather than a delay
between keystrokes.
SE (SendEvent): A delay of length zero is the default. Zero is recommended for most purposes since it is fast but still cooperates well with other processes (due to internally
doing a Sleep 0). Specify k-1 to have no delay at all, which is useful to make auto-replacements faster if your CPU is frequently under heavy load. When set to -1, a script's
process-priority becomes an important factor in how fast it can send keystrokes. To raise a script's priority, use Process, Priority,, High.
O: Omit the ending character of auto-replace hotstrings when the replacement is produced. This is useful when you want a hotstring to be kept unambiguous by still requiring an
ending character, but don't actually want the ending character to be shown on the screen. For example, if :o:ar::aristocrat is a hotstring, typing "ar" followed by the spacebar will
produce "aristocrat" with no trailing space, which allows you to make the word plural or possessive without having to backspace. Use O0 (the letter O followed by a zero) to turn this
option back off.
Pn: The priority of the hotstring (e.g. P1). This rarely-used option has no effect on auto-replace hotstrings.
R: Send the replacement text raw; that is, exactly as it appears rather than translating {Enter} to an ENTER keystroke, ^c to Control-C, etc. This option is put into effect
automatically for hotstrings that have a continuation section. Use R0 to turn this option back off.
SI or SP or SE [v1.0.43+]: Sets the method by which auto-replace hotstrings send their keystrokes. These options are mutually exclusive: only one can be in effect at a time. The
following describes each option:
SI stands for SendInput, which became the default in v1.0.43+ because of its superior speed and reliability. Another benefit is that like SendPlay below, SendInput postpones
anything you type during a hotstring's auto-replacement text. This prevents your keystrokes from being interspersed with those of the replacement. When SendInput is
unavailable, hotstrings automatically use SendPlay instead.
SP stands for SendPlay, which may allow hotstrings to work in a broader variety of games.
SE stands for SendEvent, which is the default in versions older than 1.0.43.
Z: This rarely-used option resets the hotstring recognizer after each triggering of the hotstring. In other words, the script will begin waiting for an entirely new hotstring, eliminating
from consideration anything you previously typed. This can prevent unwanted triggerings of hotstrings. To illustrate, consider the following hotstring:
:b0*?:11::
SendInput xx
return
Since the above lacks the Z option, typing 111 (three consecutive 1's) would trigger the hotstring twice because the middle 1 is the last character of the first triggering but also the
first character of the second triggering. By adding the letter Z in front of b0, you would have to type four 1's instead of three to trigger the hotstring twice. Use Z0 to turn this option
back off.
Long Replacements
Hotstrings that produce a large amount of replacement text can be made more readable and maintainable by using a continuation section. For example:
::text1::
(
Any text between the top and bottom parentheses is treated literally, including commas and percent signs.
By default, the hard carriage return (Enter) between the previous line and this one is also preserved.
By default, the indentation (tab) to the left of this line is preserved.
See continuation section for how to change these default behaviors.
)
The presence of a continuation section also causes the hotstring to default to raw mode. The only way to override this special default is to specify the r0 option in each hotstring that
has a continuation section (e.g. :r0:text1::).
Context-sensitive Hotstrings
The directives #IfWinActive/Exist can be used to make selected hotstrings context sensitive. Such hotstrings send a different replacement, perform a different action, or do nothing
at all depending on the type of window that is active or exists. For example:
#IfWinActive ahk_class Notepad
::btw::This replacement text will appear only in Notepad.
#IfWinActive
::btw::This replacement text appears in windows other than Notepad.
AutoCorrect
The following script uses hotstrings to correct about 4700 common English misspellings on-the-fly. It also includes a Win+H hotkey to make it easy to add more misspellings:
Download: AutoCorrect.ahk (127 KB)
Author: Jim Biancolo and Wikipedia's Lists of Common Misspellings
Remarks
Variable references such as %MyVar% are not currently supported within the replacement text. To work around this, don't make such hotstrings auto-replace. Instead, use the
SendInput command beneath the abbreviation, followed by a line containing only the word Return.
To send an extra space or tab after a replacement, include the space or tab at the end of the replacement but make the last character an accent/backtick (`). For example:
:*:btw::By the way `
Any click of the left or right mouse button will reset the hotstring recognizer. In other words, the script will begin waiting for an entirely new hotstring, eliminating from consideration
anything you previously typed (if this is undesirable, specify the line #Hotstring NoMouse anywhere in the script). This "reset upon mouse click" behavior is the default because each
click typically moves the text insertion point (caret) or sets keyboard focus to a new control/field. In such cases, it is usually desirable to: 1) fire a hotstring even if it lacks the
question mark option; 2) prevent a firing when something you type after clicking the mouse accidentally forms a valid abbreviation with what you typed before.
The built-in variable A_EndChar contains the ending character that you typed to trigger the most recent non-auto-replace hotstring. If no ending character was required (due to the
* option), it will be blank. A_EndChar is useful when making hotstrings that use the Send command or whose behavior should vary depending on which ending character you typed.
To send the ending character itself, use SendRaw %A_EndChar% (SendRaw is used because characters such as !{} would not be sent correctly by the normal Send command).
Although commas, percent signs, and single-colons within hotstring definitions do not need to be escaped, backticks and those semicolons having a space or tab to their left require
it. See escape sequences for a complete list.
Although the Send command's special characters such as {Enter} are supported in auto-replacement text (unless the raw option is used), the hotstring abbreviations themselves do
not use this. Instead, specify `n for the ENTER key and `t (or a literal tab) for TAB (see escape sequences for a complete list). For example, the hotstring :*:ab`t:: would be
triggered when you type "ab" followed by a tab.
Spaces and tabs are treated literally within hotstring definitions. For example, the following would produce two different results:
::btw::by the way
::btw:: by the way
Each hotstring abbreviation can be no more than 40 characters long. The program will warn you if this length is exceeded. By contrast, the length of hotstring's replacement text is
limited to about 5000 characters when the sending mode is at its default of SendInput. That limit can be increased to 16,383 characters by switching to one of the other sending
modes. Furthermore, an unlimited amount of text can be sent by using SendPlay %MyVariable% in the body of the hotstring.
The order in which hotstrings are defined determines their precedence with respect to each other. In other words, if more than one hotstring matches something you type, only the
one listed first in the script will take effect. Related topic: context-sensitive hotstrings.
Any backspacing you do is taken into account for the purpose of detecting hotstrings. However, the use of arrow keys, PageUp, PageDown, Home, and End to navigate within an
editor will cause the hotstring recognition process to reset. In other words, it will begin waiting for an entirely new hotstring.
A hotstring may be typed even when the active window is ignoring your keystrokes. In other words, the hotstring will still fire even though the triggering abbreviation is never
visible. In addition, you may still press the backspace key to undo the most recently typed keystroke (even though you can't see the effect).
It is possible to Gosub or Goto a hotstring label by including its first pair of colons (including any option symbols) in front of its name. For example: Gosub ::xyz. However, jumping
to a single-line (auto-replace) hotstring will do nothing other than execute a return.
Although hotstrings are not monitored and will not be triggered during the course of an invisible Input command, visible Inputs are capable of triggering them.
Hotstrings can never be triggered by keystrokes produced by any AutoHotkey script. This avoids the possibility of an infinite loop where hotstrings trigger each other over and over.
The Input command is more flexible than hotstrings for certain purposes. For example, it allows your keystrokes to be invisible in the active window (such as a game). It also
supports non-character ending keys such as Escape.
The keyboard hook is automatically used by any script that contains hotstrings.
Hotstrings behave identically to hotkeys in the following ways:
They are affected by the Suspend command.
They obey #MaxThreads and #MaxThreadsPerHotkey (but not #MaxThreadsBuffer).
Scripts containing hotstrings are automatically persistent.
Non-auto-replace hotstrings will create a new thread when launched. In addition, they will update the built-in hotkey variables such as A_ThisHotkey.
Known limitation: On some systems in Java applications, hotstrings might interfere with the user's ability to type diacritical letters (via dead keys). To work around this, Suspend can
be turned on temporarily (which disables all hotstrings).
Hotstring Helper
Andreas Borutta suggested the following script, which might be useful if you are a heavy user of hotstrings. By pressing Win+H (or another hotkey of your choice), the currently
selected text can be turned into a hotstring. For example, if you have "by the way" selected in a word processor, pressing Win+H will prompt you for its abbreviation (e.g. btw) and
then add the new hotstring to the script. It will then reload the script to activate the hotstring.
GUI
Creates and manages windows and controls. Such windows can be used as
data entry forms or custom user interfaces.
Gui, sub-command [, Param2, Param3, Param4]
Table of Contents
Add: Creates a control such as text, button, or checkbox.
Show: Displays the window. It can also minimize, maximize, or move the window.
Submit: Saves the user's input and optionally hides the window.
Cancel (or Hide): Hides the window.
Destroy: Deletes the window.
Font: Sets the typeface, size, style, and text color for subsequently created controls.
Color: Sets the background color for the window and/or its controls.
Margin: Sets the margin/spacing used whenever no explicit position has been specified for a control.
Options and styles for a window: Sets various options for the appearance and behavior of the window.
Menu: Adds or removes a menu bar.
Minimize / Maximize / Restore: Performs the indicated operation on the window.
Flash: Blinks the window and its taskbar button.
Default: Changes the current thread's default GUI window number.
Positioning and sizing of controls
Storing and responding to user input: variables and g-labels
Options and styles for controls
Window Events: GuiClose | GuiEscape | GuiSize | GuiContextMenu | GuiDropFiles
Creating Multiple GUI windows
GUI Events, Threads, and Subroutines
Miscellaneous: Keyboard Navigation | Window Appearance | General Remarks
Examples: Contains working scripts that demonstrate GUI windows and controls.
Omit the X, Y, W, and H options below to have the window retain its previous size and position. If there is no previous
position, the window will be auto-centered in one or both dimensions if the X and/or Y options mentioned below are
absent. If there is no previous size, the window will be auto-sized according to the size and positions of the controls it
contains.
Zero or more of the following strings may be present in Options (specify each number as decimal, not hexadecimal):
Wn: Specify for n the width (in pixels) of the window's client area (the client area excludes the window's borders, title
bar, and menu bar).
Hn: Specify for n the height of the window's client area, in pixels.
Xn: Specify for n the window's X-position on the screen, in pixels. Position 0 is the leftmost column of pixels visible on
the screen.
Yn: Specify for n the window's Y-position on the screen, in pixels. Position 0 is the topmost row of pixels visible on the
screen.
Center: Centers the window horizontally and vertically on the screen.
xCenter: Centers the window horizontally on the screen. For example: Gui, Show, xCenter y0
yCenter: Centers the window vertically on the screen.
AutoSize: Resizes the window to accommodate only its currently visible controls. This is useful to resize the window
after new controls are added, or existing controls are resized, hidden, or unhidden. For example:
Gui, Show, AutoSize Center
One of the following may also be present:
Minimize: Minimizes the window and activates the one beneath it.
Maximize: Maximizes and activates the window.
Restore: Unminimizes or unmaximizes the window, if necessary. The window is also shown and activated, if necessary.
NoActivate: Unminimizes or unmaximizes the window, if necessary. The window is also shown without activating it.
NA: Shows the window without activating it. If the window is minimized, it will stay that way but will probably rise higher
in the z-order (which is the order seen in the alt-tab selector). If the window was previously hidden, this will probably
cause it to appear on top of the active window even though the active window is not deactivated.
Hide: Hides the window and activates the one beneath it. This is identical in function to Gui Cancel except that it allows a
hidden window to be moved, resized, or given a new title without showing it. For example: Gui, Show, Hide x55 y66
w300 h200, New Title
Gui, Cancel
Hides the window without saving the controls' contents to their associated variables. If the window does not exist -perhaps due to having been destroyed via Gui Destroy -- this command has no effect.
Gui, Destroy
Removes the window (if it exists) and all its controls, freeing the corresponding memory and system resources. If the
script later recreates the window, all of the window's properties such as color and font will start off at their defaults (as
though the window never existed). If Gui Destroy is not used, all GUI windows are automatically destroyed when the
script exits.
Omit the last two parameters to restore the font to the system's default GUI typeface, size, and color.
FontName may be the name of any font, such as one from the font table. If FontName is omitted or does not exist on the
system, the previous font's typeface will be used (or if none, the system's default GUI typeface). This behavior is useful
to make a GUI window have a similar font on multiple systems, even if some of those systems lack the preferred font. For
example, by using the following commands in order, Verdana will be given preference over Arial, which in turn is given
preference over MS sans serif:
gui, font,, MS sans serif
gui, font,, Arial
gui, font,, Verdana ; Preferred font.
If the Options parameter is blank, the previous font's attributes will be used. Otherwise, specify one or more of the
following option letters as substitutes:
C: Color name (see color chart) or RGB value -- or specify the word Default to return to the system's default color (black
on most systems). Example values: cRed, cFFFFAA, cDefault. Note: Buttons do not obey custom colors. Also, an
individual control can be created with a font color other than the current one by including the C option. For example: Gui,
Add, Text, cRed, My Text
S: Size (in points). For example: s12 (specify decimal, not hexadecimal)
W: Weight (boldness), which is a number between 1 and 1000 (400 is normal and 700 is bold). For example: w600
(specify decimal, not hexadecimal)
The following words are also supported: bold, italic, strike, underline, and norm. Norm returns the font to normal
weight/boldness and turns off italic, strike, and underline (but it retains the existing color and size). It is possible to use
norm to turn off all attributes and then selectively turn on others. For example, specifying norm italic would set the font
to normal then to italic.
To specify more than one option, include a space between each. For example: cBlue s12 bold
If a script creates multiple GUI windows, each window remembers its own "current font" for the purpose of creating more
controls.
On a related note, the operating system offers standard dialog boxes that prompt the user to pick a font, color, or icon.
These dialogs can be displayed via DllCall() as demonstrated at www.autohotkey.com/forum/topic17230.html.
Gui, Margin [, X, Y]
X and Y are the number of pixels of space to leave at the left/right and top/bottom sides of the window when autopositioning any control that lacks an explicit X or Y coordinate. Also, the margins are used to determine the vertical and
horizontal distance that separates auto-positioned controls from each other. Finally, the margins are taken into account
by the first use of Gui Show to calculate the window's size (when no explicit size is specified).
If this command is not used, when the first control is added to a window, the window acquires a default margin on all
sides proportional to the size of the currently selected font (0.75 times font-height for top & bottom, and 1.25 times fontheight for left & right).
Although the margin may be changed during the course of adding controls, the change will affect only controls added in
the future, not ones that already exist. Finally, either X or Y may be blank to leave the corresponding margin unchanged.
MinimizeBox (present by default): Enables the minimize button in the title bar.
MinSize and MaxSize [v1.0.44.13+]: Determines the minimum and/or maximum size of the window, such as when the
user drags its edges to resize it. Specify the word MinSize and/or MaxSize with no suffix to use the window's current size
as the limit (if the window has no current size, it will use the size from the first use of Gui Show). Alternatively, append
the width, followed by an X, followed by the height; for example: Gui +Resize +MinSize640x480. The dimensions are in
pixels, and they specify the size of the window's client area (which excludes borders, title bar, and menu bar). Specify
each number as decimal, not hexadecimal.
Either the width or the height may be omitted to leave it unchanged (e.g. +MinSize640x or +MinSizex480). Furthermore,
Min/MaxSize can be specified more than once to use the window's current size for one dimension and an explicit size for
the other. For example, +MinSize +MinSize640x would use the window's current size for the height and 640 for the width.
If MinSize and MaxSize are never used, the operating system's defaults are used (similarly, Gui -MinSize -MaxSize can be
used to return to the defaults). Note: the window must have +Resize to allow resizing by the user.
OwnDialogs: Gui +OwnDialogs should be specified in each thread (such as a ButtonOK subroutine) for which
subsequently displayed MsgBox, InputBox, FileSelectFile, and FileSelectFolder dialogs should be owned by the window.
Such dialogs become modal, meaning that the user cannot interact with the GUI window until dismissing the dialog. By
contrast, ToolTip, Progress, and SplashImage windows do not become modal even though they become owned; they will
merely stay always on top of their owner. In either case, any owned dialog or window is automatically destroyed when its
GUI window is destroyed.
There is typically no need to turn this setting back off because it does not affect other threads. However, if a thread needs
to display both owned and unowned dialogs, it may turn off this setting via Gui -OwnDialogs.
If no window number prefix is specified -- such as using Gui +OwnDialogs rather than Gui 2:+OwnDialogs -- the thread's
default window will own the dialogs.
Owner: Use +owner to make the window owned by another (but once the window is created, -owner has no effect). An
owned window has no taskbar button by default, and when visible it is always on top of its owner. It is also automatically
destroyed when its owner is destroyed. +Owner must be used after the window's owner is created but before the owned
window is created (that is, before commands such as Gui Add). There are two ways to use +owner as shown in these
examples:
gui, 2:+owner1 ; Make #2 window owned by #1 window.
gui, 2:+owner ; Make #2 window owned by script's main window to prevent display of a taskbar button.
To prevent the user from interacting with the owner while one of its owned window is visible, disable the owner via Gui
+Disabled. Later (when the time comes to cancel or destroy the owned window), re-enable the owner via Gui -Disabled.
Do this prior to cancel/destroy so that the owner will be reactivated automatically.
Resize: Makes the window resizable and enables its maximize button in the title bar. To avoid enabling the maximize
button, specify +Resize -MaximizeBox.
SysMenu (present by default): Specify -SysMenu (minus SysMenu) to omit the system menu and icon in the window's
upper left corner. This will also omit the minimize, maximize, and close buttons in the title bar.
Theme: By specifying -Theme, all subsequently created controls in the window will have Classic Theme appearance on
Windows XP and beyond. To later create additional controls that obey the current theme, turn it back on via +Theme.
Note: This option has no effect on operating systems older than Windows XP, nor does it have any effect on XP itself if the
Classic Theme is in effect. Finally, this setting may be changed for an individual control by specifying +Theme or -Theme
in its options.
ToolWindow: Provides a narrower title bar but the window will have no taskbar button.
(Unnamed Style): Specify a plus or minus sign followed immediately by a decimal or hexadecimal style number.
(Unnamed ExStyle): Specify a plus or minus sign followed immediately by the letter E and a decimal or hexadecimal
extended style number. For example, +E0x40000 would add the WS_EX_APPWINDOW style, which provides a taskbar
button for a window that would otherwise lack one. Although the other extended styles are not documented here (since
they are rarely used), they can be discovered by searching for WS_EX_APPWINDOW at www.microsoft.com.
Menu, MyMenuBar, Add, &File, :FileMenu ; Attach the two sub-menus that were created above.
Menu, MyMenuBar, Add, &Help, :HelpMenu
Gui, Menu, MyMenuBar
In the first line above, notice that &Open is followed by Ctrl+O (with a tab character in between). This indicates a
keyboard shortcut that the user may press instead of selecting the menu item. To enable such a shortcut in the script,
use a context-sensitive hotkey:
#IfWinActive GUI Window's Title ahk_class AutoHotkeyGUI
^o:: ; The Ctrl+O hotkey.
MenuFileOpen:
Gui +OwnDialogs ; Force the user to dismiss the FileSelectFile dialog before returning to the main window.
FileSelectFile, SelectedFile
MsgBox You selected the file %SelectedFile%.
return
; The following part is needed only if the script will be run on Windows 95/98/Me:
#IfWinActive
$^o::Send ^o
To remove a window's current menu bar, use Gui Menu (that is, omit the last parameter).
Once a menu has been used as a menu bar, it should not be used as a popup menu or a submenu. This is because menu
bars internally require a different format (however, this restriction applies only to the menu bar itself, not its submenus).
If you need to work around this, create one menu to use as the menu bar and another identical menu to use for
everything else.
The use of certain destructive menu sub-commands such as Delete and DeleteAll against a menu that is currently being
used as a menu bar (and in some cases, its submenus) is not supported and will cause an error dialog to be displayed
(unless UseErrorLevel is in effect). Use the following steps to make such changes: 1) detach the menu bar via Gui Menu
(that is, omit MenuName); 2) make the changes; 3) reattach the menu bar via Gui, Menu, MyMenuBar
Gui, 2:Default
Changes the current thread's default GUI window number, which is used whenever a window number is not specified for
GuiControl, GuiControlGet, and the Gui command itself. In the following example, the default window number is changed
to two: Gui 2:Default. See thread's default window for more information about the default window.
If some dimensions and/or coordinates are omitted from Options, the control will be positioned relative to the previous
control and/or sized automatically according to its nature and contents.
The following options are supported:
R: Rows of text (can contain a floating point number such as R2.5). R is often preferable to specifying H (Height). If both
the R and H options are present, R will take precedence. For a GroupBox, this setting is the number of controls for which
to reserve space inside the box. For DropDownLists, ComboBoxes, and ListBoxes, it is the number of items visible at one
time inside the list portion of the control (but on Windows XP or later, it is often desirable to omit both the R and H
options for DropDownList and ComboBox, which makes the popup list automatically take advantage of the available
height of the user's desktop). For other control types, R is the number of rows of text that can visibly fit inside the
control.
W: Width, in pixels. If omitted, the width is calculated automatically for some control types based on their contents. The
other controls types have the following default widths:
Tab controls: 30 times the current font size, plus 3 times the X-margin.
Vertical Progress Bars: Two times the current font size.
Horizontal Progress Bars, horizontal Sliders, DropDownLists, ComboBoxes, ListBoxes, GroupBoxes, Edits, and Hotkeys: 15
times the current font size (except GroupBoxes, which multiply by 18 to provide room inside for margins).
H: Height, in pixels. If both the H and R options are absent, DropDownLists, ComboBoxes, ListBoxes, and empty multiline Edit controls default to 3 rows; GroupBoxes default to 2 rows; vertical Sliders and Progress Bars default to 5 rows;
horizontal Sliders default to 30 pixels (except if a thickness has been specified); horizontal Progress Bars default to 2
times the current font size; Hotkey controls default to 1 row; and Tab controls default to 10 rows. For the other control
types, the height is calculated automatically based on their contents. Note that for DropDownLists and ComboBoxes, H is
the combined height of the control's always-visible portion and its list portion (but even if the height is set too low, at
least one item will always be visible in the list). Also, for all types of controls, specifying the number of rows via the R
option is usually preferable to using H because it prevents a control from showing partial/incomplete rows of text.
wp+n, hp+n, wp-n, hp-n (where n is any number) can be used to set the width and/or height of a control equal to the
previously added control's width or height, with an optional plus or minus adjustment. For example, wp would set a
control's width to that of the previous control, and wp-50 would set it equal to 50 less than that of the previous control.
X: X-position. For example, specifying "x0 y0" would position the control in the upper left corner of the window's client
area, which is the area beneath the title bar and menu bar (if any). If X is omitted but not Y, the control will be
positioned to the right of all previously added controls, which can be thought of as starting a new "column".
Y: Y-position. If Y is omitted but not X, the control will be positioned beneath all previously added controls, which can be
thought of as starting a new "row".
Omitting either X, Y or both is useful to make a GUI layout automatically adjust to any future changes you might make to
the size of controls or font. By contrast, specifying an absolute position for every control might require you to manually
shift the position of all controls that lie beneath and/or to the right of a control that is being enlarged or reduced.
If both X and Y are omitted, the control will be positioned beneath the previous control using a standard padding
distance.
For X and Y, an optional plus sign can be included to position a control relative to the right or bottom edge (respectively)
of the control that was previously added. For example, specifying Y+10 would position the control 10 pixels beneath the
bottom of the previous control rather than using the standard padding distance. Similarly, specifying X+10 would position
the control 10 pixels to the right of the previous control's right edge. Since negative numbers such as X-10 are reserved
for absolute positioning, to use a negative offset, include a plus sign in front of it. For example: X+-10
xp+n, yp+n, xp-n, yp-n (where n is any number) can be used to position controls relative to the previous control's
upper left corner, which is often useful for enclosing controls in a GroupBox.
xm and ym can be used to position a control at the leftmost and topmost margins of the window, respectively (these two
may also be followed by a plus/minus sign and a number). By specifying ym without any x-position at all, the control will
be positioned at the top margin but to the right of all previously added controls, which can be thought of as starting a
new "column". The converse is also true.
xs and ys: these are similar to xm and ym except that they refer to coordinates that were saved by having previously
added a control with the word Section in its options (the first control of the window always starts a new section, even if
that word isn't specified in its options). By specifying ys without any x-position at all, the control will be positioned at the
previously saved y-position, but to the right of all controls that have been added since the most recent use of the word
Section; this can be thought of as starting a new column within the section. For example:
gui, add, edit, w600 ; Add a fairly wide edit control at the top of the window.
gui, add, text, section, First Name: ; Save this control's position and start a new section.
gui, add, text,, Last Name:
Window Events
The following labels (subroutines) will be automatically associated with a GUI window if they exist in the script:
GuiClose: Launched when the window is closed by any of the following: pressing its X button in the title bar, selecting
"Close" from its system menu, or closing it with WinClose. If this label is absent, closing the window simply hides it,
which is the same effect as Gui Cancel. One of the most common actions to take in response to GuiClose is ExitApp; for
example:
GuiClose:
ExitApp
GuiEscape: Launched when the user presses Escape while the GUI window is active. If this label is absent, pressing
Escape has no effect. Known limitation: If the first control in the window is disabled (possibly depending on control type),
the GuiEscape label will not be launched. There may be other circumstances that produce this effect.
GuiSize: Launched when the window is resized, minimized, maximized, or restored. The built-in variables A_GuiWidth
and A_GuiHeight contain the new width and height of the window's client area, which is the area excluding title bar, menu
bar, and borders. In addition, A_EventInfo and ErrorLevel will both contain one of the following digits:
0: The window has been restored, or resized normally such as by dragging its edges.
1: The window has been minimized.
2: The window has been maximized.
A script may use GuiSize to reposition and resize controls in response to the user's resizing of the window. This process
can be made much easier by using #Include to load Titan's "Anchor" script.
GuiContextMenu: Launched whenever the user right-clicks anywhere in the window except the title bar and menu bar.
It is also launched in response to pressing the Apps key or Shift-F10. Unlike most other GUI labels, GuiContextMenu can
have more than one concurrent thread. The following built-in variables are available within GuiContextMenu:
1. A_GuiControl, which contains the text or variable name of the control that received the event (blank if none).
2. A_EventInfo: When a ListBox, ListView, or TreeView is the target of the context menu (as determined by
A_GuiControl above), A_EventInfo specifies which of the control's items is the target:
ListBox or ListView: A_EventInfo contains the number of the currently focused row (0 if none).
TreeView: For right-clicks, A_EventInfo contains the clicked item's ID number (or 0 if the user clicked somewhere
other than an item). For the AppsKey and Shift-F10, A_EventInfo contains the selected item's ID number.
3. A_GuiX and A_GuiY, which contain the X and Y coordinates of where the script should display the menu (e.g. Menu,
MyContext, Show, %A_GuiX%, %A_GuiY%). Coordinates are relative to the upper-left corner of the window.
4. A_GuiEvent, which contains the word RightClick if the user right-clicked, or Normal if the menu was triggered by
the Apps key or Shift-F10.
Note: Since Edit and MonthCal controls have their own context menu, a right-click in one of them will not launch
GuiContextMenu.
GuiDropFiles: Launched whenever files/folders are dropped onto the window as part of a drag-and-drop operation (but
if the label is already running, drop events are ignored). The following built-in variables are available within GuiDropFiles:
1. A_GuiControl, which contains the text or variable name of the control upon which the files were dropped (blank if
none).
2. A_EventInfo and ErrorLevel, which both contain the number of files dropped.
3. A_GuiX and A_GuiY, which contain the X and Y coordinates of where the files were dropped (relative to the
window's upper left corner).
4. A_GuiEvent, which contains the names of the files that were dropped, with each filename except the last
terminated by a linefeed (`n).
To extract the individual files, use a parsing loop as shown below:
; EXAMPLE #1:
Loop, parse, A_GuiEvent, `n
{
MsgBox, 4,, File number %A_Index% is:`n%A_LoopField%.`n`nContinue?
IfMsgBox, No, Break
}
; EXAMPLE #2: To extract only the first file, follow this example:
Loop, parse, A_GuiEvent, `n
{
FirstFile = %A_LoopField%
Break
}
; EXAMPLE #3: To process the files in alphabetical order, follow this example:
FileList = %A_GuiEvent%
Sort, FileList
Loop, parse, FileList, `n
MsgBox File number %A_Index% is:`n%A_LoopField%.
To temporarily disable drag-and-drop for a window, remove the WS_EX_ACCEPTFILES style via Gui -E0x10. To re-enable
it later, use Gui +E0x10.
Detecting and responding to other events: Other types of GUI events can be detected and acted upon via
OnMessage(). For example, a script can display context-sensitive help via ToolTip whenever the user moves the mouse
over particular controls in the window. This is demonstrated in the GUI ToolTip example.
Keyboard Navigation
A GUI window may be navigated via the TAB key, which moves keyboard focus to the next input-capable control (controls
from which the Tabstop style has been removed are skipped). The order of navigation is determined by the order in which
the controls were originally added. When the window is shown for the first time, the first input-capable control that has
the Tabstop style (which most control types have by default) will have keyboard focus.
Certain controls may contain an ampersand (&) to create a keyboard shortcut, which might be displayed in the control's
text as an underlined character (depending on system settings). A user activates the shortcut by holding down the ALT
key then typing the corresponding character. For buttons, checkboxes, and radio buttons, pressing the shortcut is the
same as clicking the control. For GroupBoxes and Text controls, pressing the shortcut causes keyboard focus to jump to
the first input-capable tabstop control that was created after it. However, if more than one control has the same shortcut
key, pressing the shortcut will alternate keyboard focus among all controls with the same shortcut.
To display a literal ampersand inside the control types mentioned above, specify two consecutive ampersands as in this
example: Save && Exit
Window Appearance
For its icon, a GUI window uses the tray icon that was in effect at the time the window was created. Thus, to have a
different icon, change the tray icon before creating the window. For example: Menu, Tray, Icon, MyIcon.ico. It is also
possible to have a different large icon for a window than its small icon (the large icon is displayed in the alt-tab task
switcher). This can be done via DllCall and SendMessage; for example:
hIcon32 := DllCall("LoadImage", uint, 0
, str, "My Icon.ico" ; Icon filename (this file may contain multiple icons).
, uint, 1 ; Type of image: IMAGE_ICON
, int, 32, int, 32 ; Desired width and height of image (helps LoadImage decide which icon is best).
, uint, 0x10) ; Flags: LR_LOADFROMFILE
Gui +LastFound
SendMessage, 0x80, 1, hIcon32 ; 0x80 is WM_SETICON; and 1 means ICON_BIG (vs. 0 for ICON_SMALL).
Gui Show
Due to OS limitations, Checkboxes, Radio buttons, and GroupBoxes for which a non-default text color was specified will
take on Classic Theme appearance on Windows XP and beyond.
Related topic: window's margin.
General Remarks
Use GuiControl and GuiControlGet to operate upon individual controls in a GUI window.
Each GUI window may have up to 11,000 controls. However, use caution when creating more than 5000 controls because
system instability may occur for certain control types.
Any script that uses the GUI command anywhere is automatically persistent (even if the GUI command is never actually
executed). It is also single-instance unless the #SingleInstance directive has been used to override that.
Related
GuiControl, GuiControlGet, Menu, Control Types, ListView, TreeView, Control, ControlGet, SplashImage, MsgBox,
FileSelectFile, FileSelectFolder
Examples
; Example: Achieve an effect similar to SplashTextOn:
Gui, +AlwaysOnTop +Disabled -SysMenu +Owner ; +Owner avoids a taskbar button.
Gui, Add, Text,, Some text to display.
Gui, Show, NoActivate, Title of Window ; NoActivate avoids deactivating the currently active window.
; Example: A simple input-box that asks for first name and last name:
Gui, Add, Text,, First name:
Gui, Add, Text,, Last name:
Gui, Add, Edit, vFirstName ym ; The ym option starts a new column of controls.
Gui, Add, Edit, vLastName
Gui, Add, Button, default, OK ; The label ButtonOK (if it exists) will be run when the button is pressed.
Gui, Show,, Simple Input Example
return ; End of auto-execute section. The script is idle until the user does something.
GuiClose:
ButtonOK:
Gui, Submit ; Save the input from the user to each control's associated variable.
MsgBox You entered "%FirstName% %LastName%".
ExitApp
; Example: Display context-senstive help (via ToolTip) whenever the user moves the mouse over a particular control:
Gui, Add, Edit, vMyEdit
MyEdit_TT := "This is a tooltip for the control whose variable is MyEdit."
Gui, Add, DropDownList, vMyDDL, Red|Green|Blue
MyDDL_TT := "Choose a color from the drop-down list."
Gui, Add, Checkbox, vMyCheck, This control has no tooltip.
Gui, Show
OnMessage(0x200, "WM_MOUSEMOVE")
return
WM_MOUSEMOVE()
{
static CurrControl, PrevControl, _TT ; _TT is kept blank for use by the ToolTip command below.
CurrControl := A_GuiControl
If (CurrControl <> PrevControl and not InStr(CurrControl, " "))
{
ToolTip ; Turn off any previous tooltip.
SetTimer, DisplayToolTip, 1000
PrevControl := CurrControl
}
return
DisplayToolTip:
SetTimer, DisplayToolTip, Off
ToolTip % %CurrControl%_TT ; The leading percent sign tell it to use an expression.
SetTimer, RemoveToolTip, 3000
return
RemoveToolTip:
SetTimer, RemoveToolTip, Off
ToolTip
return
}
GuiClose:
ExitApp
return
Gosub FileRead
return
FileRead: ; Caller has set the variable SelectedFileName for us.
FileRead, MainEdit, %SelectedFileName% ; Read the file's contents into the variable.
if ErrorLevel
{
MsgBox Could not open "%SelectedFileName%".
return
}
GuiControl,, MainEdit, %MainEdit% ; Put the text into the control.
CurrentFileName = %SelectedFileName%
Gui, Show,, %CurrentFileName% ; Show file name in title bar.
return
FileSave:
if CurrentFileName = ; No filename selected yet, so do Save-As instead.
Goto FileSaveAs
Gosub SaveCurrentFile
return
FileSaveAs:
Gui +OwnDialogs ; Force the user to dismiss the FileSelectFile dialog before returning to the main window.
FileSelectFile, SelectedFileName, S16,, Save File, Text Documents (*.txt)
if SelectedFileName = ; No file selected.
return
CurrentFileName = %SelectedFileName%
Gosub SaveCurrentFile
return
SaveCurrentFile: ; Caller has ensured that CurrentFileName is not blank.
IfExist %CurrentFileName%
{
FileDelete %CurrentFileName%
if ErrorLevel
{
MsgBox The attempt to overwrite "%CurrentFileName%" failed.
return
}
}
GuiControlGet, MainEdit ; Retrieve the contents of the Edit control.
FileAppend, %MainEdit%, %CurrentFileName% ; Save the contents to the file.
; Upon success, Show file name in title bar (in case we were called by FileSaveAs):
Gui, Show,, %CurrentFileName%
return
HelpAbout:
Gui, 2:+owner1 ; Make the main window (Gui #1) the owner of the "about box" (Gui #2).
Gui +Disabled ; Disable main window.
Gui, 2:Add, Text,, Text for about box.
Gui, 2:Add, Button, Default, OK
Gui, 2:Show
return
2ButtonOK: ; This section is used by the "about box" above.
2GuiClose:
2GuiEscape:
Gui, 1:-Disabled ; Re-enable the main window (must be done prior to the next step).
Gui Destroy ; Destroy the about box.
return
GuiDropFiles: ; Support drag & drop.
Loop, parse, A_GuiEvent, `n
{
SelectedFileName = %A_LoopField% ; Get the first file only (in case there's more than one).
break
}
Gosub FileRead
return
GuiSize:
if ErrorLevel = 1 ; The window has been minimized. No action needed.
return
; Otherwise, the window has been resized or maximized. Resize the Edit control to match.
NewWidth := A_GuiWidth - 20
NewHeight := A_GuiHeight - 20
GuiControl, Move, MainEdit, W%NewWidth% H%NewHeight%
return
FileExit:
; User chose "Exit" from the File menu.
GuiClose: ; User closed the window.
ExitApp
Variables
Variable types: AutoHotkey has no explicitly defined variable types. However, a variable containing only digits (with an
optional decimal point) is automatically interpreted as a number when a math operation or comparison requires it. (To
improve performance, numbers are cached internally to avoid conversions to/from strings.)
Variable scope and declarations: 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. Except where noted on the functions page, variables are
not declared; they come into existence simply by using them (and each variable starts off empty/blank).
Variable names: Variable names are not case sensitive (for example, CurrentDate is the same as currentdate). Variable
names may be up to 253 characters long and may consist of letters, numbers and the following punctuation: # _ @ $ ? [
]
Due to style conventions, it is generally better to name your variables using only letters, numbers, and the underscore
character (for example: CursorPosition, Total_Items, and entry_is_valid). This style allows people familiar with other
computer languages to understand your scripts more easily. Also, if you use the same conventions in AutoHotkey as you
use in other languages, you may find it easier to re-read your own scripts.
Although a variable name may consist entirely of digits, this is generally used only for incoming command line
parameters. Such numeric names cannot be used in expressions because they would be seen as numbers rather than
variables.
Since the words AND, OR, and NOT are used as operators in expressions, generally they should not be used as variable
names. Using such names in an expression would prevent proper evaluation.
Storing values in variables: To store a string or number in a variable, there are two methods: traditional and
expression. The traditional method uses the equal sign operator (=) to assign unquoted literal strings or variables
enclosed in percent signs. For example:
MyNumber = 123
MyString = This is a literal string.
CopyOfVar = %Var% ; With the = operator, percent signs are required to retrieve a variable's contents.
By contrast, the expression method uses the colon-equal operator (:=) to store numbers, quoted strings, and other
types of expressions. The following examples are functionally identical to the previous ones:
MyNumber := 123
MyString := "This is a literal string."
CopyOfVar := Var ; Unlike its counterpart in the previous section, percent signs are not used with the := operator.
The latter method is preferred by many due to its greater clarity, and because it supports an expression syntax nearly
identical to that in many other languages.
You may have guessed from the above that there are two methods to erase the contents of a variable (that is, to make it
blank):
MyVar =
MyVar := ""
The empty pair of quotes above should be used only with the := operator because if it were used with the = operator, it
would store two literal quote-characters inside the variable.
Retrieving the contents of variables: Like the two methods of storing values, there are also two methods for
retrieving them: traditional and expression. The traditional method requires that each variable name be enclosed in
percent signs to retrieve its contents. For example:
MsgBox The value in the variable named Var is %Var%.
CopyOfVar = %Var%
By contrast, the expression method omits the percent signs around variable names, but encloses literal strings in quotes.
Thus, the following are the expression equivalents of the previous examples:
MsgBox % "The value in the variable named Var is " . Var . "." ; A period is used to concatenate (join) two strings.
CopyOfVar := Var
In the MsgBox line above, a percent sign and a space is used to change the parameter from traditional to expression
mode. This is necessary because the traditional method is used by default by all commands (except where otherwise
documented). However, certain parameters of some commands are documented as accepting expressions, in which case
the leading percent sign is permitted but not necessary. For example, all of the following are effectively identical because
Sleep's first parameter is expression-capable:
Sleep MillisecondsToWait
Sleep %MillisecondsToWait%
Sleep % MillisecondsToWait
Comparing variables: Please read the expressions section below for important notes about the different kinds of
comparisons, especially about when to use parentheses.
Expressions
Expressions are used to perform one or more operations upon a series of variables, literal strings, and/or literal
numbers.
Variable names in an expression are not enclosed in percent signs (except for arrays and other double references).
Consequently, literal strings must be enclosed in double quotes to distinguish them from variables. For example:
if (CurrentSetting > 100 or FoundColor <> "Blue")
MsgBox The setting is too high or the wrong color is present.
In the example above, "Blue" appears in quotes because it is a literal string. To include an actual quote-character inside
a literal string, specify two consecutive quotes as shown twice in this example: "She said, ""An apple a day."""
Important: An if-statement that contains an expression is differentiated from a traditional if-statement such as If
FoundColor <> Blue by making the character after the word "if" an open-parenthesis. Although this is usually
accomplished by enclosing the entire expression in parentheses, it can also be done with something like if (x > 0) and (y
> 0). In addition, the open-parenthesis may be omitted entirely if the first item after the word "if" is a function call or an
operator such as "not" or "!".
Empty strings: To specify an empty string in an expression, use an empty pair of quotes. For example, the statement if
(MyVar <> "") would be true if MyVar is not blank. However, in a traditional-if, a pair of empty quotes is treated literally.
For example, the statement if MyVar = "" is true only if MyVar contains an actual pair of quotes. Thus, to check if a
variable is blank with a traditional-if, use = or <> with nothing on the right side as in this example: if Var =
On a related note, any invalid expression such as (x +* 3) yields an empty string.
Storing the result of an expression: To assign a result to a variable, use the := operator. For example:
NetPrice := Price * (1 - Discount/100)
Boolean values: When an expression is required to evaluate to true or false (such as an IF-statement), a blank or zero
result is considered false and all other results are considered true. For example, the statement "if ItemCount" would be
false only if ItemCount is blank or 0. Similarly, the expression "if not ItemCount" would yield the opposite result.
Operators such as NOT/AND/OR/>/=/< automatically produce a true or false value: they yield 1 for true and 0 for false.
For example, in the following expression, the variable Done is assigned 1 if either of the conditions is true:
Done := A_Index > 5 or FoundIt
As hinted above, a variable can be used to hold a false value simply by making it blank or assigning 0 to it. To take
advantage of this, the shorthand statement "if Done" can be used to check whether the variable Done is true or false.
The words true and false are built-in variables containing 1 and 0. They can be used to make a script more readable as
in these examples:
CaseSensitive := false
ContinueSearch := true
Integers and floating point: Within an expression, numbers are considered to be floating point if they contain a
decimal point; otherwise, they are integers. For most operators -- such as addition and multiplication -- if either of the
inputs is a floating point number, the result will also be a floating point number.
Within expressions and non-expressions alike, integers may be written in either hexadecimal or decimal format.
Hexadecimal numbers all start with the prefix 0x. For example, Sleep 0xFF is equivalent to Sleep 255. In v1.0.46.11+,
floating point numbers written in scientific notation are recognized; but only if they contain a decimal point (e.g. 1.0e4
and -2.1E-4).
Force an expression: An expression can be used in a parameter that does not directly support it (except an OutputVar
or InputVar parameter such as those of StringLen) by preceding the expression with a percent sign and a space or tab.
This technique is often used to access arrays. For example:
FileAppend, % MyArray%i%, My File.txt
MsgBox % "The variable MyVar contains " . MyVar . "."
Loop % Iterations + 1
WinSet, Transparent, % X + 100
Control, Choose, % CurrentSelection - 1
Operators in Expressions
Operators of equal precedence such as multiply (*) and divide (/) are evaluated in left-to-right order unless otherwise
specified below. By contrast, an operator of lower precedence such as add (+) is evaluated after a higher one such as
multiply (*). For example, 3 + 2 * 2 is evaluated as 3 + (2 * 2). Parentheses may be used to override precedence as in
this example: (3 + 2) * 2
Except where noted below, any blank value (empty string) involved in a math operation is not assumed to be zero.
Instead, it is treated as an error, which causes that part of the expression to evaluate to an empty string. For example, if
the variable X is blank, the expression X+1 yields a blank value rather than 1.
Such a reference should not resolve to an environment variable, the clipboard, or any reserved/read-only
variable. If it does, it is treated as an empty string. Also, for backward compatibility, command parameters
that are documented as "can be an expression" treat an isolated name in percent signs (e.g. %Var%, but not
Array%i%) as though the percent signs are absent. This can be avoided by enclosing the reference in
parentheses; e.g. Sleep (%Var%)
++
--
Pre- and post-increment/decrement. Adds or subtracts 1 from a variable (but in versions prior to 1.0.46,
these can be used only by themselves on a line; no other operators may be present). The operator may
appear either before or after the variable's name. If it appears before the name, the operation is performed
immediately and its result is used by the next operation. For example, Var := ++X increments X immediately
and then assigns its value to Var. Conversely, if the operator appears after the variable's name, the operation
is performed after the variable is used by the next operation. For example, Var := X++ increments X only
after assigning the current value of X to Var. Due to backward compatibility, the operators ++ and -- treat
blank variables as zero, but only when they are alone on a line; for example, y:=1, ++x and MsgBox % ++x
both produce a blank result when x is blank.
**
Power. Both the base and the exponent may contain a decimal point. If the exponent is negative, the result
will be formatted as a floating point number even if the base and exponent are both integers. Since ** is of
higher precedence than unary minus, -2**2 is evaluated like -(2**2) and so yields -4. Thus, to raise a literal
negative number to a power, enclose it in parentheses such as (-2)**2. Note: A negative base combined with
a fractional exponent such as (-2)**0.5 is not supported; it will yield an empty string. But both (-2)**2 and
Bitwise-not (~): This inverts each bit of its operand. If the operand is a floating point value, it is truncated
to an integer prior to the calculation. If the operand is between 0 and 4294967295 (0xffffffff), it will be
treated as an unsigned 32-bit value. Otherwise, it is treated as a signed 64-bit value. For example, ~0xf0f
evaluates to 0xfffff0f0 (4294963440).
Address (&): &MyVar retrieves the address of MyVar's contents in memory, which is typically used with
DllCall structures. &MyVar also disables the caching of binary numbers in that variable, which can slow down
its performance if it is ever used for math or numeric comparisons. Caching is re-enabled for a variable
whenever its address changes (e.g. via VarSetCapacity()).
Dereference (*): *Expression assumes that Expression resolves to a numeric memory address; it retrieves
the byte at that address as a number between 0 and 255 (0 is always retrieved if the address is 0; but any
other invalid address must be avoided because it might crash the script). However, NumGet() generally
performs much better when retrieving binary numbers.
Multiply (*): The result is an integer if both inputs are integers; otherwise, it is a floating point number.
True divide (/): Unlike EnvDiv, true division yields a floating point result even when both inputs are
integers. For example, 3/2 yields 1.5 rather than 1, and 4/2 yields 2.0 rather than 2.
*
/
//
Floor divide (//): The double-slash operator uses high-performance integer division if the two inputs are
integers. For example, 5//3 is 1 and 5//-3 is -1. If either of the inputs is in floating point format, floating
point division is performed and the result is truncated to the nearest integer to the left. For example, 5//3.0
is 1.0 and 5.0//-3 is -2.0. Although the result of this floating point division is an integer, it is stored in floating
point format so that anything else that uses it will see it as such. For modulo, see mod().
The *= and /= operators are a shorthand way to multiply or divide the value in a variable by another value.
For example, Var*=2 produces the same result as Var:=Var*2 (though the former performs better).
Division by zero yields a blank result (empty string).
+
-
Add (+) and subtract (-). On a related note, the += and -= operators are a shorthand way to increment or
decrement a variable. For example, Var+=2 produces the same result as Var:=Var+2 (though the former
performs better). Similarly, a variable can be increased or decreased by 1 by using Var++, Var--, ++Var, or -Var.
<<
>>
Bit shift left (<<) and right (>>). Example usage: Value1 << Value2. Any floating point input is truncated
to an integer prior to the calculation. Shift left (<<) is equivalent to multiplying Value1 by "2 to the Value2th
power". Shift right (>>) is equivalent to dividing Value1 by "2 to the Value2th power" and rounding the
result to the nearest integer leftward on the number line; for example, -3>>1 is -2.
&
^
|
Bitwise-and (&), bitwise-exclusive-or (^), and bitwise-or (|). Of the three, & has the highest
precedence and | has the lowest. Any floating point input is truncated to an integer prior to the calculation.
Concatenate. The period (dot) operator is used to combine two items into a single string (there must be at
least one space on each side of the period). You may also omit the period to achieve the same result (except
where ambiguous such as x -y, or when the item on the right side has a leading ++ or --). When the dot is
omitted, there should be at least one space between the items to be merged.
Example (expression method): Var := "The color is " . FoundColor
Example (traditional method): Var = The color is %FoundColor%
Sub-expressions can also be concatenated. For example: Var := "The net price is " . Price * (1 Discount/100)
A line that begins with a period (or any other operator) is automatically appended to the line above it.
Greater (>), less (<), greater-or-equal (>=), and less-or-equal (<=). If either of the inputs is not a
> < number, both are compared alphabetically (a quoted literal string such as "55" is always considered non>= <= numeric in this context). The comparison is case sensitive only if StringCaseSense has been turned on. See
also: Sort
=
==
<> !=
Equal (=) , case-sensitive-equal (==) , and not-equal (<> or !=). The operators != and <> are
identical in function. The == operator behaves identically to = except when either of the inputs is not a
number, in which case == is always case sensitive and = is always case insensitive (the method of
insensitivity depends on StringCaseSense). By contrast, <> and != obey StringCaseSense. Note: A quoted
literal string such as "55" is always considered non-numeric in this context.
NOT
Logical-NOT. Except for its lower precedence, this is the same as the ! operator. For example, not (x = 3 or
y = 3) is the same as !(x = 3 or y = 3)
AND
&&
Both of these are logical-AND. For example: x > 3 and x < 10. To enhance performance, short-circuit
evaluation is applied. Also, a line that begins with AND/OR/&&/|| (or any other operator) is automatically
appended to the line above it.
OR
||
?:
:=
+=
-=
*=
/=
//=
.=
|=
&=
^=
>>=
<<=
Both of these are logical-OR. For example: x <= 3 or x >= 10. To enhance performance, short-circuit
evaluation is applied.
Ternary operator [v1.0.46+]. This operator is a shorthand replacement for the if-else statement. It
evaluates the condition on its left side to determine which of its two branches should become its final result.
For example, var := x>y ? 2 : 3 stores 2 in Var if x is greater than y; otherwise it stores 3. To enhance
performance, only the winning branch is evaluated (see short-circuit evaluation). Note: For compatibility
reasons, the question mark must have at least one space on both sides (this may be resolved in a future
version).
Assign. Performs an operation on the contents of a variable and stores the result back in the same variable
(but in versions prior to 1.0.46, these could only be used as the leftmost operator on a line, and only the first
five operators were supported). The simplest assignment operator is colon-equals (:=), which stores the
result of an expression in a variable. For a description of what the other operators do, see their related
entries in this table. For example, Var //= 2 performs floor division to divide Var by 2, then stores the result
back in Var. Similarly, Var .= "abc" is a shorthand way of writing Var := Var . "abc".
Unlike most other operators, assignments are evaluated from right to left. Consequently, a line such as Var1
:= Var2 := 0 first assigns 0 to Var2 then assigns Var2 to Var1.
If an assignment is used as the input for some other operator, its value is the variable itself. For example, the
expression (Var+=2) > 50 is true if the newly-increased value in Var is greater than 50. This also allows an
assignment to be passed ByRef, or its address taken; for example: &(x:="abc").
The precedence of the assignment operators is automatically raised when it would avoid a syntax error or
provide more intuitive behavior. For example: not x:=y is evaluated as not (x:=y). Similarly, ++Var := X is
evaluated as ++(Var := X); and Z>0 ? X:=2 : Y:=2 is evaluated as Z>0 ? (X:=2) : (Y:=2)
Known limitations caused by backward compatibility (these may be resolved in a future release): 1) When
/= is the leftmost operator in an expression and it is not part of a multi-statement expression, it performs
floor division unless one of the inputs is floating point (in all other cases, /= performs true division); 2)
Date/time math is supported by += and -= only when that operator is the leftmost one on a line; 3) The
operators +=, -=, and *= treat blank variables as zero, but only when they are alone on a line; for example,
y:=1, x+=1 and MsgBox % x-=3 both produce a blank result when x is blank.
Comma (multi-statement) [v1.0.46+]. Commas may be used to write multiple sub-expressions on a single
line. This is most commonly used to group together multiple assignments or function calls. For example:
x:=1, y+=2, ++index, func(). Such statements are executed in order from left to right. Note: A line that
begins with a comma (or any other operator) is automatically appended to the line above it. See also:
comma performance.
In v1.0.46.01+, when a comma is followed immediately by a variable and an equal sign, that equal sign is
automatically treated as an assignment (:=). For example, all of the following are assignments: x:=1, y=2,
a=b=c
mod()
round() These and other built-in math functions are described here.
abs()
Performance: The expression assignment operator (:=) is optimized so that it performs just as quickly as the non-
Built-in Variables
The following variables are built into the program and can be referenced by any script. With the exception of Clipboard,
ErrorLevel, and command line parameters, these variables are read-only; that is, their contents cannot be directly
altered by the script.
Table of Contents
Special Characters: A_Space, A_Tab
Script Properties: command line parameters, A_WorkingDir, A_ScriptDir, A_ScriptName, (...more...)
Date and Time: A_YYYY, A_MM, A_DD, A_Hour, A_Min, A_Sec, (...more...)
Script Settings: A_IsSuspended, A_BatchLines, A_TitleMatchMode, (...more...)
User Idle Time: A_TimeIdle, A_TimeIdlePhysical
GUI Windows and Menu Bars: A_Gui, A_GuiControl, A_GuiEvent, A_EventInfo
Hotkeys, Hotstrings, and Custom Menu Items: A_ThisHotkey, A_EndChar, A_ThisMenuItem, (...more...)
Operating System and User Info: A_OSVersion, A_ScreenWidth, A_ScreenHeight, (...more...)
Misc: A_Cursor, A_CaretX, A_CaretY, Clipboard, ClipboardAll, ErrorLevel
Loop: A_Index, (...more...)
Special Characters
A_Space
This variable contains a single space character. See AutoTrim for details.
A_Tab
This variable contains a single tab character. See AutoTrim for details.
Script Properties
1, 2, 3, etc.
These variables are automatically created whenever a script is launched with command line
parameters. They can be changed and referenced just like normal variable names (for example:
%1%). The variable %0% contains the number of parameters passed (0 if none). For details, see the
command line parameters.
A_WorkingDir
The script's current working directory, which is where files will be accessed by default. The final
backslash is not included unless it is the root directory. Two examples: C:\ and C:\My Documents. Use
SetWorkingDir to change the working directory.
A_ScriptDir
The full path of the directory where the current script is located. For backward compatibility with
AutoIt v2, the final backslash is included only for .aut scripts (even for root directories). An
example for .aut scripts is C:\My Documents\
A_ScriptName
The file name of the current script, without its path, e.g. MyScript.ahk.
A_ScriptFullPath
The combination of the above two variables to give the complete file specification of the script, e.g.
C:\My Documents\My Script.ahk
A_LineNumber
The number of the currently executing line within the script (or one of its #Include files). This line
number will match the one shown by ListLines; it can be useful for error reporting such as this
example: MsgBox Could not write to log file (line number %A_LineNumber%).
Since a compiled script has merged all its #Include files into one big script, its line numbering may be
different than when it is run in non-compiled mode.
A_LineFile
The full path and name of the file to which A_LineNumber belongs, which will be the same as
A_ScriptFullPath unless the line belongs to one of a non-compiled script's #Include files.
A_ThisFunc
The name of the user-defined function that is currently executing (blank if none); for example:
[v1.0.46.16+]
A_ThisLabel
[v1.0.46.16+]
The name of the label (subroutine) that is currently executing (blank if none); for example: MyLabel.
It is updated whenever the script executes Gosub/Return or Goto. It is also updated for automaticallycalled labels such as timers, GUI threads, menu items, hotkeys, hotstrings, OnClipboardChange, and
OnExit, However, A_ThisLabel is not updated when execution "falls into" a label from above; when
that happens, A_ThisLabel retains its previous value. See also: A_ThisHotkey and IsLabel()
A_AhkVersion
In versions prior to 1.0.22, this variable is blank. Otherwise, it contains the version of AutoHotkey
that is running the script, such as 1.0.22. In the case of a compiled script, the version that was
originally used to compile it is reported. The formatting of the version number allows a script to check
whether A_AhkVersion is greater than some minimum version number with > or >= as in this
example: if A_AhkVersion >= 1.0.25.07
For non-compiled scripts: The full path and name of the EXE file that is actually running the current
script. For example: C:\Program Files\AutoHotkey\AutoHotkey.exe
A_AhkPath
For compiled scripts: The same as the above except the AutoHotkey directory is discovered via the
registry entry HKEY_LOCAL_MACHINE\SOFTWARE\AutoHotkey\InstallDir. If there is no such entry,
A_AhkPath is blank.
A_IsCompiled
A_ExitReason
The most recent reason the script was asked to terminate. This variable is blank unless the script has
an OnExit subroutine and that subroutine is currently running or has been called at least once by an
exit attempt. See OnExit for details.
Current 4-digit year (e.g. 2004). Synonymous with A_Year. Note: To retrieve a formatted time or date
appropriate for your locale and language, use "FormatTime, OutputVar" (time and long date) or
"FormatTime, OutputVar,, LongDate" (retrieves long-format date).
A_MM
A_DD
A_MMMM
Current month's full name in the current user's language, e.g. July
A_MMM
A_DDDD
Current day of the week's full name in the current user's language, e.g. Sunday
A_DDD
Current day of the week's 3-letter abbreviation in the current user's language, e.g. Sun
A_WDay
A_YDay
Current day of the year (1-366). The value is not zero-padded, e.g. 9 is retrieved, not 009. To retrieve a
zero-padded value, use the following: FormatTime, OutputVar, , YDay0
A_YWeek
Current year and week number (e.g. 200453) according to ISO 8601. To separate the year from the
week, use StringLeft, Year, A_YWeek, 4 and StringRight, Week, A_YWeek, 2. Precise definition of
A_YWeek: If the week containing January 1st has four or more days in the new year, it is considered
week 1. Otherwise, it is the last week of the previous year, and the next week is week 1.
A_Hour
Current 2-digit hour (00-23) in 24-hour time (for example, 17 is 5pm). To retrieve 12-hour time as well
as an AM/PM indicator, follow this example: FormatTime, OutputVar, , h:mm:ss tt
A_Min
A_Sec
A_MSec
Current 3-digit millisecond (000-999). To remove the leading zeros, follow this example: Milliseconds :=
A_MSec + 0
A_Now
The current local time in YYYYMMDDHH24MISS format. Note: Date and time math can be performed with
EnvAdd and EnvSub. Also, FormatTime can format the date and/or time according to your locale or
preferences.
A_NowUTC
The current Coordinated Universal Time (UTC) in YYYYMMDDHH24MISS format. UTC is essentially the
same as Greenwich Mean Time (GMT).
The number of milliseconds since the computer was rebooted. By storing A_TickCount in a variable,
elapsed time can later be measured by subtracting that variable from the latest A_TickCount value. For
example:
A_TickCount
StartTime := A_TickCount
Sleep, 1000
ElapsedTime := A_TickCount - StartTime
MsgBox, %ElapsedTime% milliseconds have elapsed.
If you need more precision than A_TickCount's 10ms, use QueryPerformanceCounter().
Script Settings
A_IsSuspended
A_IsPaused
[v1.0.48+]
Contains 1 if the thread immediately underneath the current thread is paused. Otherwise it
contains 0.
A_IsCritical
[v1.0.48+]
Contains 0 if Critical is off for the current thread. Otherwise it contains an integer greater
than zero, namely the message-check frequency being used by Critical. Since "Critical 0"
turns off critical, the current state of Critical can be saved and restored via Old_IsCritical :=
A_IsCritical followed later by Critical %Old_IsCritical%
A_BatchLines
A_TitleMatchMode
A_AutoTrim
A_StringCaseSense
A_FormatInteger
A_FormatFloat
A_KeyDelay
The current delay set by SetKeyDelay (always decimal, not hex). This delay is for the
traditional SendEvent mode, not SendPlay.
A_WinDelay
A_ControlDelay
A_MouseDelay
The current delay set by SetMouseDelay (always decimal, not hex). This delay is for the
traditional SendEvent mode, not SendPlay.
A_DefaultMouseSpeed
A_IconHidden
Contains 1 if the tray icon is currently hidden or 0 otherwise. The icon can be hidden via
#NoTrayIcon or the Menu command.
A_IconTip
Blank unless a custom tooltip for the tray icon has been specified via Menu, Tray, Tip -- in
which case it's the text of the tip.
A_IconFile
Blank unless a custom tray icon has been specified via Menu, tray, icon -- in which case it's
the full path and name of the icon's file.
A_IconNumber
Blank if A_IconFile is blank. Otherwise, it's the number of the icon in A_IconFile (typically 1).
A_TimeIdle
The number of milliseconds that have elapsed since the system last received keyboard, mouse, or
other input. This is useful for determining whether the user is away. This variable will be blank
unless the operating system is Windows 2000, XP, or beyond. Physical input from the user as well
as artificial input generated by any program or script (such as the Send or MouseMove commands)
will reset this value back to zero. Since this value tends to increase by increments of 10, do not
check whether it is equal to another value. Instead, check whether it is greater or less than
another value. For example: IfGreater, A_TimeIdle, 600000, MsgBox, The last keyboard or mouse
activity was at least 10 minutes ago.
Similar to above but ignores artificial keystrokes and/or mouse clicks whenever the corresponding
hook (keyboard or mouse) is installed; that is, it responds only to physical events. (This prevents
A_TimeIdlePhysical simulated keystrokes and mouse clicks from falsely indicating that a user is present.) If neither
hook is installed, this variable is equivalent to A_TimeIdle. If only one hook is installed, only its
type of physical input affects A_TimeIdlePhysical (the other/non-installed hook's input, both
physical and artificial, has no effect).
The GUI window number that launched the current thread. This variable is blank unless a Gui control,
menu bar item, or event such as GuiClose/GuiEscape launched the current thread.
A_GuiControl
The name of the variable associated with the GUI control that launched the current thread. If that
control lacks an associated variable, A_GuiControl instead contains the first 63 characters of the
control's text/caption (this is most often used to avoid giving each button a variable name).
A_GuiControl is blank whenever: 1) A_Gui is blank; 2) a GUI menu bar item or event such as
GuiClose/GuiEscape launched the current thread; 3) the control lacks an associated variable and has
no caption; or 4) The control that originally launched the current thread no longer exists (perhaps due
to Gui Destroy).
A_GuiWidth
A_GuiHeight
These contain the GUI window's width and height when referenced in a GuiSize subroutine. They apply
to the window's client area, which is the area excluding title bar, menu bar, and borders.
A_GuiX
A_GuiY
These contain the X and Y coordinates for GuiContextMenu and GuiDropFiles events. Coordinates are
relative to the upper-left corner of the window.
The type of event that launched the current thread. If the thread was not launched via GUI action, this
variable is blank. Otherwise, it contains one of the following strings:
A_GuiEvent
or
A_GuiControlEvent
Normal: The event was triggered by a single left-click or via keystrokes (arrow keys, TAB key, space
bar, underlined shortcut key, etc.). This value is also used for menu bar items and the special events
such as GuiClose and GuiEscape.
DoubleClick: The event was triggered by a double-click. Note: The first click of the click-pair will still
cause a Normal event to be received first. In other words, the subroutine will be launched twice: once
for the first click and again for the second.
RightClick: Occurs only for GuiContextMenu, ListViews, and TreeViews.
Context-sensitive values: For details see GuiContextMenu, GuiDropFiles, Slider, MonthCal, ListView,
and TreeView.
Contains additional information about the following events:
A_EventInfo
Note: Unlike variables such as A_ThisHotkey, each thread retains its own value for A_Gui, A_GuiControl, A_GuiX/Y,
A_GuiEvent, and A_EventInfo. Therefore, if a thread is interrupted by another, upon being resumed it will still see its
original/correct values in these variables.
The name of the most recently selected custom menu item (blank if none).
A_ThisMenu
A_ThisMenuItemPos
A number indicating the current position of A_ThisMenuItem within A_ThisMenu. The first
item in the menu is 1, the second is 2, and so on. Menu separator lines are counted. This
variable is blank if A_ThisMenuItem is blank or no longer exists within A_ThisMenu. It is also
blank if A_ThisMenu itself no longer exists.
The key name of the most recently executed hotkey or non-auto-replace hotstring (blank if
none), e.g. #z. This value will change if the current thread is interrupted by another hotkey,
so be sure to copy it into another variable immediately if you need the original value for later
use in a subroutine.
A_ThisHotkey
When a hotkey is first created -- either by the Hotkey command or a double-colon label in the
script -- its key name and the ordering of its modifier symbols becomes the permanent name
of that hotkey. See also: A_ThisLabel
A_PriorHotkey
Same as above except for the previous hotkey. It will be blank if none.
A_TimeSinceThisHotkey
The number of milliseconds that have elapsed since A_ThisHotkey was pressed. It will be -1
whenever A_ThisHotkey is blank.
A_TimeSincePriorHotkey
The number of milliseconds that have elapsed since A_PriorHotkey was pressed. It will be -1
whenever A_PriorHotkey is blank.
A_EndChar
The ending character that was pressed by the user to trigger the most recent non-autoreplace hotstring. If no ending character was required (due to the * option), this variable will
be blank.
A_Temp
[v1.0.43.09+]
The full path and name of the folder designated to hold temporary files (e.g.
C:\DOCUME~1\UserName\LOCALS~1\Temp). It is retrieved from one of the following locations
(in order): 1) the environment variables TMP, TEMP, or USERPROFILE; 2) the Windows directory.
On Windows 9x, A_WorkingDir is returned if neither TMP nor TEMP exists.
A_OSType
The type of Operating System being run. Either WIN32_WINDOWS (i.e. Windows 95/98/ME) or
WIN32_NT (i.e. Windows NT4/2000/XP/2003/Vista).
One of the following strings: WIN_VISTA [requires v1.0.44.13+], WIN_2003, WIN_XP,
WIN_2000, WIN_NT4, WIN_95, WIN_98, WIN_ME. For example:
A_OSVersion
A_Language
A_ComputerName
A_UserName
A_WinDir
A_ProgramFiles
or ProgramFiles
The Program Files directory (e.g. C:\Program Files). In v1.0.43.08+, the A_ prefix may be
omitted, which helps ease the transition to #NoEnv.
A_AppData
[v1.0.43.09+]
The full path and name of the folder containing the current user's application-specific data. For
example: C:\Documents and Settings\Username\Application Data
A_AppDataCommon
[v1.0.43.09+]
The full path and name of the folder containing the all-users application-specific data.
A_Desktop
The full path and name of the folder containing the current user's desktop files.
A_DesktopCommon
The full path and name of the folder containing the all-users desktop files.
A_StartMenu
The full path and name of the current user's Start Menu folder.
A_StartMenuCommon The full path and name of the all-users Start Menu folder.
A_Programs
The full path and name of the Programs folder in the current user's Start Menu.
A_ProgramsCommon
The full path and name of the Programs folder in the all-users Start Menu.
A_Startup
The full path and name of the Startup folder in the current user's Start Menu.
A_StartupCommon
The full path and name of the Startup folder in the all-users Start Menu.
A_MyDocuments
The full path and name of the current user's "My Documents" folder. Unlike most of the similar
variables, if the folder is the root of a drive, the final backslash is not included. For example, it
The width and height of the primary monitor, in pixels (e.g. 1024 and 768).
To discover the dimensions of other monitors in a multi-monitor system, use SysGet.
A_ScreenWidth
A_ScreenHeight
To instead discover the width and height of the entire desktop (even if it spans multiple
monitors), use the following example (but on Windows 95/NT, both of the below variables will be
set to 0):
SysGet, VirtualWidth, 78
SysGet, VirtualHeight, 79
In addition, use SysGet to discover the work area of a monitor, which can be smaller than the
monitor's total area because the taskbar and other registered desktop toolbars are excluded.
A_IPAddress1
through 4
Misc.
A_Cursor
The type of mouse cursor currently being displayed. It will be one of the following words: AppStarting,
Arrow, Cross, Help, IBeam, Icon, No, Size, SizeAll, SizeNESW, SizeNS, SizeNWSE, SizeWE, UpArrow, Wait,
Unknown. The acronyms used with the size-type cursors are compass directions, e.g. NESW =
NorthEast+SouthWest. The hand-shaped cursors (pointing and grabbing) are classified as Unknown.
Known limitation on Windows 95: If this variable's contents are fetched repeatedly at a high frequency
(i.e. every 500 ms or faster), it will probably disrupt the user's ability to double-click. There is no known
workaround.
The current X and Y coordinates of the caret (text insertion point). The coordinates are relative to the
active window unless CoordMode is used to make them relative to the entire screen. If there is no active
window or the caret position cannot be determined, these variables are blank.
The following script allows you to move the caret around to see its current position displayed in an autoupdate tooltip. Note that some windows (e.g. certain versions of MS Word) report the same caret position
regardless of its actual position.
A_CaretX
A_CaretY
#Persistent
SetTimer, WatchCaret, 100
return
WatchCaret:
ToolTip, X%A_CaretX% Y%A_CaretY%, A_CaretX, A_CaretY - 20
return
If the contents of these variables are fetched repeatedly at a high frequency (i.e. every 500 ms or faster),
the user's ability to double-click will probably be disrupted. There is no known workaround.
Clipboard
The contents of the OS's clipboard, which can be read or written to. See the Clipboard section.
ClipboardAll The entire contents of the clipboard (such as formatting and text). See ClipboardAll.
ErrorLevel
See ErrorLevel.
A_LastError The result from the OS's GetLastError() function. For details, see DllCall() and Run/RunWait.
Loop
A_Index
This is the number of the current loop iteration (a 64-bit integer). For example, the first time the
script executes the body of a loop, this variable will contain the number 1. For details see Loop or
While-loop.
A_LoopFileName,
This and other related variables are valid only inside a file-loop.
etc.
A_LoopRegName,
This and other related variables are valid only inside a registry-loop.
etc.
A_LoopReadLine
A_LoopField