Variables and Expressions - Definition & Usage | AutoHotkey

AutoHotkey

Variables and Expressions

Table of Contents

Variables

See Variables for general explanation and details about how variables work.

Storing values in variables: To store a string or number in a variable, there are two methods: legacy and expression. The legacy 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: legacy and expression. The legacy 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 legacy to expression mode. This is necessary because the legacy method is used by default by all commands, except where otherwise documented.

Comparing variables: Please read the expressions section below for important notes about the different kinds of comparisons, especially about when to use parentheses.

Expressions

See Expressions for a structured overview and further explanation.

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 pseudo-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. [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 OutputVar parameters) by preceding the expression with a percent sign and a space or tab. In [v1.1.21+], this prefix can be used in the InputVar parameters of all commands except the traditional IF commands (use If (expression) instead). This technique is often used to access arrays. For example:

FileAppend, % MyArray[i], My File.txt
FileAppend, % MyPseudoArray%i%, My File.txt
MsgBox % "The variable MyVar contains " . MyVar . "."
Loop % Iterations + 1
WinSet, Transparent, % X + 100
Control, Choose, % CurrentSelection - 1

Operators in Expressions

See Operators for general information about operators.

Except where noted below, any blank value (empty string) or non-numeric value 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.

For historical reasons, quoted numeric strings such as "123" are always considered non-numeric when used directly in an expression (but not when stored in a variable or returned by a function). This non-numeric attribute is propagated by concatenation, so expressions like "0x" n also produce a non-numeric value (even when n contains valid hexadecimal digits). This problem can be avoided by assigning the value to a variable or passing it through a function like Round(). Scripts should avoid using quote marks around literal numbers, as the behavior may change in a future version.

Expression Operators (in descending precedence order)

%Var%

If a variable is enclosed in percent signs within an expression (e.g. %Var%), whatever that variable contains is assumed to be the name or partial name of another variable (if there is no such variable, %Var% resolves to a blank string). This is most commonly used to reference pseudo-array elements such as the following example:

Var := MyArray%A_Index% + 100

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%).

[AHK_L 52+]: In addition to normal variables, %Var% may resolve to an environment variable, the clipboard, or any reserved/read-only variable. Prior to revision 52, %Var% yielded an empty string in these cases.

x.y [AHK_L 31+]: Object access. Get or set a value or call a method of object x, where y is a literal value. See object syntax.
new [v1.1.00+]: Creates a new object derived from another object. For example, x := new y is often equivalent to x := {base: y}. new should be followed by a variable or simple class name of the form GlobalClass.NestedClass, and optionally parameters as in x := new y(z) (where y is a variable, not a function name). For details, see Custom Objects.
++
--
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 (-2)**2.0 are supported.

-
!
~
& *

Unary minus (-): Although it uses the same symbol as the subtract operator, unary minus applies to only a single item or sub-expression as shown twice in this example: -(3 / -x). On a related note, any unary plus signs (+) within an expression are ignored.

Logical-not (!): If the operand is blank or 0, the result of applying logical-not is 1, which means "true". Otherwise, the result is 0 (false). For example: !x or !(y and z). Note: The word NOT is synonymous with ! except that ! has a higher precedence. [v1.0.46+]: Consecutive unary operators such as !!Var are allowed because they are evaluated in right-to-left order.

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.

~= [AHK_L 31+]: Shorthand for RegExMatch. For example, "abc123" ~= "\d" sets ErrorLevel to 0 and yields 4 (the position of the first numeric character). Prior to [v1.1.03], this operator had the same precedence as the equal (=) operator and was not fully documented.
>   <
>= <=
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).
:=
+=
-=
*=
/=
//=
.=
|=
&=
^=
>>=
<<=

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, MyFunc(). 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.

