Variables and Expressions
Table of Contents
- Variables
- Expressions
- Operators in Expressions
- Built-in Variables
- Environment Variables vs. Normal Variables
- Variable Capacity and Memory
Variables
Variable types: AutoHotkey has no explicitly defined variable types. Instead, any variable can contain a string, integer, floating-point number, or reference to an object. Additionally, numbers are automatically converted to or from strings as required. The Type function can be used to determine the actual type of a value.
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 do not need to be 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, underscore and non-ASCII characters. Variable names must not start with a digit.
Reserved words: and
, contains
, in
, is
, new
, not
and or
. These words are reserved for use as operators and therefore cannot be used as variable names when written literally in an expression.
Names of control flow statements are also reserved, primarily to detect mistakes. This includes: Break
, Catch
, Continue
, Else
, Finally
, For
, Gosub
, Goto
, If
, Loop
, LoopFile
, LoopParse
, LoopRead
, LoopReg
, Return
, Throw
, Try
, Until
, While
Functions, classes and window groups use the same validation as variables and therefore have the same restrictions.
Storing values in variables: To store a string or number in a variable, use the colon-equal operator (:=) followed by a number, quoted string or any other type of expression. For example:
MyNumber := 123 MyString := "This is a literal string." CopyOfVar := Var
Variables which have not been assigned a value contain an empty string by default. Therefore, to erase the contents of a variable, simply assign an empty string:
MyVar := ""
A variable can also be assigned a value indirectly, by using it as an output variable of a command. For example:
MouseGetPos x, y
Retrieving the contents of variables: To include the contents of a variable in a string, use concatenation or Format. For example:
MsgBox "The value of Var is " . Var . "." MsgBox "The value in the variable named Var is " Var "." MsgBox Format("Var has the value {1}.", Var)
Sub-expressions can be combined with strings in the same way. For example:
MsgBox("The sum of X and Y is " . (X + Y))
Comparing variables: Please read the expressions section below for important notes about the different kinds of comparisons.
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 variables inside quoted strings, and 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. Single-quote marks (') and double-quote marks (") function identically, except that a string enclosed in single-quote marks can contain literal double-quote marks and vice versa. Therefore, to include an actual quote mark inside a literal string, escape the quote mark or enclose the string in the opposite type of quote mark. For example:
MsgBox "She said, `"An apple a day.`"" MsgBox 'She said, "An apple a day."'
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.
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/>/=/< automatically produce a true or false value: they yield 1 for true and 0 for false. However, the AND/OR operators always produce one of the input values. For example, in the following expression, the variable Done is assigned 1 if A_Index is greater than 5 or the value of FoundIt in all other cases:
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.
In an expression, the keywords true, false and null resolve to 1, 0 and 0. They can be used to make a script more readable as in these examples:
CaseSensitive := false ContinueSearch := true hWindow := null
Integers and floating point: Within an expression, numbers are considered to be floating point if they contain a decimal point or scientific notation; 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
. Floating point numbers can optionally be written in scientific notation, with or without a decimal point (e.g. 1e4
or -2.1E-4
).
Within expressions, unquoted literal numbers such as 128
, 0x7F
and 1.0
are converted to pure numbers before the script begins executing, so converting the number to a string may produce a value different to the original literal value. For example:
MsgBox(0x7F) ; Shows 128 MsgBox(1.00) ; Shows 1.0
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) 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.
Expression Operators (in descending precedence order)
%Expr% |
Evaluates the sub-expression Expr and uses its value as the name or partial name of a variable or function. This allows the script to refer to a variable or function whose name is not written literally in the script, but is determined by evaluating Expr, which is typically another variable. Percent signs cannot be used directly within Expr due to ambiguity, but can be nested within parentheses. Otherwise, Expr can be any expression.
If the variable does not already exist, a blank variable is created. An exception is thrown if the name is invalid. This is most commonly used to reference pseudo-array elements such as in the following example: Loop 4 MsgBox("IP address " A_Index " is " A_IPAddress%A_Index%) Although this is historically known as a "double-deref", this term is inaccurate when Expr does not contain a variable (first deref), and also when the resulting variable is the target of an assignment, not being dereferenced (second deref). |
x.y | Object access. Get or set a value or call a method of object x, where y is a literal value. See object syntax. |
new | new Class or new Class(Params) creates a new object derived from Class. For example, x := new y is often equivalent to x := {base: y} . Class can be almost any expression which produces a class object, but is typically a class name such as GlobalClass or GlobalClass.NestedClass . More complex cases such as new new (getClass())(params1)(params2) are also supported, but there must be no space between the class expression and parameter list. For details, see Custom Objects. |
++ -- |
Pre- and post-increment/decrement. Adds or subtracts 1 from a variable. 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, If the target variable is empty, the operators ++ and -- treat it as zero. This allows a line such as |
** | 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 (-): Inverts the sign of its operand. Unary plus (+): 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: 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, Address (&): |
* / // |
Multiply (*): The result is an integer if both inputs are integers; otherwise, it is a floating point number. True divide (/): True division yields a floating point result even when both inputs are integers. For example, Floor divide (//): The double-slash operator uses high-performance integer division if the two inputs are integers. For example, The *= and /= operators are a shorthand way to multiply or divide the value in a variable by another value. For example, 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, |
<< >> |
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 Var := "The color is " . FoundColor ; Explicit concat Var := "The color is " FoundColor ; Auto-concat Sub-expressions can also be concatenated. For example: A line that begins with a period (or any other operator) is automatically appended to the line above it. The entire length of each input is used, even if it includes binary zero. For example, |
~= | Shorthand for RegExMatch. For example, the result of "abc123" ~= "\d" is 4 (the position of the first numeric character). |
> < >= <= |
Greater (>), less (<), greater-or-equal (>=), and less-or-equal (<=). If either of the inputs is not numeric (or both are strings), they are compared alphabetically. For example, 2 < "10" is true whereas "2" < "10" is false. The comparison is case sensitive only if StringCaseSense has been turned on. See also: Sort When comparing strings, these operators compare only up to the first binary zero. |
= == <> != |
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 numeric (or both are strings), in which case == is always case sensitive and = is always case insensitive (the method of insensitivity depends on StringCaseSense). By contrast, <> and != obey StringCaseSense. The == operator can be used to compare strings which contain binary zero. All other comparison operators except ~= compare only up to the first binary zero. |
IS IN CONTAINS |
|
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: In the expression 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: In the expression x or y, if x is false, the result is y. Otherwise the result is x, and y is not evaluated at all - short-circuit evaluation is applied to enhance performance. Although the result is not limited to boolean 0 and 1, it can be interpreted as a boolean value as with any other expression. In effect, the result is true if either input is true. |
?: | Ternary operator. 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, |
:= += -= *= /= //= .= |= &= ^= >>= <<= |
Assign. Performs an operation on the contents of a variable and stores the result back in the same variable. 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, Unlike most other operators, assignments are evaluated from right to left. Consequently, a line such as If an assignment is used as the input for some other operator, its value is the variable itself. For example, the expression The precedence of the assignment operators is automatically raised when it would avoid a syntax error or provide more intuitive behavior. For example: If the target variable is empty, the operators += and -= treat it as zero. This allows a line such as |
, | Comma (multi-statement). 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: When a multi-statement expression is used inside another expression, each sub-expression is evaluated and the value of the final (rightmost) sub-expression becomes the result of the expression. For example, |
mod() |
These and other built-in math functions are described here. |
%func%() |
See Dynamically Calling a Function. |
F(p*) | See Variadic Functions. |
x[y] | Object access. Get or set a value or call a method of object x, where y is a parameter list or calculated method name. See array syntax and object syntax. |
Performance: 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 following variables are built into the program and can be referenced by any script. Except where noted, 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_TitleMatchMode, (...more...)
- User Idle Time: A_TimeIdle, A_TimeIdlePhysical
- 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, A_EventInfo, Clipboard, ClipboardAll, ErrorLevel
- Loop: A_Index, (...more...)
- Other: A_ScriptStruct, A_GlobalStruct, A_IsDll (...more...)
Special Characters
A_Space | Contains a single space character. |
A_Tab | Contains a single tab character. |
Script Properties
A_Args | Read/write: Contains an array of command line parameters. For details, see Passing Command Line Parameters to a Script. |
A_WorkingDir | Read/write: 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: Use SetWorkingDir or assign a path to A_WorkingDir to change the working directory. The script's working directory defaults to A_ScriptDir, regardless of how the script was launched. |
A_InitialWorkingDir | The script's initial working directory, which is determined by how it was launched. For example, if it was run via shortcut -- such as on the Start Menu -- its initial working directory is determined by the "Start in" field within the shortcut's properties. |
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 | Read/write: The default title for MsgBox, InputBox, FileSelect, DirSelect and GuiCreate. If not set by the script, it defaults to the file name of the current script, without its path, e.g. MyScript.ahk. |
A_ScriptFullPath | The full path of the current script, e.g. C:\My Documents\My Script.ahk |
A_ScriptHwnd | 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: 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: MyFunction. See also: IsFunc() |
A_ThisLabel | 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 and hotstrings. 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 | 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 HKEY_LOCAL_MACHINE\SOFTWARE\AutoHotkey\InstallDir. If there is no such entry, A_AhkPath is blank. |
A_DllPath | The full path and name of the DLL file that is actually running the current script. For example: C:\Program Files\AutoHotkey\AutoHotkey.dll. If the script is executed by EXE, it contains the path of EXE |
A_AhkDir | For non-compiled scripts: The full path and name of the directory of EXE file that is actually running the current script. For example: C:\Program Files\AutoHotkey 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_AhkDir | The full path and name of the directory of DLL file that is actually running the current script. For example: C:\Program Files\AutoHotkey, if the script is executed by EXE it contains the directory of EXE. |
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. |
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() (time and long date) or FormatTime(, "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 3-letter 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(, "YDay0") . |
A_YWeek | Current year and week number (e.g. 200453) according to ISO 8601. To separate the year from the week, use SubStr. 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(, "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 DateAdd and DateDiff. 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 | Contains 1 if the thread immediately underneath the current thread is paused. Otherwise it contains 0. |
A_IsCritical | 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. The current state of Critical can be saved and restored via Old_IsCritical := A_IsCritical followed later by A_IsCritical := Old_IsCritical . |
A_TitleMatchMode | Read/write: The current mode set by SetTitleMatchMode: 1, 2, 3, or RegEx. |
A_TitleMatchModeSpeed | Read/write: The current match speed (fast or slow) set by SetTitleMatchMode. |
A_DetectHiddenWindows | Read/write: The current mode (On or Off) set by DetectHiddenWindows. |
A_DetectHiddenText | Read/write: The current mode (On or Off) set by DetectHiddenText. |
A_StringCaseSense | Read/write: The current mode (On, Off, or Locale) set by StringCaseSense. |
A_FileEncoding | Read/write: The default encoding for various commands; see FileEncoding. |
A_SendMode | Read/write: The current mode (Event, Input, Play or InputThenPlay) set by SendMode. |
A_SendLevel | Read/write: The current SendLevel setting (an integer between 0 and 100, inclusive). |
A_StoreCapslockMode | Read/write: The current mode (On or Off) set by SetStoreCapslockMode. |
A_KeyDelay A_KeyDuration |
Read/write: The current delay or duration set by SetKeyDelay (always decimal, not hex). |
A_KeyDelayPlay A_KeyDurationPlay |
Read/write: The current delay or duration set by SetKeyDelay for the SendPlay mode (always decimal, not hex). |
A_WinDelay | Read/write: The current delay set by SetWinDelay (always decimal, not hex). |
A_ControlDelay | Read/write: The current delay set by SetControlDelay. |
A_MouseDelay A_MouseDelayPlay |
Read/write: 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_DefaultMouseSpeed | Read/write: The current speed set by SetDefaultMouseSpeed. |
A_CoordModeToolTip A_CoordModePixel A_CoordModeMouse A_CoordModeCaret A_CoordModeMenu |
Read/write: The current mode (Client = 0, Window/Relative 0 1 or Screen = 2) set by CoordMode. |
A_RegView | Read/write: 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. Known limitation: This path may be incorrect if the script originally passed a relative path to a system DLL; for example, Menu "Tray", "Icon", "user32.dll", 2 . |
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:
if 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). |
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 | 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
A_ComSpec | Contains the same string as the environment's ComSpec variable (e.g. C:\Windows\system32\cmd.exe). Often used with Run/RunWait. |
A_Temp | 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_OSVersion |
The version number of the operating system, in the format "major.minor.build". For example, Windows 7 SP1 is 6.1.7601. 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. |
A_Is64bitOS | Contains 1 (true) if the OS is 64-bit or 0 (false) if it is 32-bit. |
A_PtrSize | 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 |
The Program Files directory (e.g. On 64-bit systems (and not 32-bit systems), the following applies:
|
A_AppData | 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 | 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 |
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: VirtualWidth := SysGet(78) VirtualHeight := SysGet(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 | 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 the GUI's -DPIScale option. |
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. |
A_Input | Current text of Input, used in multi-threading environment to retrieve or change the text of Input. It is also available after Input exited or before it started (see A option). |
A_GlobalStruct (low level) | Pointer to internal global structure. |
A_MainThreadID | Id of main thread (exe). |
A_ModuleHandle | Handle of currently executed Module (dll/exe). |
A_ScriptStruct (low level) | Pointer to internal script structure. |
A_ThreadID | Handle of currently executed Thread. |
A_EventInfo | Contains additional information about the following events:
Note: Unlike variables such as A_ThisHotkey, each thread retains its own value for A_EventInfo. Therefore, if a thread is interrupted by another, upon being resumed it will still see its original/correct values in these variables. Read/write: A_EventInfo can also be set by the script, but can only accept unsigned integers within the range available to pointers (32-bit or 64-bit depending on the version of AutoHotkey). |
Clipboard | Read/write: The contents of the OS's clipboard, which can be read or written to. See the Clipboard section. |
ClipboardAll | Read-only: The entire contents of the clipboard (such as formatting and text). See ClipboardAll. |
ErrorLevel | Read/write: See ErrorLevel. |
A_LastError | Read/write: This is usually the result from the OS's GetLastError() function after the script calls certain commands/functions, or the HRESULT of the last COM object invocation. See DllCall() or Run/RunWait for more details. Assigning a value to A_LastError also causes the OS's SetLastError() function to be called. |
Loop
A_Index | Read/write: 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. |
Environment Variables vs. "Normal" Variables
Environment variables are maintained by the operating system. You can see a list of them at the command prompt by typing SET then pressing Enter. Use EnvGet or EnvSet to retrieve or set environment variable.
A script may create a new environment variable or change the contents of an existing one with EnvSet. However, such additions and changes are private; they are not seen by the rest of the system. One exception is when a script uses Run or RunWait to launch a program (even another script): such programs inherit a copy of the parent script's environment variables, including private ones.
Variable Capacity and Memory
- 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).