[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. New scripts should not rely on this behavior as it may change. The rule applies only to plain variables and not double-derefs, so the following contains only one assignment: x:=1, %y%=2

The following types of sub-expressions override precedence/order of evaluation:

(expression)

Any sub-expression enclosed in parentheses. For example, (3 + 2) * 2 forces 3 + 2 to be evaluated first.

mod()
round()
abs()

Function call. The function name must be immediately followed by an open-parentheses, without any spaces or tabs in between. For details, see Functions.

%func%()

See Dynamically Calling a Function.
func.()

Deprecated: This syntax is not recommended for use. Use %func%() (for function names and objects) or func.Call() (for function objects) instead.

[AHK_L 48+]: Attempts to call an empty-named method of the object func. By convention, this is the object's "default" method. If func does not contain an object, the default base object is invoked instead.

[v1.0.95+]: If func contains a function name, the named function is called.

Fn(Params*)

[AHK_L 60+]: Variadic function call. Params is an array (object) containing parameter values.

x[y]
[a, b, c]

[AHK_L 31+]: Member access. Get or set a value or call a method of object x, where y is a parameter list (typically an array index or key) or an expression which returns a method name.

[v1.0.97+]: Array literal. If the open-bracket is not preceded by a value (or a sub-expression which yields a value), it is interpreted as the beginning of an array literal. For example, [a, b, c] is equivalent to Array(a, b, c) (a, b and c are variables).

See array syntax and object syntax for more details.

{a: b, c: d}

[v1.0.97+]: Object literal. Create an object or associative array. For example, x := {a: b} is equivalent to x := Object("a", b) or x := Object(), x.a := b. See Associative Arrays for details.


Performance: [v1.0.48+]: The comma operator is usually faster than writing separate expressions, especially when assigning one variable to another (e.g. x:=y, a:=b). Performance continues to improve as more and more expressions are combined into a single expression; for example, it may be 35% faster to combine five or ten simple expressions into a single expression.

Built-in Variables

The variables below are built into the program and can be referenced by any script.

See Built-in Variables for general information.

Table of Contents

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%), but cannot be referenced directly in an expression. The variable %0% contains the number of parameters passed (0 if none). For details, see the command line parameters.
A_Args
[v1.1.27+]
Read/write: Contains an array of command line parameters. For details, see Passing Command Line Parameters to a Script.
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. The final backslash is omitted (even for root directories).
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_ScriptHwnd
[v1.1.01+]
The unique ID (HWND/handle) of the script's hidden main window.
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
[v1.0.46.16+]
The name of the user-defined function that is currently executing (blank if none); for example: MyFunction. See also: IsFunc()
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 automatically-called labels such as timers, GUI threads, menu items, hotkeys, hotstrings, OnClipboardChange (label), 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.
A_AhkPath

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

For compiled scripts: The same as the above except the AutoHotkey directory is discovered via the registry entry HKLM\SOFTWARE\AutoHotkey\InstallDir. If there is no such entry, A_AhkPath is blank.

A_IsUnicode

Contains 1 if strings are Unicode (16-bit) and an empty string (which is considered false) if strings are ANSI (8-bit). The format of strings depends on the version of AutoHotkey.exe which is used to run the script, or if it is compiled, which bin file was used to compile it.

For ANSI executables prior to [v1.1.06], A_IsUnicode was left undefined; that is, the script could assign to it, and attempting to read it could trigger a UseUnsetGlobal warning. In later versions it is always defined and is read-only.

A_IsCompiled

Contains 1 if the script is running as a compiled EXE and an empty string (which is considered false) if it is not.

For non-compiled scripts prior to [v1.1.06], A_IsCompiled was left undefined; that is, the script could assign to it, and attempting to read it could trigger a UseUnsetGlobal warning. In later versions it is always defined and is read-only.

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.

Date and Time

A_YYYY

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 Current 2-digit month (01-12). Synonymous with A_Mon.
A_DD Current 2-digit day of the month (01-31). Synonymous with A_MDay.
A_MMMM Current month's full name in the current user's language, e.g. July
A_MMM Current month's abbreviation in the current user's language, e.g. Jul
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 abbreviation in the current user's language, e.g. Sun
A_WDay Current 1-digit day of the week (1-7). 1 is Sunday in all locales.
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

Current 2-digit minute (00-59).

A_Sec Current 2-digit second (00-59).
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).
A_TickCount

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:

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 Contains 1 if the script is suspended and 0 otherwise.
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 (synonymous with A_NumBatchLines) The current value as set by SetBatchLines. Examples: 200 or 10ms (depending on format).
A_ListLines
[v1.1.28+]
Contains 1 if ListLines is enabled. Otherwise it contains 0.
A_TitleMatchMode The current mode set by SetTitleMatchMode: 1, 2, 3, or RegEx.
A_TitleMatchModeSpeed The current match speed (fast or slow) set by SetTitleMatchMode.
A_DetectHiddenWindows The current mode (On or Off) set by DetectHiddenWindows.
A_DetectHiddenText The current mode (On or Off) set by DetectHiddenText.
A_AutoTrim The current mode (On or Off) set by AutoTrim.
A_StringCaseSense The current mode (On, Off, or Locale) set by StringCaseSense.
A_FileEncoding [AHK_L 46+]: Contains the default encoding for various commands; see FileEncoding.
A_FormatInteger The current integer format (H or D) set by SetFormat. [AHK_L 42+]: This may also contain lower-case h.
A_FormatFloat The current floating point number format set by SetFormat.
A_SendMode [v1.1.23+]: The current mode (Event, Input, Play or InputThenPlay) set by SendMode.
A_SendLevel [v1.1.23+]: The current SendLevel setting (an integer between 0 and 100, inclusive).
A_StoreCapsLockMode [v1.1.23+]: The current mode (On or Off) set by SetStoreCapsLockMode.
A_KeyDelay
A_KeyDuration
The current delay or duration set by SetKeyDelay (always decimal, not hex). A_KeyDuration requires [v1.1.23+].
A_KeyDelayPlay
A_KeyDurationPlay
The current delay or duration set by SetKeyDelay for the SendPlay mode (always decimal, not hex). Requires [v1.1.23+].
A_WinDelay The current delay set by SetWinDelay (always decimal, not hex).
A_ControlDelay The current delay set by SetControlDelay (always decimal, not hex).
A_MouseDelay
A_MouseDelayPlay
The current delay set by SetMouseDelay (always decimal, not hex). A_MouseDelay is for the traditional SendEvent mode, whereas A_MouseDelayPlay is for SendPlay. A_MouseDelayPlay requires [v1.1.23+].
A_DefaultMouseSpeed The current speed set by SetDefaultMouseSpeed (always decimal, not hex).
A_CoordModeToolTip
A_CoordModePixel
A_CoordModeMouse
A_CoordModeCaret
A_CoordModeMenu
[v1.1.23+]: The current mode (Window, Client or Screen) set by CoordMode.
A_RegView [v1.1.08+]: The current registry view as set by SetRegView.
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).

User Idle Time

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. 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.
A_TimeIdlePhysical 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 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).
A_TimeIdleKeyboard
[v1.1.28+]
If the keyboard hook is installed, this is the number of milliseconds that have elapsed since the system last received physical keyboard input. Otherwise, this variable is equivalent to A_TimeIdle.
A_TimeIdleMouse
[v1.1.28+]
If the mouse hook is installed, this is the number of milliseconds that have elapsed since the system last received physical mouse input. Otherwise, this variable is equivalent to A_TimeIdle.

GUI Windows and Menu Bars

A_DefaultGui [v1.1.23+] The name or number of the current thread's default GUI.
A_DefaultListView [v1.1.23+] The variable name or HWND of the ListView control upon which the ListView functions operate. If the default GUI lacks a ListView, this variable is blank.
A_DefaultTreeView [v1.1.23+] The variable name or HWND of the TreeView control upon which the TreeView functions operate. If the default GUI lacks a TreeView, this variable is blank.
A_Gui The name or number of the GUI 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. [v1.1.11+]: These values are affected by DPI scaling.
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. [v1.1.11+]: These values are affected by DPI scaling.
A_GuiEvent
or A_GuiControlEvent

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:

Normal: The event was triggered by a single left-click or via keystrokes (, , , , Tab, Space, 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.

A_EventInfo

Contains additional information about the following events:

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.

Hotkeys, Hotstrings, and Custom Menu Items

A_ThisMenuItem The name of the most recently selected custom menu item (blank if none).
A_ThisMenu The name of the menu from which A_ThisMenuItem was selected.
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.
A_ThisHotkey

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.

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, shared by all variants of the hotkey.

See also: A_ThisLabel

A_PriorHotkey Same as above except for the previous hotkey. It will be blank if none.
A_PriorKey [v1.1.01+]: The name of the last key which was pressed prior to the most recent key-press or key-release, or blank if no applicable key-press can be found in the key history. All input generated by AutoHotkey scripts is excluded. For this variable to be of use, the keyboard or mouse hook must be installed and key history must be enabled.
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-auto-replace hotstring. If no ending character was required (due to the * option), this variable will be blank.

Operating System and User Info

ComSpec [v1.0.43.08+]
A_ComSpec [v1.1.28+]

Contains the same string as the environment's ComSpec variable (e.g. C:\Windows\system32\cmd.exe). Often used with Run/RunWait.

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.
A_OSType The type of operating system being run. Since AutoHotkey 1.1 only supports NT-based operating systems, this is always WIN32_NT. Older versions of AutoHotkey return WIN32_WINDOWS when run on Windows 95/98/ME.
A_OSVersion

One of the following strings, if appropriate: WIN_7 [requires AHK_L 42+], WIN_8 [requires v1.1.08+], WIN_8.1 [requires v1.1.15+], WIN_VISTA, WIN_2003, WIN_XP, WIN_2000.

Applying compatibility settings in the AutoHotkey executable or compiled script's properties causes the OS to report a different version number, which is reflected by A_OSVersion.

[v1.1.20+]: If the OS version is not recognized as one of those listed above, a string in the format "major.minor.build" is returned. For example, 10.0.14393 is Windows 10 build 14393, also known as version 1607.

; This example is obsolete as these operating systems are no longer supported.
if A_OSVersion in WIN_NT4,WIN_95,WIN_98,WIN_ME  ; Note: No spaces around commas.
{
    MsgBox This script requires Windows 2000/XP or later.
    ExitApp
}
A_Is64bitOS [v1.1.08+]: Contains 1 (true) if the OS is 64-bit or 0 (false) if it is 32-bit.
A_PtrSize [AHK_L 42+]: Contains the size of a pointer, in bytes. This is either 4 (32-bit) or 8 (64-bit), depending on what type of executable (EXE) is running the script.
A_Language The system's default language, which is one of these 4-digit codes.
A_ComputerName The name of the computer as seen on the network.
A_UserName The logon name of the user who launched this script.
A_WinDir The Windows directory. For example: C:\Windows
A_ProgramFiles
or ProgramFiles

The Program Files directory (e.g. C:\Program Files or C:\Program Files (x86)). This is usually the same as the ProgramFiles environment variable.

On 64-bit systems (and not 32-bit systems), the following applies:

  • If the executable (EXE) that is running the script is 32-bit, A_ProgramFiles returns the path of the "Program Files (x86)" directory.
  • For 32-bit processes, the ProgramW6432 environment variable contains the path of the 64-bit Program Files directory. On Windows 7 and later, it is also set for 64-bit processes.
  • The ProgramFiles(x86) environment variable contains the path of the 32-bit Program Files directory.

[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 would contain M: rather than M:\
A_IsAdmin

If the current user has admin rights, this variable contains 1. Otherwise, it contains 0.

To have the script restart itself as admin (or show a prompt to the user requesting admin), use Run *RunAs. However, note that running the script as admin causes all programs launched by the script to also run as admin. For a possible alternative, see the FAQ.

A_ScreenWidth
A_ScreenHeight

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.

To instead discover the width and height of the entire desktop (even if it spans multiple monitors), use the following example:

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_ScreenDPI [v1.1.11+] Number of pixels per logical inch along the screen width. In a system with multiple display monitors, this value is the same for all monitors. On most systems this is 96; it depends on the system's text size (DPI) setting. See also Gui -DPIScale.
A_IPAddress1 through 4 The IP addresses of the first 4 network adapters in the computer.

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.

A_CaretX
A_CaretY

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 auto-update tooltip. Note that some windows (e.g. certain versions of MS Word) report the same caret position regardless of its actual position.

#Persistent
SetTimer, WatchCaret, 100
return
WatchCaret:
    ToolTip, X%A_CaretX% Y%A_CaretY%, A_CaretX, A_CaretY - 20
return
Clipboard Read/write: 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 Read/write: See ErrorLevel.
A_LastError The result from the OS's GetLastError() function or the last COM object invocation. For details, see DllCall() and Run/RunWait.
True
False

Contain 1 and 0. They can be used to make a script more readable. See Boolean Values for details.

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, etc. This and other related variables are valid only inside a file-loop.
A_LoopRegName, etc. This and other related variables are valid only inside a registry-loop.
A_LoopReadLine See file-reading loop.
A_LoopField See parsing loop.

Variable Capacity and Memory

  • Each variable may contain up to 64 MB of text (this limit can be increased with #MaxMem).
  • When a variable is given a new string longer than its current contents, additional system memory is allocated automatically.
  • The memory occupied by a large variable can be freed by setting it equal to nothing, e.g. var := "".
  • There is no limit to how many variables a script may create. The program is designed to support at least several million variables without a significant drop in performance.
  • Commands, functions, and expressions that accept numeric inputs generally support 15 digits of precision for floating point values. For integers, 64-bit signed values are supported, which range from -9223372036854775808 (-0x8000000000000000) to 9223372036854775807 (0x7FFFFFFFFFFFFFFF). Any integer constants outside this range are not supported and might yield inconsistent results. By contrast, arithmetic operations on integers wrap around upon overflow (e.g. 0x7FFFFFFFFFFFFFFF + 1 = -0x8000000000000000).