autoHotKeyHelp For Vim version 7.3 Last change: 2018 Apr 14
==============================================================================
*WinSet*
+--------+~
| WinSet |~
+--------+~
Makes a variety of changes to the specified window, such as "always on
top" and transparency.
|WinSet|, Attribute , Value [, WinTitle, WinText, ExcludeTitle,
ExcludeText ]
Parameters~
Attribute, Value
-----------------
See list below.
WinTitle
--------
A window title or other criteria identifying the target window. See
|WinTitle|.
WinText
-------
If present, this parameter must be a substring from a single text
element of the target window (as revealed by the included Window Spy
utility). Hidden text elements are detected if DetectHiddenText is
ON.
ExcludeTitle
------------
Windows whose titles include this value will not be considered.
ExcludeText
-----------
Windows whose text include this value will not be considered.
Attribute, Value~
AlwaysOnTop , [ On | Off | Toggle ]
-----------------------------------
Makes a window stay on top of all other windows. Use ON to turn on the
setting, OFF to turn it off, or TOGGLE to set it to the opposite of
its current state. If omitted, it defaults to TOGGLE. The word
Topmost can be used in place of AlwaysOnTop.
Bottom
------
Sends a window to the bottom of stack; that is, beneath all other
windows. The effect is similar to pressing Alt-Escape . For example:
>
WinSet, Bottom,, WinTitle
<
Top
-----
Brings a window to the top of the stack without explicitly activating
it. However, the system default settings will probably cause it to
activate in most cases. In addition, this command may have no effect
due to the operating system's protection against applications that try
to steal focus from the user (it may depend on factors such as what
type of window is currently active and what the user is currently
doing). One possible work-around is to make the window briefly
AlwaysOnTop, then turn off AlwaysOnTop.
Disable or Enable
-----------------
Disables or enables a window (respectively). When a window is
disabled, the user cannot move it or interact with its controls. In
addition, disabled windows are omitted from the alt-tab list.
Redraw
------
Attempts to update the appearance/contents of a window by informing
the OS that the window's rectangle needs to be redrawn. If this method
does not work for a particular window, try |WinMove|. If that does
not work, try the following:
>
WinHide, WinTitle
WinShow, WinTitleStyle,
<
Style, N or ExStyle, N
----------------------
Changes the style or extended style of a window, respectively. If the
first character of N is a plus or minus sign, the style(s) in N are
added or removed, respectively. If the first character is a caret (^),
the style(s) in N are each toggled to the opposite state. If the first
character is a digit, the window's style is overwritten completely;
that is, it becomes N.
ErrorLevel is set to 1 upon failure and 0 upon success. Failure occurs
if the target window is not found or the style is not allowed to be
applied (which happens more often on Windows 9x).
After applying certain style changes to a visible window, it might be
necessary to redraw the window using |WinSet| Redraw (see below).
Finally, the styles table lists some of the common style numbers.
Examples:
>
WinSet, Style, -0xC00000, A
; Remove the active window's title bar (WS_CAPTION).
WinSet, ExStyle, ^0x80, WinTitle
; Toggle the WS_EX_TOOLWINDOW attribute, which
; removes/adds the window from the alt-tab list
<
WinSet, Region [, Options, WinTitle, ...]
-----------------------------------------
Changes the shape of a window to be the specified rectangle, ellipse,
or polygon. If the Options parameter is blank, the window is restored
to its original/default display area. Otherwise, one or more of the
following options can be specified, each separated from the others
with space(s):
Wn
-----
Width of rectangle or ellipse. For example: w200
Hn
-----
Height of rectangle or ellipse. For example: h300
X-Y
-----
Each of these is a pair of X/Y coordinates. For example, 200-0 would
use 200 for the X coordinate and 0 for the Y.
E
-----
Makes the region an ellipse rather than a rectangle. This option is
valid only when W and H are present.
R [w-h]
-------
Makes the region a rectangle with rounded corners. For example,
>
R30-30
would use a 30x30 ellipse for each corner. If w-h is omitted, 30-30 is
used. R is valid only when W and H are present.
Rectangle or ellipse ~
If the W and H options are present, the new display area will be a
rectangle whose upper left corner is specified by the first (and only)
pair of X-Y coordinates. However, if the E option is also present, the
new display area will be an ellipse rather than a rectangle. For
example:
>
WinSet, Region, 50-0 W200 H250 E, WinTitle
<
Polygon ~
When the W and H options are absent, the new display area will be a
polygon determined by multiple pairs of X-Y coordinates (each pair of
coordinates is a point inside the window relative to its upper left
corner). For example, if three pairs of coordinates are specified, the
new display area will be a triangle in most cases. The order of the
coordinate pairs with respect to each other is sometimes important. In
addition, the word Wind maybe be present in Options to use the winding
method instead of the alternating method to determine the polygon's
region.
ErrorLevel is set to 1 upon failure and 0 upon success. Failure occurs
when: 1) the target window does not exist; 2) one or more Options are
invalid; 3) more than 2000 pairs of coordinates were specified; or 4)
the specified region is invalid or could not be applied to the target
window.
See the bottom of this page for examples of how to use this command.
WinSet, Transparent, N, WinTitle~
Makes a window semi-transparent. Specify for N a number between 0 and
255 to indicate the degree of transparency: 0 makes the window
invisible while 255 makes it opaque. Transparency may be turned off
completely for a window by specifying the word OFF. This is
different than specifying 255 because it may improve performance and
reduce usage of system resources.
Known Limitations for Transparent and TransColor:
- They have no effect on Windows 9x and NT4.
- They have no effect on a window that lacks a caption (title bar) and
lacks the always-on-top property. For GUI windows, this can be
solved by removing the caption only after making the window
transparent. Alternatively, the following properties allow
transparency to take effect: Gui -Caption +ToolWindow.
- Setting "Transparent" to 255 prior to turning it off might avoid
window redrawing problems such as a black background. If the window
still fails to be redrawn correctly, see |Redraw| for a possible
workaround.
- To change a window's existing TransColor, it may be necessary to
turn off transparency before making the change.
Tip ~
-----
To make the task bar transparent, use
>
WinSet, Transparent, 150, ahk_class Shell_TrayWnd
<
Similarly, to make the Start Menu transparent, follow this example:
>
DetectHiddenWindows, on
WinSet, Transparent, 150, ahk_class BaseBar
; To make the Start Menu's submenus transparent, also
; include the script below
<
To make all or selected menus on the entire system transparent, keep a
script such as the following always running. Note that although such a
script cannot make its own menus transparent, it can make those of
other scripts transparent:
>
#Persistent
SetTimer, WatchForMenu, 5
return ; End of auto-execute section.
WatchForMenu:
DetectHiddenWindows, on ; Might allow detection of menu sooner.
IfWinExist, ahk_class #32768
WinSet, Transparent, 150
; Uses the window found by the above line.
return
<
WinSet, TransColor, Color [N], WinTitle~
Makes all pixels of the chosen color invisible inside the target
window, which allows the contents of the window behind it to show
through (has no effect on Windows 9x and NT4). If the user clicks on
an invisible pixel, the click will "fall through" to the window behind
it. Specify for Color a color name or RGB value (see the color chart
for guidance, or use |PixelGetColor| in its RGB mode). To additionally
make the visible part of the window partially transparent, append a
space (not a comma) followed by the transparency level ( 0 - 255 ).
For example:
>
WinSet, TransColor, EEAA99 150, WinTitle
<
TransColor is often used to create on-screen displays and other visual
effects. There is an example of an on-screen display at the bottom of
the Gui page.
The word OFF may be specified to completely turn off transparency for
a window. Both of the following are identical in function:
>
WinSet, Transparent, Off, WinTitle
WinSet, TransColor, Off, WinTitleKnown Limitations: See the list above.
<
Remarks~
ErrorLevel is not changed by this command except where indicated above.
Although transparency is supported on Windows 2000/XP or later,
retrieving the current transparency settings of a window is possible
only on Windows XP or later (via |WinGet|).
A script's |SplashText| window can be made non-AlwaysOnTop via:
>
WinSet, AlwaysOnTop, Off, My Splash Window Title
<
Window titles and text are case sensitive. Hidden windows are not
detected unless DetectHiddenWindows has been turned on.
Related~
|WinGet|, |WinHide|, |WinSetTitle|, |WinMove|, |WinActivate|,
|Control|
Examples~
>
WinSet, Transparent, 200, Untitled - Notepad
; Make the window a little bit transparent.
WinSet, TransColor, White, Untitled - Notepad
; Make all white pixels invisible.
WinSet, AlwaysOnTop, toggle, Calculator
; Toggle the always-on-top status of Calculator.
; Longer Example:
; Here are some hotkeys that demonstrate the effects of
; "Transparent" and "TransColor". NOTE: If you press one of
; the hotkeys while the mouse cursor is hovering over a pixel
; that is invisible as a result of TransColor, the window
; visible beneath that pixel will be acted upon instead!
; Also, Win+G will have an effect only on Windows XP because
; retrieval of transparency settings is not supported by
; Windows 2000:
#t:: ; Press Win+T to make the color under the mouse cursor invisible.
MouseGetPos, MouseX, MouseY, MouseWin
PixelGetColor, MouseRGB, %MouseX%, %MouseY%, RGB
; In seems necessary to turn off any existing transparency first:
WinSet, TransColor, Off, ahk_id %MouseWin%
WinSet, TransColor, %MouseRGB% 220, ahk_id %MouseWin%
return
#o:: ; Press Win+O to turn off transparency for the window under the mouse.
MouseGetPos,,, MouseWin
WinSet, TransColor, Off, ahk_id %MouseWin%
return
#g:: ; Press Win+G to show the current settings of the window under the mouse.
MouseGetPos,,, MouseWin
WinGet, Transparent, Transparent, ahk_id %MouseWin%
WinGet, TransColor, TransColor, ahk_id %MouseWin%
ToolTip Translucency:`t%Transparent%`nTransColor:`t%TransColor%
return
; Examples of "WinSet Region":
WinSet, Region, 50-0 W200 H250, WinTitle
; Make all parts of the window outside this rectangle
; invisible.
WinSet, Region, 50-0 W200 H250 R40-40, WinTitle
; Same as above but with corners rounded to 40x40.
WinSet, Region, 50-0 W200 H250 E, WinTitle
; An ellipse instead of a rectangle.
WinSet, Region, 50-0 250-0 150-250, WinTitle
; A triangle with apex pointing down.
WinSet, Region,, WinTitle
; Restore the window to its original/default display area.
; Here is a region with a more complex area. It creates a
; see-through rectangular hole inside a window. There are two
; rectangles specified below: an outer and an inner. Each
; rectangle consists of 5 pairs of X/Y coordinates because the
; first pair is repeated at the end to "close off" each
; rectangle. WinSet, Region, 0-0 300-0 300-300 0-300 0-0
; 100-100 200-100 200-200 100-200 100-100, WinTitle
<
==============================================================================
*WinTitle*
+----------+~
| WinTitle |~
+----------+~
The WinTitle Parameter & the Last Found Window
Many commands and a few functions have a |WinTitle| parameter, used to
identify which window (or windows) to operate on. This parameter can
be the title or partial title of the window, and/or any other criteria
described on this page.
Quick Reference: ~
Title Matching Behaviour
A The Active Window
ahk_class Window Class
ahk_id Unique ID/HWND
ahk_pid Process ID
ahk_exe Process Name/Path
ahk_group Window Group
Multiple Criteria
(All empty) Last Found Window
Matching Behaviour~
|SetTitleMatchMode| controls how a partial or complete title is
compared against the title of each window. Depending on the setting,
WinTitle can be an exact title, or it can contain a prefix, a
substring which occurs anywhere in the title, or a RegEx pattern. This
setting also controls whether ahk_class is interpreted as an exact
class name or a RegEx pattern.
Hidden windows are only detected if DetectHiddenWindows is On, except
with |WinShow|, which always detects hidden windows.
If multiple windows match the WinTitle and any other criteria, the
topmost matching window is used. If the active window matches the
criteria, it usually takes precedence since it is usually above all
other windows. However, if an always-on-top window also matches (and
the active window is not always-on-top), it may be used instead.
Active Window (A)~
If WinTitle is the letter A and the other 3 window parameters
(WinText , ExcludeTitle and ExcludeText) are blank or omitted,
the active window will be used.
>
; Retrieve the ID/HWND of the active window
id := WinExist("A")
MsgBox % id
; Press Win+? to maximize the active window
#Up::WinMaximize, A
<
ahk_class Window Class~
A window class is a set of attributes that the system uses as a
template to create a window. In other words, the class name of the
window identifies what type of window it is. To use a window class,
specify ahk_class ExactClassName as shown by Window Spy.
ExactClassName can be retrieved by WinGetClass.
If the RegEx title matching mode is active, ahk_class accepts a
regular expression.
>
; Activate a console window (e.g. cmd.exe)
WinActivate, ahk_class ConsoleWindowClass
<
ahk_id Unique ID / HWND~
Each window or control has a unique ID, also known as a HWND (short
for handle to window). This ID can be used to identify the window or
control even if its title changes. The ID of a window is typically
retrieved via |WinExist|() or |WinGet|. The ID of a control is typically
retrieved via |ControlGet| Hwnd, |MouseGetPos|, or |DllCall|. Also, ahk_id
will operate on controls even if they are hidden; that is, the setting
of DetectHiddenWindows does not matter for controls.
>
WinActivate, ahk_id %VarContainingID%
<
ahk_pid Process ID~
Use ahk_pid to identify a window belonging to a specific process. The
process identifier (PID) is typically retrieved by |WinGet|, |Run| or
|Process|.
>
WinActivate, ahk_pid %VarContainingPID%
<
ahk_exe Process Name/Path~
Use ahk_exe to identify a window belonging to any process with the
given name or path.
While ahk_pid is limited to one specific process, ahk_exe considers
all processes with name or full path matching a given string. If the
RegEx title matching mode is active, ahk_exe accepts a regular
expression. Otherwise, ahk_exe accepts a case-insensitive name or full
path; for example, ahk_exe notepad.exe covers ahk_exe
C:\Windows\Notepad.exe, ahk_exe C:\Windows\System32\Notepad.exe and
other variations.
>
; Activate an existing notepad.exe window, or open a new one
if WinExist("ahk_exe notepad.exe")
WinActivate, ahk_exe notepad.exe
else
Run, notepad.exe
<
ahk_group Window Group~
Use ahk_group to identify a window or windows matching the rules
contained by a previously defined window group.
The commands |WinMinimize|, |WinMaximize|, |WinRestore|, |WinHide|,
|WinShow|, |WinClose|, and |WinKill| will act on all the group's
windows. By contrast, the other window commands such as |WinActivate|
and |IfWinExist| will operate only on the topmost window of the group.
>
; Define the group: Windows Explorer windows
GroupAdd, Explorer, ahk_class ExploreWClass ; Unused on Vista and later
GroupAdd, Explorer, ahk_class CabinetWClass
; Activate any window matching the above criteria
WinActivate, ahk_group Explorer
<
Multiple Criteria~
By contrast with ahk_group (which broadens the search), the search may
be narrowed by specifying more than one criterion within the
|WinTitle| parameter. In the following example, the script waits for a
window whose title contains My File.txt and whose class is Notepad:
>
WinWait My File.txt ahk_class Notepad
WinActivate ; Activate the window it found.
<
When using this method, the text of the title (if any is desired)
should be listed first, followed by one or more additional criteria.
Criteria beyond the first should be separated from the previous with
exactly one space or tab (any other spaces or tabs are treated as a
literal part of the previous criterion).
ahk_id can be combined with other criteria to test a window's title,
class or other attributes:
>
MouseGetPos,,, id
if WinExist("ahk_class Notepad ahk_id " id)
MsgBox The mouse is over Notepad.
<
The "Last Found" Window~
This is the window most recently found by |IfWin| [Not] |Exist|,
|WinExist|(), |IfWin| [Not] |Active|, |WinActive|(), |WinWait| [Not]
|Active|, or |WinWait|. It can make scripts easier to create and
maintain since the |WinTitle| and |WinText| of the target window do
not need to be repeated for every windowing command. In addition,
scripts perform better because they don't need to search for the
target window again after it has been found the first time.
The "last found" window can be used by all of the windowing commands
except |WinWait|, |WinActivateBottom|, and |GroupAdd|. To use it, simply
omit all four window parameters (|WinTitle|, |WinText|, |ExcludeTitle|, and
|ExcludeText|).
Each thread retains its own value of the "last found" window, meaning
that if the current thread is interrupted by another, when the
original thread is resumed it will still have its original value of
the "last found" window, not that of the interrupting thread.
If the last found window is a hidden Gui window , it can be used even
when DetectHiddenWindows is Off. This is often used in conjunction
with Gui +LastFound.
>
Run Notepad
WinWait Untitled - Notepad
WinActivate ; Uses the last found window.
IfWinExist, Untitled - Notepad
{
WinActivate ; Automatically uses the window found above.
WinMaximize ; same
Send, Some text.{Enter}
return
}
IfWinNotExist, Calculator
return
else
{
WinActivate
; The above "IfWinNotExist" also set the "last found"
; window for us.
WinMove, 40, 40
; Move it to a new position.
return
}
<
==============================================================================
*#Persistent*
+-------------+~
| #Persistent |~
+-------------+~
Keeps a script permanently running (that is, until the user closes it
or |ExitApp| is encountered).
>
#Persistent
<
If this directive is present anywhere in the script, that script will
stay running after the auto-execute section (top part of the script)
completes. This is useful in cases where a script contains timers
and/or custom menu items but not hotkeys , hotstrings , or any use of
|OnMessage|() or Gui.
If this directive is added to an existing script, you might want to
change some or all occurrences of |Exit| to be |ExitApp| . This is
because |Exit| will not terminate a persistent script; it terminates
only the current thread.
In v1.0.16+, this directive also makes a script single-instance. To
override this or change the way single-instance behaves, see
#SingleInstance.
Related~
#SingleInstance, |SetTimer|, |Menu|, |Exit|, |ExitApp|
Example~
>
#Persistent
<
==============================================================================
*Variables_and_Expressions*
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. 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 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 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~
------------------------------------------------------------------------------
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 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.
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.
*object_method_operator*
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.
*pre_and_post_increment*
++~
--~
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_operator*
**~
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*
-~
!~
& *~
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*
!~
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. In v1.0.46+,
consecutive unary operators such as !!Var are allowed because they are
evaluated in right-to-left order.
*bitwise_not*
~ ~
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_of*
&~
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_operator*
*~
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_operator*
*~
/~
//~
Multiply (*): The result is an integer if both inputs are integers;
otherwise, it is a floating point number.
*true_divide_operator*
/~
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_operator*
//~
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_operator*
*plus_and_minus_operator*
+~
-~
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*
<<~
>>~
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_exclusive_or_or_operators*
&~
^~
|~
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*
.~
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.
*regex_match_operator*
~=~
[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_than_less_than*
*greater_than_equal_less_than_equal*
> <~
>= <=~
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_not_equal*
=~
==~
<> !=~
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.
*logical_not_operator*
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_operator*
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_operator*
OR~
||~
Both of these are logical-OR. For example: x <= 3 or x >= 10. To
enhance performance, short-circuit evaluation is applied.
*ternary_operator*
?:~
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_operator*
+=~
-=~
*=~
/=~
//=~
.=~
|=~
&=~
^=~
>>=~
<<=~
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.
*coma_operator*
,~
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
*maths_functions*
mod()~
round()~
abs()~
These and other built-in math functions are described here.
func.()~
[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.
F(p*)~
[AHK_L 60+]: See Variadic Functions.
x[y]~
[AHK_L 31+]: 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: In 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*
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...)
Date and Time Properties~
A_MM, A_DD, A_MMMM... (...more...)
Script Settings~
A_IsSuspended , A_BatchLines , A_TitleMatchMode ,
(...more...)
User Idle Time Properties~
A_TimeIdle , A_TimeIdlePhysical
GUI~
Windows and Menu Bars Properties~
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 Properties~
A_OSVersion , A_ScreenWidth , A_ScreenHeight , (...more...)
Misc Properties~
A_Cursor , A_CaretX , A_CaretY , Clipboard,
ClipboardAll, ErrorLevel
Loop Properties~
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*
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.
[|passing_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.
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
[|functions|] 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 , 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,
[|convert_a_script_to_exe|] 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_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. 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.
*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_properties*
Date and Time Properties~
*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 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, 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*
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_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_KeyDelay*
The current delay set by |SetKeyDelay| (always decimal, not hex). This
delay is for the traditional |SendEvent| mode, not |SendPlay|.
*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*
The current delay set by |SetMouseDelay| (always decimal, not hex).
This delay is for the traditional |SendEvent| mode, not |SendPlay|.
*A_DefaultMouseSpeed*
The current speed set by |SetDefaultMouseSpeed| (always decimal, not
hex).
*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. 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 Properties ~
*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, last keyboard or mouse activity at least 10 minutes ago
(^^ this should be together coudn't fit)
*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).
*gui_windows_and_menu_bars_properties*
GUI Windows and Menu Bars Properties~
*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.
*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.
*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
(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|.
*A_EventInfo*
Contains additional information about the following events:
- The OnClipboardChange label
- Mouse wheel hotkeys (WheelDown / Up / Left / Right )
- |RegisterCallback|()
- GUI events , namely |GuiContextMenu|, |GuiDropFiles|, |ListBox|,
|ListView|, |TreeView|, and |StatusBar|. If there is no additional
information for an event, A_EventInfo contains 0.
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*
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. 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_properties*
Operating System and User Properties ~
*ComSpec*
[v1.0.43.08+] Contains the same string as the environment's ComSpec
variable (e.g. C:\Windows\system32\cmd.exe). Often used with
|Run|/|RunWait|. Note: there is no A_ prefix on this variable.
*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. 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: WIN_7 [requires AHK_L], WIN_8 [requires
v1.1.08+], WIN_VISTA , WIN_2003 , WIN_XP , WIN_2000 .
>
; 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).
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 would
contain M: rather than M:\
*A_IsAdmin*
If the current user has admin rights, this variable contains 1.
Otherwise, it contains 0. Under Windows 95/98/Me, this variable always
contains 1.
On Windows Vista or later, some scripts might require administrator
privileges to function properly (such as a script that interacts with
a process or window that is run as administrator). To achieve this,
add the following at the top of the script:
>
if not A_IsAdmin
{
Run *RunAs "%A_ScriptFullPath%" ; Requires v1.0.92.01+
ExitApp
}
<
*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 (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 The IP addresses of the first 4 network adapters in the
computer.
*misc_properties*
Misc. Properties~
*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.
*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
<
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 or the last COM
object invocation. For details, see |DllCall|() and |Run|/|RunWait|.
Loop Properties~
*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.
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.
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.
In v1.0.43.08+, it is recommended that all new scripts retrieve
environment variables such as Path via:
>
EnvGet, OutputVar, Path ; For explanation, see #NoEnv
<
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).
==============================================================================
*WinActivate*
+-------------+~
| WinActivate |~
+-------------+~
Activates the specified window (makes it foremost).
|WinActivate| [, WinTitle, WinText, ExcludeTitle, ExcludeText ]
Parameters~
WinTitle
--------
A window title or other criteria identifying the target window. See
|WinTitle|.
WinText
-------
If present, this parameter must be a substring from a single text
element of the target window (as revealed by the included Window Spy
utility). Hidden text elements are detected if DetectHiddenText is ON.
ExcludeTitle
------------
Windows whose titles include this value will not be considered.
ExcludeText
-----------
Windows whose text include this value will not be considered.
Remarks~
If the window is minimized, it is automatically restored prior to
being activated.
Six attempts will be made to activate the target window over the
course of 60ms. Thus, it is usually unnecessary to follow
|WinActivate| with |WinWaitActive| or |IfWinNotActive|.
If a matching window is already active, that window will be kept
active rather than activating any other matching window beneath it. In
general, if more than one window matches, the topmost (most recently
used) will be activated. You can activate the bottommost (least
recently used) via |WinActivateBottom|.
When a window is activated immediately after the activation of some
other window, task bar buttons might start flashing on some systems
(depending on OS and settings). To prevent this, use
#WinActivateForce.
Window titles and text are case sensitive. Hidden windows are not
detected unless DetectHiddenWindows has been turned on.
Related~
|WinActivateBottom|, #WinActivateForce, |SetTitleMatchMode|,
|DetectHiddenWindows|, |Last| |Found| |Window|, |IfWinExist|, |IfWinActive|,
|WinWaitActive|, |WinWait|, |WinWaitClose|, |WinClose|, |GroupActivate|, |WinSet|
Example~
>
IfWinExist, Untitled - Notepad
WinActivate ; use the window found above
else
WinActivate, Calculator
<
==============================================================================
*WinWaitActive* / *WinWaitNotActive*
------------------------------------------------------------------------------
+----------------------------------+~
| WinWaitActive / WinWaitNotActive |~
+----------------------------------+~
Waits until the specified window is active or not active.
>
WinWaitActive [, WinTitle, WinText, Seconds, ExcludeTitle, ExcludeText]
WinWaitNotActive [, WinTitle, WinText, Seconds, ExcludeTitle, ExcludeText]
Parameters~
WinTitle
--------
A window title or other criteria identifying the target window. See
WinTitle.
WinText
-------
If present, this parameter must be a substring from a single text
element of the target window (as revealed by the included Window Spy
utility). Hidden text elements are detected if DetectHiddenText is ON.
Seconds
-------
How many seconds to wait before timing out and setting ErrorLevel to
1. Leave blank to wait indefinitely. Specifying 0 is the same as
specifying 0.5. This parameter can be an expression.
ExcludeTitle
------------
Windows whose titles include this value will not be considered.
ExcludeText
-----------
Windows whose text include this value will not be considered.
ErrorLevel
----------
ErrorLevel is set to 1 if the command timed out or 0 otherwise.
Remarks~
If a matching window satisfies the command's expectation, the command
will not wait for Seconds to expire. Instead, it will immediately set
ErrorLevel to 0 and the script will continue executing.
Both WinWaitActive and WinWaitNotActive will update the Last Found
Window if a qualified window is active when the command begins. In
addition, WinWaitActive will update the Last Found Window if a
qualified window becomes active before the command times out.
While the command is in a waiting state, new threads can be launched
via hotkey, custom menu item, or timer.
If another thread changes the contents of any variable(s) that were
used for this command's parameters, the command will not see the
change -- it will continue to use the title and text that were
originally present in the variables when the command first started
waiting.
Window titles and text are case sensitive. Hidden windows are not
detected unless DetectHiddenWindows has been turned on.
Related~
|WinWait|, |WinWaitClose|, |IfWinExist|, |IfWinActive|,
|SetTitleMatchMode|, |DetectHiddenWindows|
Example~
>
Run, notepad.exe
WinWaitActive, Untitled - Notepad, , 2
if ErrorLevel
{
MsgBox, WinWait timed out.
return
}
else
WinMinimize ; minimize the window found by WinWaitActive.
<
==============================================================================
*IfWinActive* *IfWinNotActive*
+----------------------------+~
| IfWinActive-IfWinNotActive |~
+----------------------------+~
Checks if the specified window exists and is currently active (foremost).
|IfWinActive| [, WinTitle, WinText, ExcludeTitle, ExcludeText ]
|IfWinNotActive| [, WinTitle, WinText, ExcludeTitle, ExcludeText ]
UniqueID := |WinActive|("WinTitle", "WinText", "ExcludeTitle", "ExcludeText")
Parameters~
WinTitle
--------
A window title or other criteria identifying the target window. See
WinTitle.
WinText
-------
If present, this parameter must be a substring from a single text
element of the target window (as revealed by the included Window Spy
utility). Hidden text elements are detected if DetectHiddenText is ON.
ExcludeTitle
------------
Windows whose titles include this value will not be considered. Note:
Due to backward compatibility, this parameter will be interpreted as a
command if it exactly matches the name of a command. To work around
this, use the |WinActive|() function instead.
ExcludeText
-----------
Windows whose text include this value will not be considered.
Remarks~
If all parameters are omitted, the Last Found Window will be used.
If either of these commands determines that the active window is a
qualified match, the Last Found Window will be updated to be the
active window. In other words, if |IfWinActive| evaluates to "true" or
|IfWinNotActive| evaluates to "false", the Last Found Window will
be updated.
The function |WinActive|() returns the Unique ID ( HWND ) of the
active window if it matches the specified criteria. If it does not,
the function returns 0. Since all non-zero numbers are seen as "true",
the statement >
if WinActive("WinTitle")
<
is true whenever |WinTitle| is active.
|SetWinDelay| does not apply to |IfWinExist| / |IfWinActive|.
Window titles and text are case sensitive. Hidden windows are not
detected unless |DetectHiddenWindows| has been turned on.
Related~
|IfWinExist|, |SetTitleMatchMode|, |DetectHiddenWindows|, Last Found
Window, |WinActivate|, |WinWaitActive|, |WinWait|, |WinWaitClose|,
|#IfWinActive| / |Exist|
Example~
>
IfWinActive, Untitled - Notepad
{
WinMaximize ; Maximizes the Notepad window found by IfWinActive above.
Send, Some text.{Enter}
return
}
if WinActive("ahk_class Notepad") or WinActive("ahk_class" . ClassName)
; "ahk_class" need not have a space after it.
WinClose ; Uses the last found window.
<
==============================================================================
*Click*
+-------+~
| 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.
Here are examples of common usages (all commas are optional):
|Click| (by itself)
Clicks the left mouse button once at the mouse cursor's current
position
|Click| 44 , 55
Clicks the left mouse button once at coordinates 44, 55 (based on
CoordMode)
|Click| right 44 , 55
Same as above but clicks the right mouse button
|Click| 2
Clicks the left mouse button twice at the cursor's current position
(i.e. double-click).
|Click| down
Presses the left mouse button down and holds it
|Click| up right
Releases the right mouse button
|Click| %x% %y%
Since click does not support expressions, variables should be enclosed
in percent signs.
Zero or more of the following items can follow the word |Click|.
Separate each item from the next with at least one space, tab, and/or
comma. The items can appear in any order except ClickCount , which
must occur somewhere to the right of the coordinates (if coordinates
are present).
X , Y
-----
The x/y coordinates to which the mouse cursor is moved prior to
clicking. Coordinates are relative to the active window unless
CoordMode was used to change that. If omitted, the cursor's current
position is used.
Button Name
-----------
Left (default), Right , Middle (or just the first letter of each of
these); or the fourth or fifth mouse button (X1 or X2), which are
supported on Windows 2000/XP or later. NOTE: Unlike |MouseClick| , the
left and right buttons behave consistently across all systems, even if
the user has swapped the buttons via the system's control panel.
Mouse Wheel
-----------
(this has no effect on Windows 9x): Specify WheelUp or WU to turn the
wheel upward (away from you); specify WheelDown or WD to turn the
wheel downward (toward you). In v1.0.48+, WheelLeft (or WL) or
WheelRight (or WR) may also be specified (but they have no effect on
older operating systems older than Windows Vista). For ClickCount
(below), specify the number of notches to turn the wheel. However,
some applications do not obey a ClickCount higher than 1 for the mouse
wheel. For them, use a Loop such as the following:
>
Loop 5
Click WheelUp
<
ClickCount
----------
The number of times to click the mouse (examples: |Click| 2 , |Click|
100 , 200 , 2 ). If omitted, the button is clicked once. If
coordinates are specified, ClickCount must appear after them. Specify
zero ( 0 ) to move the mouse without clicking (for example: |Click|
100 , 200 , 0 ).
Down or Up
----------
These words are normally omitted, in which case each click consists of
a down-event followed by an up-event. Otherwise, specify Down (or the
letter D) to press the mouse button down without releasing it. Later,
use the word Up (or the letter U) to release the mouse button
Relative
--------
The word Rel or Relative treats the specified X and Y coordinates as
offsets from the current mouse position. In other words, the cursor
will be moved from its current position by X pixels to the right (left
if negative) and Y pixels down (up if negative).
Remarks~
|Click| is generally preferred over |MouseClick| because it automatically
compensates if the user has swapped the left and right mouse buttons
via the system's control panel
|Click| uses the sending method set by |SendMode|. To override this
mode for a particular click, use a specific Send command as in this
example: |SendEvent| { Click , 100, 200 }.
To perform a shift-click or control-click, the |Send| {Click} method
is generally easiest. For example:
>
Send +{Click 100, 200} ; Shift+LeftClick
Send ^{Click 100, 200, right} ; Control+RightClick
<
Unlike |Send|, |Click| does not automatically release the modifier
keys (Control , Alt , Shift , and Win). For example, if the Control
key is currently down, Click would produce a control-click but |Send|
{Click} would produce a normal click.
The |SendPlay| mode is able to successfully generate mouse events in a
broader variety of games than the other modes. In addition, some
applications and games may have trouble tracking the mouse if it moves
too quickly, in which case |SetDefaultMouseSpeed| can be used to reduce
the speed (but only in |SendEvent| mode).
The |BlockInput| command can be used to prevent any physical mouse
activity by the user from disrupting the simulated mouse events
produced by the mouse commands. However, this is generally not needed
for the |SendInput| and |SendPlay| modes because they automatically
postpone the user's physical mouse activity until afterward
There is an automatic delay after every click-down and click-up of the
mouse (except for |SendInput| mode and for turning the mouse wheel).
Use |SetMouseDelay| to change the length of the delay.
Related~
|Send| {Click}, |SendMode|, |CoordMode|, |SetDefaultMouseSpeed|,
|SetMouseDelay|, |MouseClick|, |MouseClickDrag|, |MouseMove|,
|ControlClick|, |BlockInput|
Examples~
>
Click ; Click left mouse button at mouse cursor's current position.
Click 100, 200 ; Click left mouse button at specified coordinates.
Click 100, 200, 0 ; Move the mouse without clicking.
Click 100, 200 right ; Click the right mouse button.
Click 2 ; Perform a double-click.
Click down ; Presses down the left mouse button and holds it.
Click up right ; Releases the right mouse button.
<
==============================================================================
*CoordMode*
+-----------+~
| CoordMode |~
+-----------+~
Sets coordinate mode for various commands to be relative to either the
active window or the screen.
|CoordMode|, ToolTip | Pixel | Mouse | Caret | Menu [, Screen | Window
| Client ]
Parameters~
Param1~
ToolTip
-------
Affects ToolTip.
Pixel
-----
Affects |PixelGetColor|, |PixelSearch|, and |ImageSearch|.
Mouse
-----
Affects |MouseGetPos|, |Click|, and |MouseMove|/|Click|/|Drag|.
Caret
-----
Affects the built-in variables A_CaretX and A_CaretY.
Menu
-----
Affects the Menu Show command when coordinates are specified for it.
Param2
------
If Param2 is omitted, it defaults to Screen.
Screen
------
Coordinates are relative to the desktop (entire screen).
Relative
--------
Coordinates are relative to the active window.
Window [v1.1.05+]
-----------------
Synonymous with Relative and recommended for clarity.
Client [v1.1.05+]
-----------------
Coordinates are relative to the active window's client area, which
excludes the window's title bar, menu (if it has a standard one) and
borders. Client coordinates are less dependent on OS version and
theme.
Remarks~
If this command is not used, all commands except those documented
otherwise (e.g. WinMove and |InputBox|) use coordinates that are
relative to the active window
Every newly launched thread (such as a hotkey, custom menu item, or
timed subroutine) starts off fresh with the default setting for this
command. That default may be changed by using this command in the
auto-execute section (top part of the script).
Related~
|Click|, |MouseMove|, |MouseClick|, |MouseClickDrag|, |MouseGetPos|,
|PixelGetColor|, |PixelSearch|, |ToolTip|, |Menu|
Example~
>
CoordMode, ToolTip, Screen ; Place ToolTips at absolute screen coordinates:
CoordMode, ToolTip ; Same effect as the above because "screen" is the default.
<
==============================================================================
*AutoHotKey--Hotkeys_and_Hotstrings*
AutoHotKey Hotkeys and Hotstrings~
------------------------------------------------------------------------------
Hotkeys (Mouse, Joystick and Keyboard Shortcuts)
Table of Contents~
Introduction and Simple Examples
Table of Hotkey Prefix Symbols (Modifiers)
Context-sensitive Hotkeys
Custom Combinations and Other Features
Mouse Wheel Hotkeys
Hotkey Tips and Remarks
Introduction and Simple Examples~
Hotkeys are sometimes referred to as shortcut keys because of their
ability to easily trigger an action (such as launching a program or
keyboard macro). In the following example, the hotkey Win+N is
configured to launch Notepad. The pound sign [#] stands for the
Windows key, which is known as a modifier:
>
#n::
Run Notepad
return
<
In the final line above, return serves to finish the hotkey. However,
if a hotkey needs to execute only a single line, that line can be
listed to the right of the double-colon. In other words, the return is
implicit:
>
#n::Run Notepad
<
To use more than one modifier with a hotkey, list them consecutively
(the order does not matter). The following example uses ^!s to
indicate Control+Alt+S:
>
^!s::
Send Sincerely,{enter}John Smith
; This line sends keystrokes to the active (foremost) window.
return
<
You can use the following modifier symbols to define hotkeys:
Symbol Description~
# 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 usages of 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. 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:
>
<^>!m::MsgBox You pressed AltGr+m.
<^
LControl & RAlt::MsgBox You pressed AltGr itself
<
* 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:
>
~RButton::MsgBox You clicked the right mouse button.
~RButton & C::MsgBox You pressed C while holding down the right mouse button.
<
Notes: 1) Unlike the other prefix symbols, the tilde prefix is
allowed to be present on some of a hotkey's variants but absent on
others; 2) Special hotkeys that are substitutes for alt-tab always
ignore the tilde prefix; 3) The tilde prefix is ignored on Windows
95/98/ME
$ This is usually only necessary if the script uses the |Send|
command to send the keys that comprise the hotkey itself, which might
otherwise cause it to trigger itself. The $ prefix forces the keyboard
hook to be used to implement this hotkey, which as a side-effect
prevents the Send command from triggering it. The $ prefix is
equivalent to having specified #UseHook somewhere above the definition
of this hotkey.
[v1.1.06+]: #InputLevel and |SendLevel| provide additional
control over which hotkeys and hotstrings are triggered by the Send
command.
UP 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:
"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::)
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| and |#If| can be used to make a hotkey
perform a different action (or none at all) depending on a specific
condition. 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.
#If MouseIsOver("ahk_class Shell_TrayWnd")
WheelUp::Send {Volume_Up} ; Wheel over taskbar: increase/decrease volume.
WheelDown::Send {Volume_Down} ;
<
Custom Combinations and Other Features [Windows NT/2000/XP or later]~
You can define a custom combination of two keys (except joystick
buttons) by using " & " between them. In the below example, you would
hold down Numpad0 then press the second key to trigger the hotkey:
>
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
alt-tab 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.
Mouse Wheel Hotkeys [Windows NT/2000/XP or later]~
Hotkeys that fire upon turning the mouse wheel are supported via the
key names WheelDown and WheelUp. WheelLeft and WheelRight are also
supported in v1.0.48+, but have no effect on operating systems older
than Windows Vista. Here are some examples of mouse wheel hotkeys:
>
MButton & WheelDown::MsgBox You turned the mouse wheel down while holding down the middle button.
^!WheelUp::MsgBox You rotated the wheel up while holding down Control+Alt.
<
In v1.0.43.03+, the built-in variable A_EventInfo contains the amount
by which the wheel was turned, which is typically 1. However,
A_EventInfo can be greater or less than 1 under the following
circumstances:
If the mouse hardware reports distances of less than one notch,
A_EventInfo may contain 0;
If the wheel is being turned quickly (depending on type of mouse),
A_EventInfo may be greater than 1. A hotkey like the following can
help analyze your mouse: >
~WheelDown::ToolTip %A_EventInfo%
<
Some of the most useful hotkeys for the mouse wheel involve alternate
modes of scrolling a window's text. For example, the following pair of
hotkeys scrolls horizontally instead of vertically when you turn the
wheel while holding down the left Control key:
>
~LControl & WheelUp:: ; Scroll left.
ControlGetFocus, fcontrol, A
Loop 2 ; <-- Increase this value to scroll faster.
SendMessage, 0x114, 0, 0, %fcontrol%, A
; 0x114 is WM_HSCROLL and the 0 after it is SB_LINELEFT.
return
~LControl & WheelDown:: ; Scroll right.
ControlGetFocus, fcontrol, A
Loop 2 ; <-- Increase this value to scroll faster.
SendMessage, 0x114, 1, 0, %fcontrol%, A
; 0x114 is WM_HSCROLL and the 1 after it is SB_LINERIGHT.
return
<
Finally, since mouse wheel hotkeys generate only down-events (never
up-events), they cannot be used as key-up hotkeys.
Hotkey Tips and Remarks~
Each numpad key can be made to launch two different hotkey subroutines
depending on the state of Numlock. Alternatively, a numpad key can be
made to launch the same subroutine regardless of the Numlock state.
For example:
>
NumpadEnd::
Numpad1::
MsgBox, This hotkey is launched regardless of whether Numlock is on.
return
<
If the tilde (~) operator is used with a prefix key even once, that
prefix will always be sent through to the active window. For example,
in both of the below hotkeys, the active window will receive all
right-clicks even though only one of the definitions contains a tilde:
>
~RButton & LButton::MsgBox You pressed the left mouse button while holding down the right.
RButton & WheelUp::MsgBox You turned the mouse wheel up while holding down the right button.
<
The |Suspend| command can temporarily disable all hotkeys except for
ones you make exempt. For greater selectivity, use #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.
Custom Combinations and Other Features~
You can define a custom combination of two keys (except joystick
buttons) by using " & " between them. In the below example, you would
hold down Numpad0 then press the second key to trigger the hotkey:
>
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 custom combination 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. In
v1.1.14+, this behaviour can be avoided by applying the tilde prefix
to either hotkey.
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
alt-tab 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.
Mouse Wheel Hotkeys~
Hotkeys that fire upon turning the mouse wheel are supported via the
key names WheelDown and WheelUp. WheelLeft and WheelRight are also
supported in v1.0.48+, but have no effect on operating systems older
than Windows Vista. Here are some examples of mouse wheel hotkeys:
MButton & WheelDown::MsgBox You turned the mouse wheel down while
holding down the middle button. ^!WheelUp::MsgBox You rotated the
wheel up while holding down Control+Alt. | In v1.0.43.03+, the
built-in variable A_EventInfo contains the amount by which the wheel
was turned, which is typically 1. However, A_EventInfo can be greater
or less than 1 under the following circumstances:
•If the mouse hardware reports distances of less than one notch,
A_EventInfo may contain 0;
•If the wheel is being turned quickly (depending on type of mouse),
A_EventInfo may be greater than 1. A hotkey like the following can
help analyze your mouse: ~WheelDown::ToolTip %A_EventInfo%.
Some of the most useful hotkeys for the mouse wheel involve alternate
modes of scrolling a window's text. For example, the following pair of
hotkeys scrolls horizontally instead of vertically when you turn the
wheel while holding down the left Control key:
>
~LControl & WheelUp:: ; Scroll left.
ControlGetFocus, fcontrol, A
Loop 2 ; <-- Increase this value to scroll faster.
SendMessage, 0x114, 0, 0, %fcontrol%, A ; 0x114 is WM_HSCROLL and the 0 after it is SB_LINELEFT.
return
~LControl & WheelDown:: ; Scroll right.
ControlGetFocus, fcontrol, A
Loop 2 ; <-- Increase this value to scroll faster.
SendMessage, 0x114, 1, 0, %fcontrol%, A ; 0x114 is WM_HSCROLL and the 1 after it is SB_LINERIGHT.
return
Finally, since mouse wheel hotkeys generate only down-events (never
up-events), they cannot be used as key-up hotkeys.
Hotkey Tips and Remarks~
Each numpad key can be made to launch two different hotkey subroutines
depending on the state of Numlock. Alternatively, a numpad key can be
made to launch the same subroutine regardless of the Numlock state.
For example:
>
NumpadEnd::
Numpad1::
MsgBox, This hotkey is launched regardless of whether Numlock is on.
return
<
If the tilde (~) operator is used with a prefix key even once, it
changes the behavior of that prefix key for all combinations. For
example, in both of the below hotkeys, the active window will receive
all right-clicks even though only one of the definitions contains a
tilde:
>
~RButton & LButton::MsgBox You pressed the left mouse button while holding down the right.
RButton & WheelUp::MsgBox You turned the mouse wheel up while holding down the right button. | The Suspend command can temporarily disable all hotkeys except for ones you make exempt. For greater selectivity, use #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). They are not affected by #IfWin or #If.
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
<
==============================================================================
*MsgBox*
+---------+~
| MsgBox |~
+---------+~
Displays the specified text in a small window containing one or more
buttons (such as Yes and No).
|MsgBox|, Text
|MsgBox| [, Options, Title, Text, Timeout ]
Parameters~
Text
-----
If all the parameters are omitted, the |MsgBox| will display the text
"Press OK to continue." Otherwise, this parameter is the text
displayed inside the message box to instruct the user what to do, or
to present information.
Escape sequences can be used to denote special characters. For
example, `n indicates a linefeed character, which ends the current
line and begins a new one. Thus, using text1`n`ntext2 would create a
blank line between text1 and text2.
If Text is long, it can be broken up into several shorter lines by
means of a continuation section, which might improve readability and
maintainability.
Options
-------
Indicates the type of message box and the possible button
combinations. If blank or omitted, it defaults to 0. See the table
below for allowed values.
This parameter must be either a literal number or (in v1.1.06+) a
forced expression such as % Options. Any other non-blank value will
not be recognized as this parameter, but instead as part of Text in
the single-parameter mode.
Title
-----
The title of the message box window. If omitted or blank, it defaults
to the name of the script (without path).
Timeout
-------
(optional) Timeout in seconds, which can contain a decimal point but
is not an expression by default. In v1.1.06+, this can be a forced
expression such as % mins*60.
If this value exceeds 2147483 (24.8 days), it will be set to 2147483.
After the timeout has elapsed the message box will be automatically
closed and the |IfMsgBox| command will see the value TIMEOUT.
Known limitation: If the MsgBox contains only an OK button, |IfMsgBox|
will think that the OK button was pressed if the MsgBox times out
while its own |thread| is interrupted by another.
The Options parameter can be a combination (sum) of one or more of the
following values.
Function Decimal Hex ~
OK (that is, only an OK button is displayed) 0 0x0
OK/Cancel 1 0x1
Abort/Retry/Ignore 2 0x2
Yes/No/Cancel 3 0x3
Yes/No 4 0x4
Retry/Cancel 5 0x5
Cancel/Try Again/Continue (2000/XP+) 6 0x6
Adds a Help button (see remarks below) 16384 0x4000
Icon Hand (stop/error) 16 0x10
Icon Question 32 0x20
Icon Exclamation 48 0x30
Icon Asterisk (info) 64 0x40
Makes the 2nd button the default 256 0x100
Makes the 3rd button the default 512 0x200
System Modal (always on top) 4096 0x1000
Task Modal 8192 0x2000
Always-on-top (style WS_EX_TOPMOST) 262144 0x40000
(like System Modal but omits title bar icon)
Make the text right-justified 524288 0x80000
Right-to-left reading order for Hebrew/Arabic 1048576 0x100000
Remarks~
The table above is used by adding up the values you wish to be present
in the MsgBox. For example, to specify a Yes/No box with the default
button being No instead of Yes, the Options value would be 256+4
(260). In hex, it would be 0x100+0x4 (0x104).
MsgBox has smart comma handling, so it is usually not necessary to
escape commas in the Text parameter.
To determine which button the user pressed in the most recent MsgBox,
use the |IfMsgBox| command. For example:
>
MsgBox, 4,, Would you like to continue? (press Yes or No)
IfMsgBox Yes
MsgBox You pressed Yes.
else
MsgBox You pressed No.
<
The names of the buttons can be customized by following this example.
Tip~
-----
Pressing Control-C while a MsgBox window is active will copy its text
to the clipboard. This applies to all MsgBoxes, not just those
produced by AutoHotkey.
Using MsgBox with GUI windows~
A GUI window may display a modal MsgBox by means of Gui +OwnDialogs. A
modal MsgBox prevents the user from interacting with the GUI window
until the MsgBox is dismissed. In such a case, it is not necessary to
specify the System Modal or Task Modal options from the table above.
When Gui +OwnDialogs is not in effect, the Task Modal option (8192)
can be used to disable all the script's windows until the user
dismisses the MsgBox
The Help button~
When the Help button option (83) is present in Options, pressing the
Help button will have no effect unless both of the following are true:
1. The MsgBox is owned by a GUI window by means of Gui +OwnDialogs.
2. The script is monitoring the WM_HELP message (0x53). For example:
|OnMessage|(0x53, "WM_HELP"). When the WM_HELP() function is called, it may
guide the user by means such as showing another window or |MsgBox|.
The Close button (in |MsgBox|'s title bar )~
Since the MsgBox window is a built-in feature of the operating system,
its X button is enabled only when certain buttons are present. If
there is only an OK button, clicking the X button is the same as
pressing OK. Otherwise, the X button is disabled unless there is a
Cancel button, in which case clicking the X is the same as pressing
Cancel.
Related~
IfMsgBox, |InputBox|, FileSelectFile, FileSelectFolder, ToolTip, GUI
Example~
>
MsgBox This is the 1-parameter method. Commas (,) do not need to be escaped.
MsgBox, 4, , This is the 3-parameter method. Commas (,) do not need to be escaped.
MsgBox, 4, , Do you want to continue? (Press YES or NO)
IfMsgBox No
return
MsgBox, 4, , 4-parameter method: this MsgBox will time out in 5 seconds. Continue?, 5
IfMsgBox Timeout
MsgBox You didn't press YES or NO within the 5-second period.
else IfMsgBox No
return
; By preceding any parameter with "% ", it becomes an
; expression. In the following example, math is performed, an
; array element is accessed, and a function is called. All of
; these items are concatenated via the "." operator to form a
; single string displayed by MsgBox:
MsgBox % "New width for object #" . A_Index . " is: " . RestrictWidth(ObjectWidth%A_Index% * ScalingFactor)
; The following example alerts the user that a MsgBox is going
; to steal focus (in case the user is typing).
SplashTextOn,,, A MsgBox is about to appear.
Sleep 3000
SplashTextOff
MsgBox The backup process has completed.
<
==============================================================================
*Key_List---List_of_Keys__Mouse_Buttons__and_Joystick_Controls*
*list_of_hotkeys_for_reference*
Key List~
------------------------------------------------------------------------------
List of Keys, Mouse Buttons and Joystick Controls~
Mouse~
-----
General~
LButton Left mouse button
RButton Right mouse button
MButton Middle or wheel mouse button
Advanced~
XButton1 4th mouse button. Typically performs the same function as
Browser_Back
XButton2 5th mouse button. Typically performs the same function as
Browser_Forward
Wheel
WheelDown Turn the wheel downward (toward you).
WheelUp Turn the wheel upward (away from you).
WheelLeft
WheelRight Requires Windows Vista or later. These can be used as hotkeys
with some (but not all) mice which have a second wheel or
support tilting the wheel to either side. In some cases,
software bundled with the mouse must instead be used to
control this feature. Regardless of the particular mouse,
Send and Click can be used to scroll horizontally in programs
which support it.
*keyboard_names_list*
Keyboard~
--------
Note: The names of the letter and number keys are the same as that
single letter or digit. For example: b is the "b" key and 5 is the "5"
key.
General~
CapsLock Caps lock
Space Space bar
Tab Tab key
Enter Enter key
(or Return)
Escape Esc key
(or Esc)
Backspace Backspace
(or BS )
Cursor Control
ScrollLock Scroll lock
Delete Delete key
(or Del )
Insert
(or Ins ) Insert key
Home Home key
End End key
PgUp Page Up key
PgDn Page Down key
Up Up arrow key
Down Down arrow key
Left Left arrow key
Right Right arrow key
Numpad
Numpad0 NumpadIns 0 / Insert key
Numpad1 NumpadEnd 1 / End key
Numpad2 NumpadDown 2 / Down arrow key
Numpad3 NumpadPgDn 3 / Page Down key
Numpad4 NumpadLeft 4 / Left arrow key
Numpad5 NumpadClear 5 / typically does nothing
Numpad6 NumpadRight 6 / Right arrow key
Numpad7 NumpadHome 7 / Home key
Numpad8 NumpadUp 8 / Up arrow key
Numpad9 NumpadPgUp 9 / Page Up key
NumpadDot NumpadDel Decimal separation / Delete key
NumpadDiv NumpadDiv Divide
NumpadMul NumpadMul Multiply
NumpadAdd NumpadAdd Add
NumpadSub NumpadSub Subtract
NumpadEnter NumpadEnter Enter key
Function
F1 - F24 The 12 or more function keys at the top of most
keyboards.
Modifier
LWin Left Windows logo key. Corresponds to the <# hotkey
prefix.
RWin Right Windows logo key. Corresponds to the ># hotkey
prefix. Note: Unlike Control/Alt/Shift, there is no
generic/neutral "Win" key because the OS does not
support it. However, hotkeys with the # modifier can
be triggered by either Win key.
Control
(or Ctrl) Control key. As a hotkey (Control::) it fires upon
release unless it has the tilde prefix. Corresponds to
the ^ hotkey prefix.
Alt Alt key. As a hotkey (Alt::) it fires upon release
unless it has the tilde prefix. Corresponds to the !
hotkey prefix.
Shift Shift key. As a hotkey (Shift::) it fires upon release
unless it has the tilde prefix. Corresponds to the +
hotkey prefix.
LControl
(or LCtrl) Left Control key. Corresponds to the <^ hotkey
prefix.
RControl
(or RCtrl) Right Control key. Corresponds to the >^ hotkey
prefix.
LShift Left Shift key. Corresponds to the <+ hotkey prefix.
RShift Right Shift key. Corresponds to the >+ hotkey
prefix.
LAlt Left Alt key. Corresponds to the ! hotkey prefix.
Note: If your keyboard layout has AltGr instead of
RAlt, you can probably use it as a hotkey prefix via
<^>! as described here. In addition, LControl & RAlt::
would make AltGr itself into a hotkey.
Multimedia~
Browser_Back Back
Browser_Forward Forward
Browser_Refresh Refresh
Browser_Stop Stop
Browser_Search Search
Browser_Favorites Favorites
Browser_Home Homepage
Volume_Mute Mute the volume
Volume_Down Lower the volume
Volume_Up Increase the volume
Media_Next Next Track
Media_Prev Previous Track
Media_Stop Stop
Media_Play_Pause Play/Pause
Launch_Mail Launch default e-mail program
Launch_Media Launch default media player
Launch_App1 Launch My Computer
Launch_App2 Launch Calculator
Note: The function assigned to each of the keys listed above can be
overridden by modifying the Windows registry. This table shows the
default function of each key on most versions of Windows.
Special~
AppsKey Menu key. This is the key that invokes the
right-click context menu.
PrintScreen Print screen
CtrlBreak
Pause Pause key
Break Break key. Since this is synonymous with
Pause, use ^CtrlBreak in hotkeys instead of
^Pause or ^Break.
Help Help key. This probably doesn't exist on
most keyboards. It's usually not the same as F1.
Sleep Sleep key. Note that the sleep key on some
keyboards might not work with this.
SCnnn Specify for nnn the scan code of a key.
Recognizes unusual keys not mentioned above.
See Special Keys for details.
VKnn Specify for nn the hexadecimal virtual key
code of a key. This rarely-used method also
prevents certain types of hotkeys from
requiring the keyboard hook. For example, the
following hotkey does not use the keyboard
hook, but as a side-effect it is
triggered by pressing either Home or NumpadHome:
>
^VK24::MsgBox You pressed Home or NumpadHome while holding down Control.
<
Known limitation: VK hotkeys that are forced
to use the keyboard hook, such as VK24 or
~VK24, will fire for only one of the keys, not
both (e.g. NumpadHome but not Home). For more
information about the VKnn method, see Special
Keys.
*joystick_buttons_names_list*
Joystick~
Joy1 through Joy32
------------------
The buttons of the joystick. To help determine the button numbers for
your joystick, use this test script. Note that hotkey prefix symbols
such as ^ (control) and + (shift) are not supported (though
GetKeyState can be used as a substitute). Also note that the pressing
of joystick buttons always "passes through" to the active window if
that window is designed to detect the pressing of joystick buttons.
Although the following Joystick control names cannot be used as
hotkeys, they can be used with GetKeyState : JoyX , JoyY , and JoyZ :
The X (horizontal), Y (vertical), and Z (altitude/depth) axes of the
joystick.
JoyR
-----
The rudder or 4th axis of the joystick.
JoyU and JoyV
-------------
The 5th and 6th axes of the joystick.
JoyPOV
------
The point-of-view (hat) control.
JoyName
-------
The name of the joystick or its driver.
JoyButtons
----------
The number of buttons supported by the joystick (not always accurate).
JoyAxes
-------
The number of axes supported by the joystick.
JoyInfo
-------
Provides a string consisting of zero or more of the following letters
to indicate the joystick's capabilities: Z (has Z axis), R (has R
axis), U (has U axis), V (has V axis), P (has POV control), D
(the POV control has a limited number of discrete/distinct settings),
C (the POV control is continous/fine). Example string: ZRUVPD
Multiple Joysticks
------------------
If the computer has more than one joystick and you want to use one
beyond the first, include the joystick number (max 16) in front of the
control name. For example, 2joy1 is the second joystick's first
button.
Note: If you have trouble getting a script to recognize your joystick,
one person reported needing to specify a joystick number other than 1
even though only a single joystick was present. It is unclear how this
situation arises or whether it is normal, but experimenting with the
joystick number in the joystick test script can help determine if this
applies to your system.
See Also:~
Joystick remapping
methods of sending keystrokes and mouse clicks with a joystick.
Joystick-To-Mouse
script: using a joystick as a mouse.
Hand-held Remote Controls~
Respond to signals from hand-held remote controls via the WinLIRC
client script.
Special Keys~
If your keyboard or mouse has a key not listed above, you might still
be able to make it a hotkey by using the following steps:
1. Ensure that at least one script is running that is using the
keyboard hook. You can tell if a script has the keyboard hook by
opening its main window and selecting "View->Key history" from the
menu bar.
2. Double-click that script's tray icon to open its main window.
3. Press one of the "mystery keys" on your keyboard.
4. Select the menu item "View->Key history"
5. Scroll down to the bottom of the page. Somewhere near the bottom
are the key-down and key-up events for your key. NOTE: Some keys do
not generate events and thus will not be visible here. If this is the
case, you cannot directly make that particular key a hotkey because
your keyboard driver or hardware handles it at a level too low for
AutoHotkey to access. For possible solutions, see further below.
6. If your key is detectible, make a note of the 3-digit hexadecimal
value in the second column of the list (e.g. 159 ).
To define this key as a hotkey, follow this example:
>
SC159:: ; Replace 159 with your key's value.
MsgBox, %A_ThisHotKey% was pressed.
return
<
Reverse direction
-----------------
To remap some other key to become a "mystery key", follow this
example:
>
; Replace 159 with the value discovered above. Replace FF (if needed) with the
; key's virtual key, which can be discovered in the first
; column of the Key History screen.
#c::Send {vkFFsc159}
<
Alternate solutions
-------------------
If your key or mouse button is not detectible by the Key History
screen, one of the following might help:
1. Reconfigure the software that came with your mouse or keyboard
(sometimes accessible in the Control Panel or Start Menu) to have the
"mystery key" send some other keystroke. Such a keystroke can then be
defined as a hotkey in a script. For example, if you configure a
mystery key to send Control+F1, you can then indirectly make that key
as a hotkey by using ^F1:: in a script.
2. Try DllCall: Support for Human Interface Devices . You
can also try searching the forum for a keyword like RawInput*.
3. The following is a last resort and generally should be attempted
only in desperation. This is because the chance of success is low and
it may cause unwanted side-effects that are difficult to undo:
Disable or remove any extra software that came with your keyboard or
mouse or change its driver to a more standard one such as the one
built into the OS. This assumes there is such a driver for your
particular keyboard or mouse and that you can live without the
features provided by its custom driver and software.
==============================================================================
*GetKeyState*
+-------------+~
| GetKeyState |~
+-------------+~
Checks if a keyboard key or mouse/joystick button is down or up. Also
retrieves joystick status.
|GetKeyState|, OutputVar , KeyName [, Mode ]
KeyIsDown := |GetKeyState|("KeyName" [, "Mode"])
Note
If a joystick is not plugged in the variable is set to empty string
- "". Hence this routine checks if the joystick is in plugged in:
>
GetKeyState, joyy, JoyY
if (JoyZ = "")
{
MsgBox, 4, Hello, Joystick not plugged in!
}
<
Parameters~
OutputVar
---------
The name of the variable in which to store the retrieved key state,
which is either D for down or U for up (but the |GetKeyState|()
function returns true (1) for down and false (0) for up). The variable
will be empty (blank) if the state of the key could not be determined.
The items below apply only to joysticks:
1) For a joystick axis such as JoyX, OutputVar will be set to a
floating point number between 0 and 100 to indicate the joystick's
position as a percentage of that axis's range of motion. The format of
the number can be changed via |SetFormat|. This test script can be used
to analyze your joystick(s).
2) When KeyName is JoyPOV, the retrieved value will be between 0 and
35900. The following approximate POV values are used by many
joysticks:
-1: no angle to report
0: forward POV
9000 (i.e. 90 degrees): right POV
27000 (i.e. 270 degrees): left POV
18000 (i.e. 180 degrees): backward POV
KeyName
-------
This can be just about any single character from the keyboard or one
of the key names from the key list , such as a mouse/joystick button
(though mouse button state usually cannot be detected on Windows
95/98/Me). Examples: B, 5, LWin, RControl, Alt, Enter, Escape,
LButton, MButton, Joy1.
Alternatively, an explicit virtual key code such as vkFF may be
specified. This is useful in the rare case where a key has no name.
The virtual key code of such a key can be determined by following the
steps at the bottom of the key list page.
Known limitation : This function cannot differentiate between two keys
which share the same virtual key code, such as Left and NumpadLeft.
Mode
-----
This parameter is ignored when retrieving joystick status.
If omitted, the mode will default to that which retrieves the logical
state of the key. This is the state that the OS and the active window
believe the key to be in, but is not necessarily the same as the
physical state.
Alternatively, one of these letters may be specified:
P
-----
Retrieve the physical state (i.e. whether the user is physically
holding it down). Under Windows Me/98/95, the physical state (Mode =
P) of a key is likely always the same as its logical state. Under
Windows NT/2000/XP or later, the physical state of a key or mouse
button will usually be the same as the logical state unless the
keyboard and/or mouse hooks are installed, in which case it will
accurately reflect whether or not the user is physically holding down
the key or button (as long as it was pressed down while the script was
running). You can determine if your script is using the hooks via the
KeyHistory command or menu item. You can force the hooks to be
installed by adding the |#InstallKeybdHook| and/or |#InstallMouseHook|
directives to the script.
T
-----
Retrieve the toggle state (only valid for keys that can be toggled
such as Capslock, Numlock, Scrolllock, and Insert). A retrieved value
of D means the key is "on", while U means it's "off" (but the
|GetKeyState|() function returns true (1) for "on" and false
(0) for "off").
Retrieving the toggle state of the Insert key might work only on
Windows 2000/XP or later.
On Windows 9x, retrieving the toggle state might be less reliable. For
example, immediately after the key is pressed, its new state might not
be retrieved correctly until after the display of a window that's
associated with the script, such as a |MsgBox|.
Remarks~
To wait for a key or mouse/joystick button to achieve a new state, it
is usually easier to use |KeyWait| instead of a |GetKeyState| loop.
Systems with unusual keyboard drivers might be slow to update the
state of their keys, especially the toggle-state of keys like
Capslock. A script that checks the state of such a key immediately
after it changed may use |Sleep| beforehand to give the system time to
update the key state.
For examples of using GetKeyState with a joystick, see the joystick
remapping page and the Joystick-To-Mouse script.
Related~
|GetKeyState|(), |KeyWait|, Key List , Joystick remapping,
KeyHistory, |#InstallKeybdHook|, |#InstallMouseHook|
Examples~
>
; Basic examples:
GetKeyState, state, RButton ; Right mouse button.
GetKeyState, state, Joy2 ; The second button of the first joystick.
GetKeyState, state, Shift
if state = D
MsgBox At least one Shift key is down.
else
MsgBox Neither Shift key is down.
GetKeyState, state, CapsLock, T ; D if CapsLock is ON or U otherwise.
state := GetKeyState("Capslock", "T") ; True if CapsLock is ON, false otherwise.
; Remapping example (this is only for illustration because it
; would be easier to use the built-in remapping feature): In
; the following hotkey, the mouse button is kept held down
; while NumpadAdd is down, which effectively transforms
; NumpadAdd into a mouse button. This method can also be
; used to repeat an action while the user is holding down a
; key or button:
*NumpadAdd::
MouseClick, left,,, 1, 0, D ; Hold down the left mouse button.
Loop
{
Sleep, 10
GetKeyState, state, NumpadAdd, P
if state = U ; The key has been released, so break out of the loop.
break
; ... insert here any other actions you want repeated.
}
MouseClick, left,,, 1, 0, U ; Release the mouse button.
return
; Example: Make joystick button behavior depend on joystick
; axis position.
joy2::
GetKeyState, joyx, JoyX
if joyx > 75
MsgBox Action #1 (button pressed while joystick was pushed to the right).
else if joyx < 25
MsgBox Action #2 (button pressed while joystick was pushed to the left).
else
MsgBox Action #3 (button pressed while joystick was centered horizontally).
return
; See the joystick remapping page and the Joystick-To-Mouse
; script for other examples.
<
==============================================================================
*loop_construct*
Loop Construct~
------------------------------------------------------------------------------
Perform a series of commands repeatedly: either the specified number
of times or until break is encountered.
|Loop| [, Count ]
Parameters~
Count
-----
How many times (iterations) to perform the loop. If omitted, the Loop
continues indefinitely until a break or return is encountered.
If Count is a variable reference such as %ItemCount%, the loop is
skipped entirely whenever the variable is blank or contains a number
less than 1.
Due to the need to support file-pattern loops, Count cannot be an
expression. However, as with all non-expression parameters, an
expression can be forcibly used by preceding it with a % and a space.
For example: Loop % Count + 1. In such cases, the expression is
evaluated only once, right before the loop begins.
Remarks~
The loop command is usually followed by a block, which is a collection of
statements that form the body of the loop. However, a loop with only a single
statement does not require a block (an "if" and its "else" count as a single
statement for this purpose).
A common use of this command is an infinite loop that uses the break
command somewhere in the loop's body to determine when to stop the
loop.
The use of break and continue inside a loop are encouraged as
alternatives to goto, since they generally make a script more
understandable and maintainable. To create a "Do...While" loop, make
the last statement of the loop's body an IF statement that
conditionally issues the break command. The same technique can be used
to create a "While" loop, but the While command should be used
instead.
The built-in variable A_Index contains the number of the current
loop iteration. It contains 1 the first time the loop's body is
executed. For the second time, it contains 2; and so on. If an inner
loop is enclosed by an outer loop, the inner loop takes precedence.
A_Index works inside all types of loops, including file-loops and
registry-loops ; but A_Index contains 0 outside of a loop.
The One True Brace (OTB) style may optionally be used with normal
loops (but not specialized loops such as file-pattern and parsing).
For example:
>
Loop {
...
}
Loop %RepeatCount% {
...
}
<
Specialized loops: Loops can be used to automatically retrieve files,
folders, or registry items (one at a time). See file-loop and
registry-loop for details. In addition, file-reading loops can operate
on the entire contents of a file, one line at a time. Finally, parsing
loops can operate on the individual fields contained inside a
delimited string.
Related~
Until, While-loop, For-loop, Files-and-folders loop, Registry loop,
File-reading loop, Parsing loop, Break, Continue, Blocks
Examples~
>
Loop, 3
{
MsgBox, Iteration number is %A_Index%. ; A_Index will be 1, 2, then 3
Sleep, 100
}
Loop
{
if a_index > 25
break ; Terminate the loop
if a_index < 20
continue ; Skip the below and start a new iteration
MsgBox, a_index = %a_index% ; This will display only the numbers 20 through 25
}
<
*While_Construct*
While Construct~
------------------------------------------------------------------------------
Performs a series of commands repeatedly until the specified
expression evaluates to false.
>
While Expression
<
Parameters~
Expression Any valid expression. For example: >
while x < y
<
Remarks~
The expression is evaluated once before each iteration. If the
expression evaluates to true (which is any result other than an empty
string or the number 0), the body of the loop is executed; otherwise,
execution jumps to the line following the loop's body.
A while-loop is usually followed by a block, which is a collection of
statements that form the body of the loop. However, a loop with only a
single statement does not require a block (an "if" and its "else"
count as a single statement for this purpose).
The One True Brace (OTB) style may optionally be used, which allows
the open-brace to appear on the same line rather than underneath. For
example: >
while x < y {
<
The built-in variable A_Index contains the number of the current loop
iteration. It contains 1 the first time the loop's expression and body
are executed. For the second time, it contains 2; and so on. If an
inner loop is enclosed by an outer loop, the inner loop takes
precedence. A_Index works inside all types of loops, but contains 0
outside of a loop.
As with all loops, Break may be used to exit the loop prematurely.
Also, Continue may be used to skip the rest of the current
iteration, at which time A_Index is increased by 1 and the
while-loop's expression is re-evaluated. If it is still true, a new
iteration begins; otherwise, the loop ends.
Specialized loops: Loops can be used to automatically retrieve files,
folders, or registry items (one at a time). See file-loop and
registry-loop for details. In addition, file-reading loops can operate
on the entire contents of a file, one line at a time. Finally, parsing
loops can operate on the individual fields contained inside a
delimited string.
Related~
Until, Break, Continue, Blocks, Loop, For-loop, Files-and-folders loop,
Registry loop, File-reading loop, Parsing loop, If ( expression )
Examples~
>
; As the user drags the left mouse button, a ToolTip displays
; the size of the region inside the drag-area.
CoordMode, Mouse, Screen
~LButton::
MouseGetPos, begin_x, begin_y
while GetKeyState("LButton")
{
MouseGetPos, x, y
ToolTip, % begin_x ", " begin_y "`n" Abs(begin_x-x) " x " Abs(begin_y-y)
Sleep, 10
}
ToolTip
return
<
==============================================================================
*Sleep*
+-------+~
| Sleep |~
+-------+~
Waits the specified amount of time before continuing.
|Sleep|, DelayInMilliseconds
Parameters~
Delay
-----
The amount of time to pause (in milliseconds) between 0 and 2147483647
(24 days), which can be an expression
Remarks~
Due to the granularity of the OS's time-keeping system, Delay is
typically rounded up to the nearest multiple of 10 or 15.6
milliseconds (depending on the type of hardware and drivers
installed). For example, a delay between 1 and 10 (inclusive) is
equivalent to 10 or 15.6 on most Windows NT/2000/XP systems. To
achieve a shorter delay, see Examples.
The actual delay time might wind up being longer than what was
requested if the CPU is under load. This is because the OS gives each
needy process a slice of CPU time (typically 20 milliseconds) before
giving another timeslice to the script.
A delay of 0 yields the remainder of the script's current timeslice to
any other processes that need it (as long as they are not
significantly lower in priority than the script). Thus, a delay of 0
produces an actual delay between 0 and 20ms (or more), depending on
the number of needy processes (if there are no needy processes, there
will be no delay at all). However, a Delay of 0 should always wind up
being shorter than any longer Delay would have been.
While sleeping, new threads can be launched via hotkey, custom menu
item, or timer.
Sleep -1: A delay of -1 does not sleep but instead makes the script
immediately check its message queue. This can be used to force any
pending interruptions to occur at a specific place rather than
somewhere more random. See Critical for more details.
Related~
SetKeyDelay, SetMouseDelay, SetControlDelay, SetWinDelay, SetBatchLines
Examples~
>
Sleep, 1000 ; 1 second
; The following is a working example that demonstrates how to
; sleep for less time than the ; normal 10 or 15.6 milliseconds.
; NOTE: While a script like this is running, the entire
; operating system and all applications are ; affected by
; timeBeginPeriod below.
SetBatchLines -1
; Ensures maximum effectiveness of this method.
SleepDuration = 1
; This can sometimes be finely adjusted (e.g. 2 is different
; than 3) depending on the value below.
TimePeriod = 3 ; Try 7 or 3. See comment below.
; On a PC whose sleep duration normally rounds up to 15.6 ms,
; try TimePeriod=7 to allow ; somewhat shorter sleeps, and try
; TimePeriod=3 or less to allow the shortest possible sleeps.
DllCall("Winmm\timeBeginPeriod", uint, TimePeriod)
; Affects all applications, not just this script's
; DllCall("Sleep"...), but does not affect SetTimer.
Iterations = 50
StartTime := A_TickCount
Loop %Iterations%
DllCall("Sleep", UInt, SleepDuration)
; Must use DllCall instead of the Sleep command.
DllCall("Winmm\timeEndPeriod", UInt, TimePeriod)
; Should be called to restore system to normal.
MsgBox % "Sleep duration = " . (A_TickCount - StartTime) / Iterations
<
==============================================================================
*the_brace_block_construct*
The Brace (block)~
------------------------------------------------------------------------------
A pair of braces denotes a block. Blocks are typically used with
functions, Else, Loop, While-loop, and IF-commands
{
zero or more commands
}
Remarks~
A block is used to bind two or more commands together. It can also be
used to change which IF an ELSE belongs to, as in this example where
the block forces the ELSE to belong to the first IF rather than the
second:
>
if var1 = 1
{
if var2 = abc
sleep, 1
}
else
return
<
Although blocks can be used anywhere, currently they are only
meaningful when used with functions, Else, Loop, or an IF-type command
such as IfEqual or IfWinExist.
If an IF, ELSE, Loop, While-loop, or For-loop has only a single
command, that command need not be enclosed in a block. However, there
may be cases where doing so enhances the readability or
maintainability of the script.
A block may be empty (contain zero commands), which may be useful in
cases where you want to comment out the contents of the block without
removing the block itself.
One True Brace (OTB, K&R style): The OTB style may optionally be used
in the following places: expression if-statements, the else keyword,
while-loops, For-loops, normal loops, function definitions, Try, and
Catch. This style puts the block's opening brace on the same line as
the block's controlling statement rather than underneath on a line by
itself. For example:
>
if (x < y) {
...
} else {
...
}
While x < y {
...
}
For k,v in obj {
...
}
Loop %RepeatCount% {
...
}
MyFunction(x, y) {
...
}
Try {
...
} Catch e {
...
}
<
Similarly, a command or other action may exist to the right of a brace
(except the open-brace of the One True Brace style). For example:
>
if x = 1
{ MsgBox This line appears to the right of an opening brace. It executes whenever the IF-statement is true.
MsgBox This is the next line.
} MsgBox This line appears to the right of a closing brace. It executes unconditionally.
<
Related~
Functions, While-loop, Loop, Else, If, If(Expression)
Example~
>
if x = 1
{
MsgBox, test1
Sleep, 5
}
else
MsgBox, test2
<
==============================================================================
*If* *IfEqual* *IfNotEqual* *IfLess* *IfLessOrEqual* *IfGreater* *IfGreaterOrEqual*
If IfEqual IfNotEqual IfLess IfLessOrEqual IfGreater IfGreaterOrEqual~
------------------------------------------------------------------------------
Specifies the command(s) to perform if the comparison of a variable to
a value evalutes to TRUE. When more than one command is present,
enclose them in a block (braces).
|IfEqual|, var, value (same: if var = value)
|IfNotEqual|, var, value (same: if var <> value) (!= can be used in
place of <>) |IfGreater|, var, value (same: if var > value)
|IfGreaterOrEqual|, var, value (same: if var >= value)
|IfLess|, var, value (same: if var < value)
|IfLessOrEqual|, var, value (same: if var <= value)
|If| var ; If var's contents are blank or 0, it is considered false.
Otherwise, it is true.
See also: IfInString
Parameters~
var
-----
The variable name.
value
------
A literal string, number, or variable reference (e.g. %var2%). Value
can be omitted if you wish to compare %var to an empty string (blank).
Remarks~
If both var and value are purely numeric, they will be compared as
numbers rather than as strings. Otherwise, they will be compared
alphabetically as strings (that is, alphabetical order will determine
whether var is greater, equal, or less than value).
When an IF or an ELSE owns more than one line, those lines must be
enclosed in braces. For example:
>
if count <= 0
{
WinClose Untitled - Notepad
MsgBox There are no items present.
}
<
However, if only one line belongs to the IF or ELSE, the braces are
optional.
Another command can only appear on the same line as the IF statement
if you use the command-name style. In other words, these are valid:
>
IfEqual, x, 1, Sleep, 1
IfGreater, x, 1, EnvAdd, x, 2
<
But these are not valid:
>
if x = 1 Sleep 1
IfGreater, x, 1, x += 2
<
The One True Brace (OTB) style may not be used with these types of
if-statements. It can only be used with expression if-statements.
On a related note, the command if var [not] between LowerBound and
UpperBound checks whether a variable is between two values, and if var
[not] in value1,value2 can be used to check whether a variable's
contents exist within a list of values.
Related~
IF (expression), StringCaseSense, Assign expression (:=), if var
in/contains MatchList, if var between, IfInString, Blocks, Else
Example~
>
if counter >= 1
Sleep, 10
if counter >=1 ; If an IF has more than one line, enclose those lines in braces:
{
WinClose, Untitled - Notepad
Sleep 10
}
if MyVar = %MyVar2%
MsgBox The contents of MyVar and MyVar2 are identical.
else if MyVar =
{
MsgBox, 4,, MyVar is empty/blank. Continue?
IfMsgBox, No
Return
}
else if MyVar <> ,
MsgBox The value in MyVar is not a comma.
else
MsgBox The value in MyVar is a comma.
if Done
MsgBox The variable Done is neither empty nor zero
<
==============================================================================
*if_expression*
if (expression)~
------------------------------------------------------------------------------
Specifies the command(s) to perform if an expression evaluates to TRUE
if (expression)
Remarks~
An if-statement that contains an expression is differentiated from a
traditional-if 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 "!".
If the if-statement's expression evaluates to true (which is any
result other than an empty string or the number 0), the line or block
underneath it is executed. Otherwise, if there is a corresponding
ELSE, execution jumps to the line or block underneath it.
When an IF or an ELSE owns more than one line, those lines must be
enclosed in braces. However, if only one line belongs to an IF or
ELSE, the braces are optional. See the examples at the bottom of this
page.
The One True Brace (OTB) style may optionally be used with
if-statements that are expressions (but not traditional
if-statements). For example:
>
if (x < y) {
...
}
if WinExist("Untitled - Notepad") {
WinActivate
}
if IsDone {
...
} else {
...
}
<
Unlike an "else" statement -- which supports any type of statement
immediately to its right -- an if-statement supports only a "{" to its
right.
On a related note, the command if var [not] between LowerBound and
UpperBound checks whether a variable is between two values, and if var
[not] in value1,value2 can be used to check whether a variable's
contents exist within a list of values.
Related~
Expressions, Assign expression (:=), if var in/contains MatchList, if
var between, IfInString, Blocks, Else, While-loop
Example~
>
if (A_Index > 100 or Done)
return
if (A_TickCount - StartTime > 2*MaxTime + 100)
{
MsgBox Too much time has passed.
ExitApp
}
if (Color = "Blue" or Color = "White")
{
MsgBox The color is one of the allowed values.
ExitApp
}
else if (Color = "Silver")
{
MsgBox Silver is not an allowed color.
return
}
else
{
MsgBox This color is not recognized.
ExitApp
}
<
==============================================================================
*WinGetPos*
+-----------+~
| WinGetPos |~
+-----------+~
Retrieves the position and size of the specified window.
|WinGetPos| [, X, Y, Width, Height, WinTitle, WinText, ExcludeTitle ,
ExcludeText ]
Parameters~
X , Y
-----
The names of the variables in which to store the X and Y coordinates
of the target window's upper left corner. If omitted, the
corresponding values will not be stored.
Width / Height
--------------
The names of the variables in which to store the width and height of
the target window. If omitted, the corresponding values will not be
stored.
WinTitle
--------
A window title or other criteria identifying the target window. See
WinTitle.
WinText
-------
If present, this parameter must be a substring from a single text
element of the target window (as revealed by the included Window Spy
utility). Hidden text elements are detected if DetectHiddenText is
ON.
ExcludeTitle
------------
Windows whose titles include this value will not be considered
ExcludeText
-----------
Windows whose text include this value will not be considered.
Remarks~
If no matching window is found, the output variables will be made
blank.
If the WinTitle "Program Manager" is used, the command will retrieve
the size of the desktop, which is usually the same as the current
screen resolution.
A minimized window will still have a position and size. The values
returned in this case may vary depending on OS and configuration.
To discover the name of the window and control that the mouse is
currently hovering over, use MouseGetPos.
Window titles and text are case sensitive. Hidden windows are not
detected unless DetectHiddenWindows has been turned on.
Related~
|WinMove|, |ControlGetPos|, |WinGetActiveStats|, |WinGetActiveTitle|,
|WinGetTitle|, |WinGetText|, |ControlGetText|
Example~
>
WinGetPos, X, Y, Width, Height, Calculator
MsgBox, Calculator is at %X%`,%Y%
WinGetPos, X, Y, , , A ; "A" to get the active window's pos.
MsgBox, The active window is at %X%`,%Y%
IfWinExist, Untitled - Notepad
{
WinGetPos, Xpos, Ypos ; Uses the window found above.
MsgBox, Notepad is at %Xpos%`,%Ypos%
}
<
==============================================================================
*MouseMove*
+-----------+~
| MouseMove |~
+-----------+~
Moves the mouse cursor
|MouseMove|, X, Y [, Speed, R ]
Parameters~
X , Y
-----
The x/y coordinates to move the mouse to, which can be expressions.
Coordinates are relative to the active window unless CoordMode was
used to change that.
Speed
-----
The speed to move the mouse in the range 0 (fastest) to 100 (slowest),
which can be an expression. Note: a speed of 0 will move the mouse
instantly. If omitted, the default speed (as set by
|SetDefaultMouseSpeed| or 2 otherwise) will be used.
Speed is ignored for |SendInput| / Play modes ; they move the mouse
instantaneously (though |SetMouseDelay| has a mode that applies to
SendPlay). To visually move the mouse more slowly -- such as a script
that performs a demonstration for an audience -- use
>
SendEvent {Click 100, 200}
<
or
>
SendMode Event
<
(optionally in conjuction with |BlockInput|).
R
-----
If this parameter is the letter R, the X and Y coordinates will be
treated as offsets from the current mouse position. In other words,
the cursor will be moved from its current position by X pixels to the
right (left if negative) and Y pixels down (up if negative).
Remarks~
This command uses the sending method set by |SendMode|.
The |SendPlay| mode is able to successfully generate mouse events in a
broader variety of games than the other modes. In addition, some
applications and games may have trouble tracking the mouse if it moves
too quickly. The speed parameter or |SetDefaultMouseSpeed| can be used
to reduce the speed (in the default |SendEvent| mode only).
The |BlockInput| command can be used to prevent any physical mouse
activity by the user from disrupting the simulated mouse events
produced by the mouse commands. However, this is generally not needed
for the |SendInput|/ |Play| modes because they automatically postpone
the user's physical mouse activity until afterward.
There is an automatic delay after every movement of the mouse (except
for |SendInput| mode). Use |SetMouseDelay| to change the length of the
delay.
The following is an alternate way to move the mouse cursor that may
work better in certain multi-monitor configurations:
>
DllCall("SetCursorPos", int, 100, int, 400)
; The first number is the X-coordinate
; and the second is the Y (relative to the screen).
<
On a related note, the mouse cursor can be temporarily hidden via the
hide-cursor example.
Related~
|CoordMode|, |SendMode|, |SetDefaultMouseSpeed|, |SetMouseDelay|,
|Click|, |MouseClick|, |MouseClickDrag|, |MouseGetPos|, |BlockInput|
Example~
>
; Move the mouse to a new position:
MouseMove, 200, 100
; Move the mouse slowly (speed 50 vs. 2) by 20 pixels to the right and 30 pixels down
; from its current location:
MouseMove, 20, 30, 50, R
<
==============================================================================
*IfWinExist* *IfWinNotExist* *WinExist*
+---------------------------------------+~
| IfWinExist - IfWinNotExist - WinExist |~
+---------------------------------------+~
Checks if a matching window exists. |WinExist|() returns the Unique ID
(HWND) of the first matching window
|IfWinExist| [, WinTitle, WinText, ExcludeTitle, ExcludeText ]
|IfWinNotExist| [, WinTitle, WinText, ExcludeTitle, ExcludeText ]
UniqueID := |WinExist| ( "WinTitle" , "WinText", "ExcludeTitle", "ExcludeText")
Parameters~
UniqueID
--------
Unique ID (HWND) (as hexadecimal integer) of the first window matching
the given criteria.
WinTitle
--------
A window title or other criteria identifying the target window. See
WinTitle.
WinText
-------
If present, this parameter must be a substring from a single text
element of the target window (as revealed by the included Window Spy
utility). Hidden text elements are detected if DetectHiddenText is ON.
ExcludeTitle
------------
Windows whose titles include this value will not be considered. Note:
Due to backward compatibility, this parameter will be interpreted as a
command if it exactly matches the name of a command. To work around
this, use the WinExist() function instead.
ExcludeText
-----------
Windows whose text include this value will not be considered.
Remarks~
If all parameters are omitted, the Last Found Window will be checked to see if
it still exists (or doesn't exist in the case of |IfWinNotExist|).
If either of these commands determines that a qualified window exists, the
Last Found Window will be updated to be that window. In other words, if
IfWinExist evaluates to true or IfWinNotExist evaluates to false, the Last
Found Window will be updated.
The function |WinExist|() returns the Unique ID (HWND) of the first matching
window (0 if none). Since all non-zero numbers are seen as "true", the
statement if WinExist("WinTitle") is true whenever WinTitle exists.
To discover the HWND of a control (for use with Post/SendMessage or DllCall),
use |ControlGet| Hwnd or |MouseGetPos|.
|SetWinDelay| does not apply to |IfWinExist|/|IfWinActive|.
Window titles and text are case sensitive. Hidden windows are not detected
unless DetectHiddenWindows has been turned on.
Related~
|IfWinActive|, |SetTitleMatchMode|, |DetectHiddenWindows|, Last Found Window,
|Process|, |WinActivate|, |WinWaitActive|, |WinWait|, |WinWaitClose|,
#IfWinActive/Exist
Examples~
>
; Example 1
IfWinExist, Untitled - Notepad
{
WinActivate ; Automatically uses the window found above.
WinMaximize ; same
Send, Some text.{Enter}
return
}
; Example 2
IfWinNotExist, Calculator
return
else
{
WinActivate ; The above "IfWinNotExist" also set the "last found" window for us.
WinMove, 40, 40 ; Move it to a new position.
return
}
; Example 3
if WinExist("ahk_class Notepad") or WinExist("ahk_class" . ClassName)
WinActivate ; Uses the last found window.
MsgBox % "The active window's ID is " . WinExist("A")
; Example 4: Equivalent to IfWinNotExist, Calculator
If !WinExist("Calculator")
return
<
==============================================================================
*Run* *RunWait*
+---------------+~
| Run - RunWait |~
+---------------+~
Runs an external program. Unlike Run, RunWait will wait until the
program finishes before continuing
|Run|, Target [, WorkingDir , Max | Min | Hide | UseErrorLevel ,
OutputVarPID]
Parameters~
Target
------
A document, URL, executable file (.exe, .com, .bat, etc.), shortcut
(.lnk), or system verb to launch (see remarks). If Target is a local
file and no path was specified with it, A_WorkingDir will be searched
first. If no matching file is found there, the system will search for
and launch the file if it is integrated ("known"), e.g. by being
contained in one of the PATH folders.
To pass parameters, add them immediately after the program or document
name. If a parameter contains spaces, it is safest to enclose it in
double quotes (even though it may work without them in some cases).
WorkingDir
----------
The working directory for the launched item. Do not enclose the name
in double quotes even if it contains spaces. If omitted, the script's
own working directory ( A_WorkingDir ) will be used.
Max | Min | Hide
----------------
If omitted, Target will be launched normally. Alternatively, it can
contain one or more of these words:
Max: launch maximized
---------------------
Min: launch minimized
---------------------
Hide: launch hidden (cannot be used in combination with either of the
above)
Note: Some applications (e.g. Calc.exe) do not obey the requested
startup state and thus Max/Min/Hide will have no effect.
UseErrorLevel
-------------
UseErrorLevel can be specified alone or in addition to one of the above words
(by separating it from the other word with a space). If the launch fails, this
option skips the warning dialog, sets ErrorLevel to the word ERROR, and allows
the current thread to continue. If the launch succeeds, RunWait sets
ErrorLevel to the program's exit code, and Run sets it to 0.
When UseErrorLevel is specified, the variable A_LastError is set to the result
of the operating system's GetLastError() function. A_LastError is a number
between 0 and 4294967295 (always formatted as decimal, not hexadecimal). Zero
(0) means success, but any other number means the launch failed. Each number
corresponds to a specific error condition (to get a list, search
ww.microsoft.com for "system error codes"). Like ErrorLevel, A_LastError is a
per-thread setting; that is, interruptions by other threads cannot change it.
However, A_LastError is also set by DllCall.
OutputVarPID
------------
The name of the variable in which to store the newly launched program's unique
Process ID (PID). The variable will be made blank if the PID could not be
determined, which usually happens if a system verb, document, or shortcut is
launched rather than a direct executable file. RunWait also supports this
parameter, though its OuputVarPID must be checked in another thread
(otherwise, the PID will be invalid because the process will have terminated
by the time the line following RunWait executes).
After the Run command retrieves a PID, any windows to be created by the
process might not exist yet. To wait for at least one window to be created,
use
>
WinWait ahk_pid %OutputVarPID%
<
ErrorLevel~
[v1.1.04+] This command is able to throw an exception on failure. For
more information, see Runtime Errors.
Run
-----
Does not set ErrorLevel unless UseErrorLevel (above) is in effect, in
which case ErrorLevel is set to the word ERROR upon failure or 0 upon
success.
RunWait
-------
Sets ErrorLevel to the program's exit code (a signed 32-bit integer).
If UseErrorLevel is in effect and the launch failed, the word ERROR is
stored.
Remarks~
Unlike Run, RunWait will wait until Target is closed or exits, at
which time ErrorLevel will be set to the program's exit code (as a
signed 32-bit integer). Some programs will appear to return
immediately even though they are still running; these programs spawn
another process.
If Target contains any commas, they must be escaped as shown three
times in the following example:
>
Run rundll32.exe shell32.dll`,Control_RunDLL desk.cpl`,`, 3
; Opens Control Panel > Display Properties > Settings
<
When running a program via Comspec (cmd.exe) -- perhaps because you
need to redirect the program's input or output -- if the path or name
of the executable contains spaces, the entire string should be
enclosed in an outer pair of quotes. In the following example, the
outer quotes are shown in red and all the inner quotes are shown in
black:
>
Run %comspec% /c ""C:\My Utility.exe" "param 1" "second param" >"C:\My File.txt""
<
If Target cannot be launched, an error window is displayed, after
which the script will behave as though it encountered an Exit command.
To prevent this, include the string UseErrorLevel in the third
parameter.
Performance may be slightly improved if Target is an exact path, e.g.
Run, C:\Windows\Notepad.exe "C:\My Documents\Test.txt" rather than
Run, C:\My Documents\Test.txt
Special CLSID folders may be opened via Run. For example:
>
Run ::{20d04fe0-3aea-1069-a2d8-08002b30309d}
; Opens the "My Computer" folder.
Run ::{645ff040-5081-101b-9f08-00aa002f954e}
; Opens the Recycle Bin.
<
System verbs correspond to actions available in a file's right-click
menu in the Explorer. If a file is launched without a verb, the
default verb (usually "open") for that particular file type will be
used. If specified, the verb should be followed by the name of the
target file. The following verbs are currently supported:
*verb
-----
[AHK_L 57+]: Any system-defined or custom verb. For example:
>
Run *Compile %A_ScriptFullPath%
<
On Windows Vista and later, the
>
*RunAs
<
verb may be used in place of the Run As Administrator right-click menu item.
properties
----------
Displays the Explorer's properties window for the indicated file. For
example:
>
Run, properties "C:\My File.txt" Note: The properties window
<
will automatically close when the script terminates. To prevent this, use
|WinWait| to wait for the window to appear, then use |WinWaitClose| to wait
for the user to close it.
find
-----
Opens an instance of the Explorer's Search Companion or Find File
window at the indicated folder. For example:
>
Run, find D:\
<
explore
-------
Opens an instance of Explorer at the indicated folder. For example:
>
Run, explore %A_ProgramFiles%
<
edit
-----
Opens the indicated file for editing. It might not work if the
indicated file's type does not have an "edit" action associated with
it. For example:
>
Run, edit "C:\My File.txt"
<
open
-----
Opens the indicated file (normally not needed because it is the
default action for most file types). For example:
>
Run, open "My File.txt"
<
print
-----
Prints the indicated file with the associated application, if any. For
example:
>
Run, print "My File.txt"
<
While |RunWait| is in a waiting state, new threads can be launched via
hotkey, custom menu item, or timer.
Related~
|RunAs|, |Process|, |Exit|, CLSID List, |DllCall|
Examples~
>
Run, Notepad.exe, C:\My Documents, max
Run, mailto:someone@domain.com?subject=This is the subject line&body=This is the message body's text.
Run, ReadMe.doc, , Max UseErrorLevel
; Launch maximized and don't display dialog if it fails.
if ErrorLevel = ERROR
MsgBox The document could not be launched.
RunWait, %comspec% /c dir c:\ >>c:\DirTest.txt, , min
Run, c:\DirTest.txt
Run, properties c:\DirTest.txt
Run, www.autohotkey.com ; i.e. any URL can be launched.
Run, mailto:someone@somedomain.com
; This should open the default e-mail application.
Run ::{20d04fe0-3aea-1069-a2d8-08002b30309d}
; Opens the "My Computer" folder.
Run ::{645ff040-5081-101b-9f08-00aa002f954e}
; Opens the Recycle Bin.
; To run multiple commands consecutively, use "&&" between each:
Run, %comspec% /c dir /b > C:\list.txt && type C:\list.txt && pause
<
==============================================================================
*InputBox*
+----------+~
| InputBox |~
+----------+~
Displays an input box to ask the user to enter a string
|InputBox|, OutputVar [, Title, Prompt, HIDE, Width, Height, X , Y ,
Font, Timeout, Default ]
Parameters~
OutputVar
---------
The name of the variable in which to store the text entered by the
user
Title
-----
The title of the input box. If blank or omitted, it defaults to the
name of the script
Prompt
------
The text of the input box, which is usually a message to the user
indicating what kind of input is expected. If Prompt is long, it can
be broken up into several shorter lines by means of a continuation
section, which might improve readability and maintainability.
HIDE
-----
If this parameter is the word HIDE, the user's input will be masked,
which is useful for passwords.
Width
-----
If this parameter is blank or omitted, the starting width of the
window will be 375. This parameter can be an expression.
Height
------
If this parameter is blank or omitted, the starting height of the
window will be 189. This parameter can be an expression.
X , Y
-----
The X and Y coordinates of the window (use 0,0 to move it to the upper
left corner of the desktop), which can be expressions. If either
coordinate is blank or omitted, the dialog will be centered in that
dimension. Either coordinate can be negative to position the window
partially or entirely off the desktop.
Font
-----
Not yet implemented (leave blank). In the future it might accept
something like verdana:8
Timeout
-------
Timeout in seconds (can contain a decimal point or be an expression).
If this value exceeds 2147483 (24.8 days), it will be set to 2147483.
After the timeout has elapsed, the InputBox window will be
automatically closed and ErrorLevel will be set to 2. OutputVar will
still be set to what the user entered.
Default
-------
A string that will appear in the InputBox's edit field when the dialog
first appears. The user can change it by backspacing or other means.
ErrorLevel~
[v1.1.04+] This command is able to throw an exception on failure. For more
information, see Runtime Errors.
See below.
Remarks~
The dialog allows the user to enter text and then press OK or CANCEL.
The user can resize the dialog window by dragging its borders.
ErrorLevel is set to 1 if the user presses the CANCEL button, 0 if the
user presses OK, or 2 if the dialog times out. In all three cases,
OutputVar is set to the value entered. This allows the CANCEL button
to perform a function other than CANCEL should the script designer
wish it.
A GUI window may display a modal InputBox by means of Gui +OwnDialogs.
A modal InputBox prevents the user from interacting with the GUI
window until the InputBox is dismissed.
Related~
|GUI|, |Input|, |MsgBox|, |FileSelectFile|, |FileSelectFolder|,
|SplashTextOn|, |ToolTip|
Example~
>
InputBox, password, Enter Password, (your input will be hidden), hide
InputBox, UserInput, Phone Number, Please enter a phone number., , 640, 480
if ErrorLevel
MsgBox, CANCEL was pressed.
else
MsgBox, You entered "%UserInput%"
<
==============================================================================
*Input*
+-------+~
| Input |~
+-------+~
Waits for the user to type a string (not supported on Windows 9x: it
does nothing).
|Input| [, OutputVar, Options, EndKeys, MatchList ]
Parameters~
OutputVar
---------
The name of the variable in which to store the text entered by the
user (by default, artificial input is also captured).
If this and the other parameters are omitted, any Input in progress in
another thread is terminated and its ErrorLevel is set to the word
NewInput. By contrast, the ErrorLevel of the current command will be
set to 0 if it terminated a prior Input, or 1 if there was no prior
Input to terminate.
OutputVar does not store keystrokes per se. Instead, it stores
characters produced by keystrokes according to the active window's
keyboard layout/language. Consequently, keystrokes that do not produce
characters (such as PageUp and Escape) are not stored (though they can
be recognized via the EndKeys parameter below).
Whitespace characters such as TAB (`t) are stored literally. ENTER is
stored as linefeed (`n).
Options~
A string of zero or more of the following letters (in any order, with
optional spaces in between):
B
-----
Backspace is ignored. Normally, pressing backspace during an Input
will remove the most recently pressed character from the end of the
string. Note: If the input text is visible (such as in an editor) and
the arrow keys or other means are used to navigate within it,
backspace will still remove the last character rather than the one
behind the caret (insertion point).
C
-----
Case sensitive. Normally, MatchList is not case sensitive (in versions
prior to 1.0.43.03, only the letters A-Z are recognized as having
varying case, not letters like ü/Ü).
I
-----
Ignore input generated by any AutoHotkey script, such as the
|SendEvent| command. However, the |SendInput| and |SendPlay| methods
are always ignored, regardless of this setting.
L
-----
Length limit (e.g. L5). The maximum allowed length of the input. When
the text reaches this length, the Input will be terminated and
|ErrorLevel| will be set to the word Max unless the text matches one
of the MatchList phrases, in which case |ErrorLevel| is set to the
word Match. If unspecified, the length limit is 16383, which is also
the absolute maximum.
M
-----
Modified keystrokes such as Control-A through Control-Z are recognized
and transcribed if they correspond to real ASCII characters. Consider
this example, which recognizes Control-C:
>
Transform, CtrlC, Chr, 3 ; Store the character for Ctrl-C in the CtrlC var.
Input, OutputVar, L1 M
if OutputVar = %CtrlC%
MsgBox, You pressed Control-C.
ExitApp
<
Note: The characters Ctrl-A through Ctrl-Z correspond to Chr(1) through
Chr(26). Also, the M option might cause some keyboard shortcuts such as
Ctrl-LeftArrow to misbehave while an Input is in progress.
T
-----
Timeout (e.g. T3). The number of seconds to wait before terminating
the Input and setting ErrorLevel to the word Timeout. If the Input
times out, OutputVar will be set to whatever text the user had time to
enter. This value can be a floating point number such as 2.5.
V
-----
Visible. Normally, the user's input is blocked (hidden from the
system). Use this option to have the user's keystrokes sent to the
active window.
*~
Wildcard (find anywhere). Normally, what the user types must exactly
match one of the MatchList phrases for a match to occur. Use this
option to find a match more often by searching the entire length of
the input text.
EndKeys~
A list of zero or more keys, any one of which terminates the Input
when pressed (the EndKey itself is not written to OutputVar). When an
Input is terminated this way, ErrorLevel is set to the word EndKey
followed by a colon and the name of the EndKey. Examples: "EndKey:.",
"EndKey:Escape".
The EndKey list uses a format similar to the Send command. For
example, specifying
>
{Enter}.{Esc}
<
would cause either ENTER, period (.), or ESCAPE to terminate the
Input. To use the braces themselves as end keys, specify {{} and/or
{}}.
To use Control, Alt, or Shift as end-keys, specify the left and/or
right version of the key, not the neutral version. For example,
specify {LControl}{RControl} rather than {Control}.
Although modified keys such as Control-C (^c) are not supported,
certain keys that require the shift key to be held down -- namely
punctuation marks such as ?!:@&{} -- are supported in v1.0.14+.
An explicit virtual key code such as {vkFF} may also be specified.
This is useful in the rare case where a key has no name and produces
no visible character when pressed. Its virtual key code can be
determined by following the steps at the bottom fo the key list page.
MatchList~
A comma-separated list of key phrases, any of which will cause the
Input to be terminated (in which case ErrorLevel will be set to the
word Match). The entirety of what the user types must exactly match
one of the phrases for a match to occur (unless the * option is
present). In addition, any spaces or tabs around the delimiting commas
are significant, meaning that they are part of the match string. For
example, if MatchList is "ABC , XYZ ", the user must type a space
after ABC or before XYZ to cause a match.
Two consecutive commas results in a single literal comma. For example,
the following would produce a single literal comma at the end of
string: "string1,,,string2". Similarly, the following list contains
only a single item with a literal comma inside it: "single,,item".
Because the items in MatchList are not treated as individual
parameters, the list can be contained entirely within a variable. In
fact, all or part of it must be contained in a variable if its length
exceeds 16383 since that is the maximum length of any script line. For
example, MatchList might consist of
%List1%,%List2%,%List3% -- where each of the variables contains a
%large sub-list of match phrases.
ErrorLevel~
[v1.1.04+] This command is able to throw an exception if called with
no parameters and there is no Input in progress. For more information,
see Runtime Errors.
1 or 0
------
Whenever the command is used without parameters, ErrorLevel is set to
0 if it successfully terminates a prior input, or 1 if there is no
Input in progress.
NewInput
--------
The Input was interrupted by another thread that used the Input
command. Max The Input reached the maximum allowed length and it does
not match any of the items in MatchList.
Timeout
-------
The Input timed out.
Match
-----
The Input matches one of the items in MatchList.
EndKey:name
-----------
One of the EndKeys was pressed to terminate the Input. In this case,
ErrorLevel contains the word EndKey followed by a colon and the name
of the terminating key without braces, e.g. "EndKey:Enter",
"EndKey:Escape", etc.
Remarks~
If this command is used while an Input is already in progress in
another thread, that Input will be terminated and its ErrorLevel will
be set to the word NewInput. After that (if parameters were given),
the new Input will commence.
While an Input is in progress, new |threads| such as custom menu items
and timed subroutines can still be created. Similarly, keyboard
hotkeys are still in effect if the Input is visible. If the Input is
not visible, only hook hotkeys can be triggered.
When a script first uses this command, the keyboard hook is installed
(if it is not already). In addition, the script becomes persistent,
meaning that ExitApp should be used to terminate it. The keyboard hook
will stay installed until the next use of the Suspend or Hotkey
command, at which time it is removed if not required by any hotkeys or
hotstrings.
If you use multiple languages or keyboard layouts, Input uses the
keyboard layout of the active window rather than the script's
(regardless of whether the Input is visible). However, in versions
prior to 1.0.44.03, the script's own layout is used.
Although not as flexible, hotstrings are generally easier to use than
the Input command.
Input does nothing on Windows 9x (not even changing ErrorLevel and
OutputVar). To detect Windows 9x, use A_OSType.
Related~
|KeyWait|, |Hotstrings|, |InputBox|, #InstallKeybdHook, Threads, if
var in/contains MatchList
Examples~
>
; Wait for the user to press any key. Keys that produce no visible character -- such as
; the modifier keys, function keys, and arrow keys -- are listed as end keys so that they
; will be detected too.
Input, SingleKey, L1, {LControl}{RControl}{LAlt}{RAlt}{LShift}{RShift}{LWin}{RWin}{AppsKey}{F1}{F2}{F3}{F4}{F5}{F6}{F7}{F8}{F9}{F10}{F11}{F12}{Left}{Right}{Up}{Down}{Home}{End}{PgUp}{PgDn}{Del}{Ins}{BS}{Capslock}{Numlock}{PrintScreen}{Pause}
; This is a working hotkey example. Since the hotkey has the tilde (~)
; prefix, its own keystroke will pass through to the active window
; (except on Win9x). Thus, if you type [btw (or one of the other match
; phrases) in any editor, the script will automatically perform an
; action of your choice (such as replacing the typed text):
~[::
Input, UserInput, V T5 L4 C, {enter}.{esc}{tab}, btw,otoh,fl,ahk,ca
if ErrorLevel = Max
{
MsgBox, You entered "%UserInput%", which is the maximum length of text.
return
}
if ErrorLevel = Timeout
{
MsgBox, You entered "%UserInput%" at which time the input timed out.
return
}
if ErrorLevel = NewInput
return
IfInString, ErrorLevel, EndKey:
{
MsgBox, You entered "%UserInput%" and terminated the input with %ErrorLevel%.
return
}
; Otherwise, a match was found.
SetKeyDelay, -1 ; Most editors can handle the fastest speed.
if UserInput = btw
Send, {backspace 4}by the way
else if UserInput = otoh
Send, {backspace 5}on the other hand
else if UserInput = fl
Send, {backspace 3}Florida
else if UserInput = ca
Send, {backspace 3}California
else if UserInput = ahk
Run, www.autohotkey.com
return
<
==============================================================================
*loop_parse_a_string*
Loop (parse a string)~
------------------------------------------------------------------------------
Retrieves substrings (fields) from a string, one at a time
|Loop|, Parse, InputVar [, Delimiters , OmitChars* ]
Parameters~
Parse
-----
This parameter must be the word PARSE, and unlike other loop types, it
must not be a variable reference that resolves to the word PARSE.
InputVar
--------
The name of the variable whose contents will be analyzed. Do not
enclose the name in percent signs unless you want the contents of the
variable to be used as the name.
Delimiters
----------
If this parameter is blank or omitted, each character of InputVar will
be treated as a separate substring.
If this parameter is CSV, InputVar will be parsed in standard comma
separated value format. Here is an example of a CSV line produced by
MS Excel:
>
"first field",SecondField,"the word ""special"" is quoted
literally",,"last field, has literal comma"
<
Otherwise, Delimiters contains one or more characters (case
sensitive), each of which is used to determine where the boundaries
between substrings occur in InputVar.
Delimiter characters are not considered to be part of the substrings
themselves. In addition, if there is nothing between a pair of
delimiters within InputVar, the corresponding substring will be empty.
For example: `, (an escaped comma) would divide the string based on
every occurrence of a comma. Similarly, %A_Tab%%A_Space% would start a
new substring every time a space or tab is encountered in InputVar.
To use a string as a delimiter rather than a character, first use
StringReplace to replace all occurrences of the string with a single
character that is never used literally in the text, e.g. one of these
special characters: ¢¤¥¦§©ª«®µ¶. Consider this example, which uses the
string
as a delimiter:
>
StringReplace, NewHTML, HTMLString,
, ¢, All
Loop, parse, NewHTML, ¢ ; Parse the string based on the cent symbol.
{
...
}
<
OmitChars
---------
An optional list of characters (case sensitive) to exclude from the
beginning and end of each substring. For example, if OmitChars is
%A_Space%%A_Tab%, spaces and tabs will be removed from the beginning
%and end (but not the middle) of every retrieved substring.
If Delimiters is blank, OmitChars indicates which characters should be
excluded from consideration (the loop will not see them).
Unlike the last parameter of most other commands, commas in OmitChars
must be escaped (`,).
Remarks~
A string parsing loop is useful when you want to operate on each field
contained in a string, one at a time. Parsing loops use less memory
than StringSplit (since |StringSplit| creates a permanent array) and
in most cases they are easier to use.
The built-in variable A_LoopField exists within any parsing loop. It
contains the contents of the current substring (field) from InputVar.
If an inner parsing loop is enclosed by an outer parsing loop, the
innermost loop's field will take precedence.
Although there is no built-in variable "A_LoopDelimiter", the example
at the very bottom of this page demonstrates how to detect which
delimiter was encountered for each field.
There is no restriction on the size of InputVar or its fields. In
addition, if InputVar's contents change during the execution of the
loop, the loop will not "see" the changes because it is operating on a
temporary copy of the original contents.
To arrange the fields in a different order prior to parsing, use the
|Sort| command.
See |Loop| for information about Block, |Break|, |Continue|, and the A_Index
variable (which exists in every type of loop).
Related~
|StringSplit|, file-reading loop, |Loop|, |Break|, |Continue|, Blocks, |Sort|,
|FileSetAttrib|, |FileSetTime|
Examples~
>
; Example #1:
Colors = red,green,blue
Loop, parse, Colors, `,
{
MsgBox, Color number %A_Index% is %A_LoopField%.
}
; Example #2: Read the lines inside a variable, one by one
; (similar to a file-reading loop).
; A file can be loaded into a variable via FileRead:
Loop, parse, FileContents, `n, `r ; Specifying `n prior to `r
; allows both Windows and Unix files to be parsed.
{
MsgBox, 4, , Line number %A_Index% is %A_LoopField%.`n`nContinue?
IfMsgBox, No, break
}
; Example #3: This is the same as the example above except
; that it's for the clipboard. It's useful whenever the
; clipboard contains files, such as those copied from an open
; Explorer window (the program automatically converts such
; files to their file names):
Loop, parse, clipboard, `n, `r
{
MsgBox, 4, , File number %A_Index% is %A_LoopField%.`n`nContinue?
IfMsgBox, No, break
}
; Example #4: Parse a comma separated value (CSV) file:
Loop, read, C:\Database Export.csv
{
LineNumber = %A_Index%
Loop, parse, A_LoopReadLine, CSV
{
MsgBox, 4, , Field %LineNumber%-%A_Index% is:`n%A_LoopField%`n`nContinue?
IfMsgBox, No
return
}
}
>
; Example #5: Determining which delimiter was encountered.
; Initialize string to search.
Colors = red,green|blue;yellow|cyan,magenta
; Initialize counter to keep track of our position in the string.
Position := 0
Loop, Parse, Colors, `,|;
{
; Calculate the position of the delimiter at the end of this field.
Position += StrLen(A_LoopField) + 1
; Retrieve the delimiter found by the parsing loop.
Delimiter := SubStr(Colors, Position, 1)
MsgBox Field: %A_LoopField%`nDelimiter: %Delimiter%
}
<
==============================================================================
*StringSplit*
+-------------+~
| StringSplit |~
+-------------+~
Separates a string into an array of substrings using the specified
delimiters
|StringSplit|, OutputArray, InputVar [, Delimiters, OmitChars ]
Parameters~
OutputArray
-----------
The name of the array in which to store each substring extracted from
InputVar. For example, if MyArray is specified, the command will put
the number of substrings produced (0 if none) into MyArray0, the first
substring into MyArray1, the second into MyArray2, and so on.
Within a function, to create an array that is global instead of local,
declare MyArray0 as a global variable inside the function (the
converse is true for assume-global functions).
InputVar
--------
The name of the variable whose contents will be analyzed. Do not
enclose the name in percent signs unless you want the contents of the
variable to be used as the name. NOTE: InputVar must not be one of the
variables in OutputArray.
Delimiters
----------
If this parameter is blank or omitted, each character of InputVar will
be treated as a separate substring.
Otherwise, Delimiters contains one or more characters (case
sensitive), each of which is used to determine where the boundaries
between substrings occur in InputVar. Since the delimiter characters
are not considered to be part of the substrings themselves, they are
never copied into OutputArray. Also, if there is nothing between a
pair of delimiters within InputVar, the corresponding array element
will be blank.
For example: `, (an escaped comma) would divide the string based on
every occurrence of a comma. Similarly, %A_Tab%%A_Space% would create
a new array element every time a space or tab is encountered in
InputVar.
To use a string as a delimiter rather than a character, first use
|StringReplace| to replace all occurrences of the string with a single
character that is never used literally in the text. Consider this
example, which uses the string
as a delimiter:
>
StringReplace, NewHTML, HTMLString,
, ``, All ; Replace
; each
with an accent.
StringSplit, MyArray, NewHTML, `` ; Split the string based on
; the accent character.
<
OmitChars
---------
An optional list of characters (case sensitive) to exclude from the
beginning and end of each array element. For example, if OmitChars is
%A_Space%%A_Tab%, spaces and tabs will be removed from the beginning
%and end (but not the middle) of every element.
If Delimiters is blank, OmitChars indicates which characters should be
excluded from the array.
Unlike the last parameter of most other commands, commas in OmitChars
must be escaped (`,).
Remarks~
If the array elements already exist, the command will change the
values of only the first N elements, where N is the number of
substrings present in InputVar. Any elements beyond N that existed
beforehand will be unchanged. Therefore, it is safest to use the zero
element (MyArray0) to determine how many items were actually produced
by the command.
Whitespace characters such as spaces and tabs will be preserved unless
those characters are themselves delimiters. Tabs and spaces can be
trimmed from both ends of any variable by assigning it to itself while
AutoTrim is on (the default). For example:
>
MyArray1 = %MyArray1%
<
To split a string that is in standard CSV (comma separated value)
format, use a parsing loop since it has built-in CSV handling.
To arrange the fields in a different order prior to splitting them,
use the |Sort| command.
If you do not need the substrings to be permanently stored in memory,
consider using a parsing loop -- especially if InputVar is very large,
in which case a large amount of memory would be saved. For example:
>
Colors = red,green,blue
Loop, parse, Colors, `,
MsgBox Color number %A_Index% is %A_LoopField%.
<
Related~
Parsing loop, Arrays , |Sort|, |SplitPath|, |IfInString|,
|StringGetPos|, |StringMid|, |StringTrimLeft|, |StringTrimRight|,
|StringLen|, |StringLower|, |StringUpper|, |StringReplace|
Examples~
>
TestString = This is a test.
StringSplit, word_array, TestString, %A_Space%, . ; Omits periods.
MsgBox, The 4th word is %word_array4%.
Colors = red,green,blue
StringSplit, ColorArray, Colors, `,
Loop, %ColorArray0%
{
this_color := ColorArray%a_index%
MsgBox, Color number %a_index% is %this_color%.
}
<
==============================================================================
*Arrays*
Arrays~
------------------------------------------------------------------------------
Associative Arrays [AHK_L 31+]
Self-contained associative arrays can be created by calling Object().
For example:
>
; Create the array, initially empty:
Array := Object()
; Write to the array:
Loop, Read, C:\Guest List.txt ; This loop retrieves each line from the file, one at a time.
{
Array.Insert(A_LoopReadLine) ; Append this line to the array.
}
; Read from the array:
; Loop % Array.MaxIndex() ; More traditional approach.
for index, element in Array ; Recommended approach in most cases.
{
; Using "Loop", indices must be consecutive numbers from 1 to the number
; of elements in the array (or they must be calculated within the loop).
; MsgBox % "Element number " . A_Index . " is " . Array[A_Index]
; Using "for", both the index (or "key") and its associated value
; are provided, and the index can be *any* value of your choosing.
MsgBox % "Element number " . index . " is " . element
}
<
This shows only a small subset of the functionality provided by
objects. Items can be set, retrieved, inserted, removed and
enumerated. Strings and objects can be used as keys in addition to
numbers. Objects can be stored as values in other objects and passed
as function parameters or return values. Objects can also be extended
with new functionality.
Though Insert() and enumerators have their uses, some users might find
it easier to use the more traditional approach:
>
; Each array must be initialized before use:
Array := Object()
; Array%j% := A_LoopField
Array[j] := A_LoopField
; Array%j%_%k% := A_LoopReadLine
Array[j, k] := A_LoopReadLine
ArrayCount := 0
Loop, Read, C:\Guest List.txt
{
ArrayCount += 1
; Array%ArrayCount% := A_LoopReadLine
Array[ArrayCount] := A_LoopReadLine
}
Loop %ArrayCount%
{
; element := Array%A_Index%
element := Array[A_Index]
; MsgBox % "Element number " . A_Index . " is " . Array%A_Index%
MsgBox % "Element number " . A_Index . " is " . Array[A_Index]
}
<
ArrayCount is left as a variable for convenience, but can be stored in
the array itself with
>
Array.Count := n
<
or it can be removed and
>
Array._MaxIndex()
<
used in its place. If a starting index other than 1 is desired,
>
Array._MinIndex()
<
can also be used.
Pseudo-Arrays~
Pseudo-arrays are mostly conceptual: Each array is really just a
collection of sequentially numbered variables or functions, each one
being perceived as an element of the array. AutoHotkey does not link
these elements together in any way.
In addition to array-creating commands like |StringSplit| and "WinGet
List", any command that accepts an OutputVar or that assigns a value
to a variable can be used to create an array. The simplest example is
the assignment operator (:=), as shown below:
>
Array%j% := A_LoopField
<
Multidimensional arrays are possible by using a separator character of
your choice between the indices. For example:
>
Array%j%_%k% := A_LoopReadLine
<
The following example demonstrates how to create and access an array,
in this case a series of names retrieved from a text file:
>
; Write to the array:
ArrayCount = 0
Loop, Read, C:\Guest List.txt
; This loop retrieves each line from the file, one at
; a time.
{
ArrayCount += 1
; Keep track of how many items are in the array.
Array%ArrayCount% := A_LoopReadLine
; Store this line in the next array element.
}
; Read from the array:
Loop %ArrayCount%
{
; The following line uses the := operator to retrieve an array element:
element := Array%A_Index%
; A_Index is a built-in variable.
; Alternatively, you could use the "% " prefix to make
; MsgBox or some other command expression-capable:
MsgBox % "Element number " . A_Index . " is " . Array%A_Index%
}
<
A concept related to arrays is the use of NumPut() and NumGet() to
store/retrieve a collection of numbers in binary format. This might be
helpful in cases where performance and/or memory conservation are
important.
==============================================================================
*Functions*
Functions~
------------------------------------------------------------------------------
Table of Contents~
Introduction and Simple Examples ~
Parameters ~
Optional Parameters ~
Returning Values to Caller ~
Variadic Functions ~
Local Variables ~
Dynamically Calling a Function ~
Short-circuit Boolean Evaluation ~
Using Subroutines Within a Function ~
Return, Exit, and General Remarks ~
Using #Include to Share Functions Among Multiple Scripts ~
Libraries of Functions: Standard Library and User Library ~
Built-in Functions ~
*introductions_to_functions_and_simple_examples*
Introduction and Simple Examples~
A function is similar to a subroutine (Gosub) except that it can
accept parameters (inputs) from its caller. In addition, a function
may optionally return a value to its caller. Consider the following
simple function that accepts two numbers and returns their sum:
>
Add(x, y)
{
return x + y ; "Return" expects an expression.
}
<
The above is known as a function definition because it creates a
function named "Add" (not case sensitive) and establishes that anyone
who calls it must provide exactly two parameters (x and y). To call
the function, assign its result to a variable with the := operator.
For example:
>
Var := Add(2, 3) ; The number 5 will be stored in Var.
<
Also, a function may be called without storing its return value:
>
Add(2, 3)
<
But in this case, any value returned by the function is discarded; so
unless the function produces some effect other than its return value,
the call would serve no purpose.
Since a function call is an expression, any variable names in its
parameter list should not be enclosed in percent signs. By contrast,
literal strings should be enclosed in double quotes. For example:
>
if InStr(MyVar, "fox")
MsgBox The variable MyVar contains the word fox.
<
Finally, functions may be called in the parameters of any command
(except OutputVar and InputVar parameters such as those of StringLen).
However, parameters that do not support expressions must use the "% "
prefix as in this example:
>
MsgBox % "The answer is: " . Add(3, 2)
<
The "% " prefix is also permitted in parameters that natively support
expressions, but it is simply ignored.
Parameters~
When a function is defined, its parameters are listed in parentheses
next to its name (there must be no spaces between its name and the
open-parenthesis). If a function does not accept any parameters,
leave the parentheses empty; for example: |GetCurrentTimestamp|().
*function_byref_parameters*
ByRef Parameters ~
From the function's point of view, parameters are essentially the same
as local variables unless they are defined as ByRef as in this
example:
>
Swap(ByRef Left, ByRef Right)
{
temp := Left
Left := Right
Right := temp
}
<
In the example above, the use of ByRef causes each parameter to become
an alias for the variable passed in from the caller. In other words,
the parameter and the caller's variable both refer to the same
contents in memory. This allows the Swap function to alter the
caller's variables by moving Left's contents into Right and vice
versa.
By contrast, if ByRef were not used in the example above, Left and
Right would be copies of the caller's variables and thus the Swap
function would have no external effect.
Since return can send back only one value to a function's caller,
ByRef can be used to send back extra results. This is achieved by
having the caller pass in a variable (usually empty) in which the
function stores a value.
When passing large strings to a function, ByRef enhances performance
and conserves memory by avoiding the need to make a copy of the
string. Similarly, using ByRef to send a long string back to the
caller usually performs better than something like
>
Return HugeString
<
[AHK_L 60+]: If something other than a modifiable variable is passed
to a ByRef parameter, the function behaves as though the keyword
"ByRef" is absent. For example,
>
Swap(A_Index, i)
<
stores the value of A_Index in i, but the value assigned to Left is
discarded once the Swap function returns.
[v1.1.01+]: The |IsByRef|() function can be used to determine whether
the caller supplied a variable for a given ByRef parameter
Known limitations~
Fields of objects are not considered variables for the purposes of
ByRef. For example, if
>
foo.bar
<
is passed to a ByRef parameter, it will behave as though ByRef was
omitted.
It is not possible to pass Clipboard, built-in variables, or
environment variables to a function's ByRef parameter, even when
#NoEnv is absent from the script.
Although a function may call itself recursively, if it passes one of
its own local variables or non-ByRef parameters to itself ByRef, the
new layer's ByRef parameter will refer to its own local variable of
that name rather than the previous layer's. However, this issue does
not occur when a function passes to itself a global variable, static
variable, or ByRef parameter.
If a parameter in a function-call resolves to a variable (e.g.
>
Var
<
or
>
++Var
<
or
>
Var*=2
<
other parameters to its left or right can alter that variable before
it is passed to the function. For example,
>
func(Var, Var++)
<
would unexpectedly pass 1 and 0 when Var is initially 0, even when the
function's first parameter is not ByRef. Since this behavior is
counterintuitive, it might change in a future release.
*function_optional_parametes*
Optional Parameters~
When defining a function, one or more of its parameters can be marked
as optional. This is done by appending an equal sign (or
>
:=
<
in v1.1.09+) followed by a default value. The following function has
its Z parameter marked optional:
>
Add(X, Y, Z:=0) {
return X + Y + Z
}
<
As of v1.1.09, both
>
=
<
and
>
:=
<
are supported. The latter is recommended for consistency with
expression assignments and compatibility with future versions of
AutoHotkey.
When the caller passes three parameters to the function above, Z's
default value is ignored. But when the caller passes only two
parameters, Z automatically receives the value 0.
It is not possible to have optional parameters isolated in the middle
of the parameter list. In other words, all parameters that lie to the
right of the first optional parameter must also be marked optional.
[AHK_L 31+]: Optional parameters may be omitted from the middle of the
parameter list when calling the function, unless the function call is
dynamic:
>
Func(1,, 3)
Func(X, Y:=2, Z:=0) { ; Note that Z must still be optional in this case.
MsgBox %X%, %Y%, %Z%
}
<
In v1.0.46.13+, ByRef parameters also support default values; for
example:
>
Func(ByRef p1 = "")
<
Whenever the caller omits such a parameter, the function creates a
local variable to contain the default value; in other words, the
function behaves as though the keyword "ByRef" is absent.
A parameter's default value must be one of the following:
>
true
false
<
a literal integer, a literal floating point number, or a
quoted/literal string such as "fox" or "" (but strings in versions
prior to 1.0.46.13+ support only "").
*returning_values_to_a_caller*
Returning Values to Caller~
------------------------------------------------------------------------------
As described in introduction, a function may optionally return a value
to its caller.
>
Test := returnTest()
MsgBox % Test
returnTest() {
return 123
}
<
If you want to return extra results from a function, you may also use
ByRef:
>
returnByRef(A,B,C)
MsgBox % A "," B "," C
returnByRef(ByRef val1, ByRef val2, ByRef val3)
{
val1 := "A"
val2 := 100
val3 := 1.1
return
}
<
[v1.0.97+]: Objects and Arrays can be used to return multiple values
or even named values:
>
Test1 := returnArray1()
MsgBox % Test1[1] "," Test1[2]
Test2 := returnArray2()
MsgBox % Test2[1] "," Test2[2]
Test3 := returnObject()
MsgBox % Test3.id "," Test3.val
returnArray1() {
Test := [123,"ABC"]
return Test
}
returnArray2() {
x := 456
y := "EFG"
return [x, y]
}
returnObject() {
Test := {id: 789, val: "HIJ"}
return Test
}
<
*function_variadic_functions*
Variadic Functions [AHK_L 60+]~
------------------------------------------------------------------------------
When defining a function, write an asterisk after the final parameter
to mark the function as variadic, allowing it to receive a variable
number of parameters:
>
Join(sep, params*) {
for index,param in params
str .= param . sep
return SubStr(str, 1, -StrLen(sep))
}
MsgBox % Join("`n", "one", "two", "three")
<
When a variadic function is called, surplus parameters can be accessed
via an object which is stored in the function's final parameter. The
first surplus parameter is at
>
params[1]
<
the second at
>
params[2]
<
and so on. As with any standard object,
>
params.MaxIndex()
<
can be used to determine the highest numeric index (in this case the
number of parameters). However, if there are no parameters, MaxIndex
returns an empty string.
Notes:
- The "variadic" parameter can only appear at the end of the formal
parameter list.
- RegEx callouts cannot be variadic; the "variadic" parameter is
tolerated but left blank.
- Callbacks pass surplus parameters by address rather than via an
array.
Variadic Function Calls~
While variadic functions can accept a variable number of parameters,
an array of parameters can be passed to any function by applying the
same syntax to a function-call:
>
substrings := ["one", "two", "three"]
MsgBox % Join("`n", substrings*)
<
Notes:
- Numbering of parameters within the source array begins at 1.
- Optional parameters may be entirely omitted from the array.
- The array of parameters may contain named items when directly calling
a user-defined function.
- The target function may also be variadic, in which case named items
are copied even if they have no corresponding formal parameter.
- This syntax can also be used when calling methods or retrieving
properties of objects; for example, >
Object.Property[Params*]
<
Known limitations:~
- Only the last physical parameter can be expanded this way. For
example, >
Func(x, y*)
< is supported but >
Func(x*, y)
< is not.
- This syntax cannot be used when setting properties of objects, since
the last physical parameter is actually the value being assigned.
- There must not be any non-whitespace characters between the asterisk
(*) and the symbol which ends the parameter list.
*local_and_global_variables*
Local and Global Variables ~
------------------------------------------------------------------------------
Local Variables~
All variables accessed or created inside a function are local by
default (except super-global variables and built-in variables such as
Clipboard, ErrorLevel , and A_TimeIdle). Each local variable's
contents are visible only to lines that lie inside the function.
Consequently, a local variable may have the same name as a global
variable and both will have separate contents. Finally, all local
variables start off blank each time the function is called.
Global variables~
To refer to an existing global variable inside a function (or create a
new one), declare the variable as global prior to using it. For
example:
>
LogToFile(TextToLog)
{
global LogFileName ; This global variable was previously
; given a value somewhere outside this function
FileAppend, %TextToLog%`n, %LogFileName%
}
Assume-global mode ~
If a function needs to access or create a large number of global
variables, it can be defined to assume that all its variables are
global (except its parameters) by making its first line either the
word "global" or the declaration of a local variable. For example:
>
SetDefaults()
{
global
; This word may be omitted if the first line of
; this function will be something like "local MyVar".
MyGlobal := 33 ; Assigns 33 to a global variable, first
; creating the variable if necessary.
local x, y:=0, z ; Local variables must be declared in
; this mode, otherwise they would be assumed global.
}
This assume-global mode can also be used by a function to create a
global array, such as a loop that assigns values to >
Array%A_Index%
<
*super_global_variables*
Super-global variables [v1.1.05+]~
------------------------------------------------------------------------------
If a global declaration appears outside of any function, it takes
effect for all functions by default. This avoids the need to
redeclare the variable in each function. However, if a function
parameter or local variable with the same name is declared, it takes
precedence over the global variable. Variables created by the *class*
keyword are also super-global.
Static variables~
Static variables are always implicitly local, but differ from locals
because their values are remembered between calls. For example:
>
LogToFile(TextToLog)
{
static LoggedLines = 0
LoggedLines += 1
; Maintain a tally locally (its value is remembered between calls).
global LogFileName
FileAppend, %LoggedLines%: %TextToLog%`n, %LogFileName%
}
<
Static Initializers~
In versions prior to 1.0.46, all static variables started off blank;
so the only way to detect that one was being used for the first time
was to check whether it was blank. In v1.0.46+, a static variable may
be initialized to something other than >
""
<
by following it with >
:=
<
or >
=
<
followed by one of the following: >
true
false
<
a literal integer, a literal floating point number, or a
literal/quoted string such as >
"fox"
<
For example: >
static X:=0, Y:="fox"
<
Each static variable is initialized only once (before the script
begins executing).
[AHK_L 58+]: >
Static var := expression
<
is supported. All such expressions are evaluated immediately before
the script's auto-execute section in the order they are encountered in
the script.
Assume-static mode [v1.0.48+]~
A function may be defined to assume that all its variables are static
(except its parameters) by making its first line the word "static".
For example:
>
GetFromStaticArray(WhichItemNumber)
{
static
static FirstCallToUs := true ; A static declaration's
; initializer still runs only once (upon startup).
if FirstCallToUs ; Create a static array during the
; first call, but not on subsequent calls.
{
FirstCallToUs := false
Loop 10
StaticArray%A_Index% := "Value #" . A_Index
}
return StaticArray%WhichItemNumber%
}
<
In assume-static mode, any variable that should not be static must be
declared as local or global.
More about locals and globals~
Multiple variables may be declared on the same line by separating them
with commas as in these examples:
>
global LogFileName, MaxRetries := 5
static TotalAttempts = 0, PrevResult
<
In v1.0.46+, a local or global variable may be initialized on the same
line as its declaration by following it with
>
:=
<
or
>
=
<
followed by any expression (the
>
=
<
operator behaves the same as
>
:=
<
in declarations). Unlike static initializers, the initializers of
locals and globals execute every time the function is called, but only
if/when the flow of control actually reaches them. In other words, a
line like
>
local x = 0
<
has the same effect as writing two separate lines:
>
local x
<
followed by
>
x = 0
<
Because the words local, global, and static are processed immediately
when the script launches, a variable cannot be conditionally declared
by means of an IF statement . In other words, a declaration inside an
IF's or ELSE's block takes effect unconditionally for all lines
between the declaration and the function's closing brace. Also note
that it is not currently possible to declare a dynamic variable such
as
>
global Array%i%
<
For commands that create arrays (such as |StringSplit|), the resulting
array is local if the assume-global mode is not in effect or if the
array's first element has been declared as a local variable (this is
also true if one of the function's parameters is passed -- even if
that parameter is ByRef -- because parameters are similar to local
variables). Conversely, if the first element has been declared global,
a global array is created. However, the common source of confusion
below applies even in these cases. The first element for |StringSplit|
is ArrayName0. For other array-creating commands such as WinGet List,
the first element is ArrayName (i.e. without the number).
Within a function, any dynamic variable reference such as
>
Array%i%
<
always resolves to a local variable unless no variable of that name
exists, in which case a global is used if it exists. If neither exists
and the usage requires the variable to be created, it is created as a
local variable unless the assume-global mode is in effect.
Consequently, a function can create a global array manually (by means
such as
>
Array%i% := A_Index
<
) only if it has been defined as an assume-global function.
Common source of confusion ~
Any non-dynamic reference to a variable creates that variable the
moment the script launches. For example, when used outside a function,
>
MsgBox %Array1%
<
creates Array1 as a global the moment the script launches.
Conversely, when used inside a function
>
MsgBox %Array1%
<
creates Array1 as one of the function's locals the moment the script
launches (unless assume-global is in effect), even if Array and Array0
are declared global.
Dynamically Calling a Function~
In v1.0.47.06+, a function (even a built-in function) may be called
dynamically via percent signs. For example,
>
%Var%(x, "fox")
<
would call the function whose name is contained in Var. Similarly,
>
Func%A_Index%()
<
would call Func1() or Func2(), etc., depending on the current value of
A_Index.
In v1.1.07.00+, Var in %Var%() can contain a function name, function
reference or object imitating a function . If the function does not
exist, the default base object's __Call meta-function is invoked
instead.
If the function cannot be called due to one of the reasons below, the
evaluation of the expression containing the call stops silently and
prematurely, which may lead to inconsistent results:
- Calling a nonexistent function, which can be avoided by using
>
If IsFunc(VarContainingFuncName)
<
Except for built-in functions, the called function's definition must
exist explicitly in the script by means such as |#Include| or a
non-dynamic call to a library function.
- Passing too few parameters, which can be avoided by checking
|IsFunc|()'s return value (which is the number of mandatory
parameters plus one). Note: In v1.0.48+, passing too many parameters
is tolerated; each extra parameter is fully evaluated (including any
calls to functions) and then discarded.
Finally, a dynamic call to a function is slightly slower than a normal
call because normal calls are resolved (looked up) before the script
begins running.
Short-circuit Boolean Evaluation~
When AND, OR, and the ternary operator are used within an expression,
they short-circuit to enhance performance (regardless of whether any
function calls are present). Short-circuiting operates by refusing to
evaluate parts of an expression that cannot possibly affect its final
result. To illustrate the concept, consider this example:
>
if (ColorName <> "" AND not FindColor(ColorName))
MsgBox %ColorName% could not be found.
<
In the example above, the FindColor() function never gets called if
the ColorName variable is empty. This is because the left side of the
AND would be false, and thus its right side would be incapable of
making the final outcome true.
Because of this behavior, it's important to realize that any
side-effects produced by a function (such as altering a global
variable's contents) might never occur if that function is called on
the right side of an AND or OR.
It should also be noted that short-circuit evaluation cascades into
nested ANDs and ORs. For example, in the following expression, only
the leftmost comparison occurs whenever ColorName is blank. This is
because the left side would then be enough to determine the final
answer with certainty:
>
if (ColorName = "" OR FindColor(ColorName, Region1) OR FindColor(ColorName, Region2))
break ; Nothing to search for, or a match was found.
<
As shown by the examples above, any expensive (time-consuming)
functions should generally be called on the right side of an AND or OR
to enhance performance. This technique can also be used to prevent a
function from being called when one of its parameters would be passed
a value it considers inappropriate, such as an empty string.
In v1.0.46+, the ternary conditional operator (?:) also short-circuits
by not evaluating the losing branch.
Using Subroutines Within a Function~
Although a function cannot contain definitions of other functions, it
can contain subroutines. As with other subroutines, use Gosub to
launch them and Return to return (in which case the |Return| would
belong to the |Gosub| and not the function).
Known limitation: Currently, the name of each subroutine (label) must
be unique among those of the entire script. The program will notify
you upon launch if there are duplicate labels.
If a function uses |Gosub| to jump to a public subroutine (one that
lies outside of the function's braces), all variables outside are
global and the function's own local variables are not accessible until
the subroutine returns. However, A_ThisFunc will still contain the
name of the function.
Although |Goto| cannot be used to jump from inside a function to
outside, it is possible for a function to |Gosub| an external/public
subroutine and then do a Goto from there.
Although the use of |Goto| is generally discouraged, it can be used
inside a function to jump to another position within the same
function. This can help simplify complex functions that have many
points of return, all of which need to do some clean-up prior to
returning.
A function may contain externally-called subroutines such as timers,
GUI g-labels, and menu items. This is generally done to encapsulate
them in a separate file for use with |#Include| , which prevents them
from interfering with the script's auto-execute section. However, the
following limitations apply:
- Such subroutines should use only static and global variables (not
locals) if their function is ever called normally. This is because a
subroutine thread that interrupts a function-call thread (or vice
versa) would be able to change the values of local variables seen by
the interrupted thread. Furthermore, any time a function returns to
its caller, all of its local variables are made blank to free their
memory.
- Such subroutines should use only global variables (not static
variables ) as GUI control variables.
- When a function is entered by a subroutine thread, any references to
dynamic variables made by that thread are treated as globals
(including commands that create arrays).
Return, Exit, and General Remarks~
If the flow of execution within a function reaches the function's
closing brace prior to encountering a |Return|, the function ends and
returns a blank value (empty string) to its caller. A blank value is
also returned whenever the function explicitly omits |Return's|
parameter.
When a function uses the Exit command to terminate the current thread,
its caller does not receive a return value at all. For example, the
statement
>
Var := Add(2, 3)
<
would leave
>
Var
<
unchanged if
>
Add()
<
exits. The same thing happens if a function causes a runtime error
such as running a nonexistent file (when UseErrorLevel is not in
effect).
A function may alter the value of ErrorLevel for the purpose of
returning an extra value that is easy to remember.
To call a function with one or more blank values (empty strings), use
an empty pair of quotes as in this example:
>
FindColor(ColorName, "")
<
Since calling a function does not start a new thread, any changes made
by a function to settings such as |SendMode| and |SetTitleMatchMode|
will go into effect for its caller too.
The caller of a function may pass a nonexistent variable or array
element to it, which is useful when the function expects the
corresponding parameter to be ByRef. For example, calling
>
GetNextLine(BlankArray%i%)
<
would create the variable
>
BlankArray%i%
<
automatically as a local or global (depending on whether the caller is
inside a function and whether it has the assume-global mode in
effect).
When used inside a function, |ListVars| displays a function's local
variables along with their contents. This can help debug a script.
Style and Naming Conventions~
You might find that complex functions are more readable and
maintainable if their special variables are given a distinct prefix.
For example, naming each parameter in a function's parameter list with
a leading "p" or "p_" makes their special nature easy to discern at a
glance, especially when a function has several dozen local variables
competing for your attention. Similarly, the prefix "r" or "r_" could
be used for ByRef parameters, and "s" or "s_" could be used for static
variables.
The One True Brace ( OTB ) style may optionally be used to define functions.
For example:
>
Add(x, y) {
return x + y
}
<
Using #Include to Share Functions Among Multiple Scripts~
The |#Include| directive may be used (even at the top of a script) to
load functions from an external file.
Explanation: When the script's flow of execution encounters a function
definition, it jumps over it (using an instantaneous method) and
resumes execution at the line after its closing brace. Consequently,
execution can never fall into a function from above, nor does the
presence of one or more functions at the very top of a script affect
the auto-execute section.
*libraries_of_functions*
Libraries of Functions: Standard Library and User Library [v1.0.47+] ~
A script may call a function in an external file without having to use
|#Include|. For this to work, a file of the same name as the function
must exist in one of the following library directories:
>
%A_ScriptDir%\Lib\ ; Local library - requires AHK_L 42+.
%A_MyDocuments%\AutoHotkey\Lib\ ; User library.
path-to-the-currently-running-AutoHotkey.exe\Lib\ ; Standard library.
<
For example, if a script calls a nonexistent function MyFunc(), the
program searches for a file named "MyFunc.ahk" in the user library. If
not found there, it searches for it in the standard library. If a
match is still not found and the function's name contains an
underscore (e.g. MyPrefix_MyFunc the program searches both libraries
for a file named MyPrefix.ahk and loads it if it exists. This allows
MyPrefix.ahk to contain both the function MyPrefix_MyFunc and other
related functions whose names start with MyPrefix_.
[AHK_L 42+]: The local library is supported and is searched before the
user library and standard library.
Although a library file generally contains only a single function of
the same name as its filename, it may also contain private functions
and subroutines that are called only by it. However, such functions
should have fairly distinct names because they will still be in the
global namespace; that is, they will be callable from anywhere in the
script.
If a library file uses |#Include|, the working directory for
|#Include| is the library file's own directory. This can be used to
create a redirect to a larger library file that contains that function
and others related to it.
The script compiler ( ahk2exe ) also supports library functions.
However, it requires that a copy of AutoHotkey.exe exist in the
directory above the compiler directory (which is normally the case).
If AutoHotkey.exe is absent, the compiler still works but library
functions are not automatically included.
Functions included from a library perform just as well as other
functions because they are pre-loaded before the script begins
executing.
Built-in Functions~
Any optional parameters at the end of a built-in function's parameter
list may be completely omitted. For example,
>
WinExist("Untitled - Notepad")
<
is valid because its other three parameters would be considered blank.
A built-in function is overridden if the script defines its own
function of the same name. For example, a script could have its own
custom |WinExist|() function that is called instead of the standard
one. However, the script would then have no way to call the original
function.
External functions that reside in DLL files may be called with
|DllCall|().
Frequently-used Functions~
|FileExist|(FilePattern)
Returns a blank value (empty string) if |FilePattern| does not exist
(FilePattern is assumed to be in A_WorkingDir if an absolute path
isn't specified). Otherwise, it returns the attribute string (a subset
of "RASHNDOCT") of the first matching file or folder. If the file has
no attributes (rare), "X" is returned. FilePattern may be the exact
name of a file or folder, or it may contain wildcards (* or ?). Since
an empty string is seen as "false", the function's return value can
always be used as a quasi-boolean value. For example, the statement
>
if FileExist("C:\My File.txt")
<
would be true if the file exists and false otherwise. Similarly, the
statement
>
if InStr(FileExist("C:\My Folder"), "D")
<
would be true only if the file exists and is a directory.
Corresponding commands: |IfExist| and |FileGetAttrib|.
|GetKeyState|(KeyName [, "P" or "T"])
Unlike the |GetKeyState| command -- which returns D for down and U for
up -- this function returns true (1) if the key is down and false (0)
if it is up. If |KeyName| is invalid, an empty string is returned.
See |GetKeyState| for other return values and other usage information.
|InStr|( Haystack, Needle [, CaseSensitive = false, StartingPos = 1,
Occurrence = 1])
Returns the position of an occurrence of the string Needle in the
string Haystack. Unlike |StringGetPos|, position 1 is the first
character; this is because 0 is synonymous with "false", making it an
intuitive "not found" indicator. If the parameter CaseSensitive is
omitted or false, the search is not case sensitive (the method of
insensitivity depends on |StringCaseSense|); otherwise, the case must
match exactly. If StartingPos is omitted, it defaults to 1 (the
beginning of Haystack). Otherwise, specify 2 to start at Haystack 's
second character, 3 to start at the third, etc. If StartingPos is
beyond the length of Haystack, 0 is returned. If StartingPos is 0 or
negative, the search is conducted in reverse (right-to-left) beginning
at that offset from the end. Regardless of the value of StartingPos,
the returned position is always relative to the first character of
Haystack. For example, the position of "abc" in "123abc789" is always
4. Specify 2 for Occurrence to return the position of the second
match, 3 for the third match, etc. Related items: |RegExMatch|(),
|IfInString|, and |StringGetPos|.
|RegExMatch|( Haystack, NeedleRegEx [, UnquotedOutputVar = "",
StartingPos = 1])
Determines whether a string contains a pattern (regular expression).
See |RegExMatch|() for details.
*SubStr* ( String, StartingPos [, Length ]) [v1.0.46+]
Copies a substring from String starting at StartingPos and proceeding
rightward to include at most Length characters (if Length is omitted,
it defaults to "all characters"). For StartingPos, specify 1 to start
at the first character, 2 to start at the second, and so on (if
StartingPos is beyond String's length, an empty string is returned).
If StartingPos is less than 1, it is considered to be an offset from
the end of the string. For example, 0 extracts the last character and
-1 extracts the two last characters (but if StartingPos tries to go
beyond the left end of the string, the extraction starts at the first
character). Length is the maximum number of characters to retrieve
(fewer than the maximum are retrieved whenever the remaining part of
the string is too short). Specify a negative Length to omit that many
characters from the end of the returned string (an empty string is
returned if all or too many characters are omitted). Related items:
|RegExMatch|(), |StringMid|, |StringLeft| / |Right|, |StringTrimLeft|
/ |Right|.
|StrLen|(String)
Returns the length of String. See |StrLen|() for details.
|WinActive|([ WinTitle, WinText, ExcludeTitle, ExcludeText])
Returns the Unique ID ( HWND ) of the active window if it matches the
specified criteria. If it does not, the function returns 0. Since all
non-zero numbers are seen as "true", the statement
>
if WinActive("WinTitle")
<
is true whenever WinTitle is active. The parameter WinTitle supports
ahk_id, ahk_class, and other special strings. See |IfWinActive| for
details about these and other aspects of window activation. Note: An
easy way to retrieve the unique ID of the active window is with
>
ActiveHwnd := WinExist("A")
<
|WinExist|([ WinTitle, WinText, ExcludeTitle , ExcludeText])
Returns the Unique ID ( HWND ) of the first matching window. See
|WinExist|() for details.
Miscellaneous Functions~
*Asc* ( String )
Returns the character code (a number between 1 and 255 (in ANSI
builds) or 65535 (in Unicode builds)) for the first character in
String. If String is empty, 0 is returned.
*Chr* ( Number )
Returns the single character corresponding to the character code
indicated by Number. If Number is not in the valid range of character
codes, an empty string is returned. Common character codes include 9
(tab), 10 (linefeed), 13 (carriage return), 32 (space), 48-57 (the
digits 0-9), 65-90 (uppercase A-Z), and 97-122 (lowercase a-z).
|DllCall|()
Calls a function inside a DLL, such as a standard Windows API
function. See |DllCall|() for details.
|FileOpen|()
Provides object-oriented file I/O. See |FileOpen|() for details.
|Func|(FunctionName) [v1.1.00+]
If FunctionName does not exist explicitly in the script (by means such
as |#Include| or a non-dynamic call to a library function), Func()
returns 0. Otherwise, it returns a reference to the function. This
can be used to call the function or retrieve information such as the
minimum and maximum number of parameters.
|GetKeyName|( Key ), |GetKeyVK| ( Key ), |GetKeySC|( Key ) [v1.1.01+]
Retrieves the name/text, virtual key code or scan code of a key. Key
can be a VK or SC code, such as "vkA2" or "sc01D", a combination of
both, or a key name. For example, both
>
GetKeyName|("vk1B")
<
and
>
GetKeyName|("Esc")
<
return "Escape", while
>
GetKeyVK|("Esc")
<
returns 27.
|IsByRef|( Var ) [v1.1.01+]
Returns 1 if Var is a ByRef parameter and the caller supplied a
variable; or 0 if Var is any other kind of variable.
|IsFunc|( FunctionName ) [v1.0.48+]
If FunctionName does not exist explicitly in the script (by means such
as |#Include| or a non-dynamic call to a library function), IsFunc()
returns 0. Otherwise, it returns one plus the minimum number
parameters (e.g. 1 for a function that requires zero parameters, 2 for
a function that requires 1 parameter, etc.). For example, the
statements if
>
IsFunc("MyFunc")
<
and
>
if IsFunc(VarContainingFunctionName)
<
would be true if the function exists, and false otherwise. In
v1.1.00+, FunctionName can be a function reference instead of a name.
See also: Dynamic function-call, A_ThisFunc
|IsLabel|( LabelName )
Returns a non-zero number if LabelName exists in the script as a
subroutine, hotkey, or hotstring (do not include the trailing
colon(s) in LabelName). For example, the statement if
>
IsLabel(VarContainingLabelName)
<
would be true if the label exists, and false otherwise. This is useful
to avoid runtime errors when specifying a dynamic label in commands
such as Gosub, Hotkey, Menu, and Gui. See also: Labels.
|IsObject|() [AHK_L 31+]
Determines if a value is an object. See also: |Objects|.
ListView and TreeView functions~
See the |ListView| and |TreeView| pages for details.
|NumGet|(VarOrAddress [, Offset = 0][, Type = "UPtr"]) [v1.0.47+]
Returns the binary number stored at the specified address+offset. For
VarOrAddress , passing
>
MyVar
<
is equivalent to passing
>
&MyVar
<
However, omitting the "&" performs better and ensures that the target
address is valid (invalid addresses return ""). By contrast, anything
other than a naked variable passed to VarOrAddress is treated as a
raw address; consequently, specifying
>
MyVar+0
<
forces the number in MyVar to be used instead of the address of MyVar
itself. For Type , specify UInt, Int, Int64, Short, UShort, Char,
UChar, Double, Float or Ptr (though unlike DllCall, these must be
enclosed in quotes when used as literal strings); for details see
DllCall Types. [AHK_L 57+]: Offset may be omitted entirely; for
instance,
>
NumGet(var, "int")
<
is valid.
|NumPut|(Number, VarOrAddress [, Offset = 0][, Type = "UPtr"])
[v1.0.47+]: Stores Number in binary format at the specified
address+offset and returns the address to the right of the item just
written. For |VarOrAddress|, passing
>
MyVar
<
is equivalent to passing
>
&MyVar
<
However, omitting the "&" performs better and ensures that the target
address is valid (invalid addresses return ""). By contrast, anything
other than a naked variable passed to VarOrAddress is treated as a raw
address; consequently, specifying
>
MyVar+0
<
forces the number in MyVar to be used instead of the address of MyVar
itself. For Type, specify UInt, Int, Int64, Short, UShort, Char,
UChar, Double, Float or Ptr (though unlike DllCall, these must be
enclosed in quotes when used as literal strings) (UInt64 is supported
in v1.0.48+); for details see DllCall Types . If an integer is too
large to fit in the specified Type, its most significant bytes are
ignored; e.g.
>
NumPut(257, var, 0, "Char")
<
would store the number 1. [AHK_L 57+]: Offset may be omitted
entirely; for instance,
>
NumPut(x, var, "int")
<
is valid.
|OnMessage|(MsgNumber [, "FunctionName"])
Monitors a message/event. See |OnMessage|() for details.
|StrGet|(Address [, Length ] [, Encoding = None ] ) [AHK_L 46+]
Copies a string from a memory address, optionally converting it
between code pages. See |StrGet|() for details.
|StrPut|(String, Address [, Length ] [, Encoding = None ] )
[AHK_L 46+]
Copies a string to a memory address, optionally converting it between
code pages. See |StrPut|() for details.
|RegisterCallback|()
Creates a machine-code address that when called, redirects the call to
a function in the script. See |RegisterCallback|(). for details
|Trim|() [AHK_L 31+]
Trims characters from the beginning and/or end of a string. See
|Trim|() for details.
|VarSetCapacity|(UnquotedVarName [, RequestedCapacity , FillByte ])
Enlarges a variable's holding capacity or frees its memory. See
|VarSetCapacity|() for details.
General Math ~
Note: Math functions generally return a blank value (empty string) if
any of the incoming parameters are non-numeric.
*Abs*
|Abs|(Number)
Returns the absolute value of Number. The return value is the same
type as Number (integer or floating point).
*Ceil*
|Ceil|(Number)
Returns Number rounded up to the nearest integer (without any .00
suffix). For example,
>
Ceil(1.2)
<
is 2 and
>
Ceil(-1.2)
<
is -1.
*Exp*
|Exp|(N)
Returns e (which is approximately 2.71828182845905) raised to the Nth
power. N may be negative and may contain a decimal point. To raise
numbers other than e to a power, use the ** operator.
*Floor*
|Floor|(Number)
Returns Number rounded down to the nearest integer (without any .00
suffix). For example,
>
Floor(1.2)
<
is 1 and
>
Floor(-1.2)
is -2.
*Log*
|Log|(Number)
Returns the logarithm (base 10) of Number. The result is formatted as
floating point. If Number is negative, an empty string is returned.
*Ln*
|Ln|(Number)
Returns the natural logarithm (base e) of Number. The result is
formatted as floating point. If Number is negative, an empty string is
returned.
*Mod*
|Mod|(Dividend, Divisor)
Modulo. Returns the remainder when Dividend is divided by Divisor.
The sign of the result is always the same as the sign of the first
parameter. For example, both
>
mod(5, 3)
<
and
>
mod(5, -3)
<
yield 2, but
>
mod(-5, 3)
<
and
>
mod(-5, -3)
<
yield -2. If either input is a floating point number, the result is
also a floating point number. For example,
>
mod(5.0, 3)
<
is 2.0 and
>
mod(5, 3.5)
<
is 1.5. If the second parameter is zero, the function yields a blank
result (empty string).
*Round*
|Round|(Number [, N])
If N is omitted or 0, Number is rounded to the nearest integer. If N
is positive number, Number is rounded to N decimal places. If N is
negative, Number is rounded by N digits to the left of the decimal
point. For example,
>
Round(345, -1)
<
is 350 and
>
Round (345, -2)
<
is 300. Unlike Transform Round, the result has no .000 suffix whenever
N is omitted or less than 1. In v1.0.44.01+, a value of N greater than
zero displays exactly N decimal places rather than obeying
|SetFormat|. To avoid this, perform another math operation on
Round()'s return value; for example:
>
Round(3.333, 1)+0
<
*Sqrt*
|Sqrt|(Number)
Returns the square root of Number. The result is formatted as
floating point. If Number is negative, the function yields a blank
result (empty string).
Trigonometry~
*Sin*
*Cos*
*Tan*
|Sin|(Number) | |Cos|(Number) | |Tan|(Number)
Returns the trigonometric sine | cosine | tangent of Number. Number
must be expressed in radians.
*ASin*
*ACos*
*ATan*
|ASin|(Number)
Returns the arcsine (the number whose sine is Number) in radians. If
Number is less than -1 or greater than 1, the function yields a blank
result (empty string).
|ACos|(Number)
Returns the arccosine (the number whose cosine is Number) in radians.
If Number is less than -1 or greater than 1, the function yields a
blank result (empty string).
|ATan|(Number)
Returns the arctangent (the number whose tangent is Number) in
radians.
Note: To convert a radians value to degrees, multiply it by 180/pi
(approximately 57.29578). To convert a degrees value to radians,
multiply it by pi/180 (approximately 0.01745329252). The value of pi
(approximately 3.141592653589793) is 4 times the arctangent of 1.
Other Functions~
Polyethene's Command Functions
Provides a callable function for each AutoHotkey command that has an
OutputVar. This library can be included in any script via |#Include|.
==============================================================================
*For-loop*
For-loop~
------------------------------------------------------------------------------
Repeats a series of commands once for each key-value pair in an
object.
|For| Key [, Value ] in Expression
Parameters~
Key
-----
Name of the variable in which to store the key at the beginning of
each iteration.
Value
-----
Name of the variable in which to store the value associated with the
current key.
Expression
----------
An expression which results in an object, or a variable which contains
an object.
Remarks~
Expression is evaluated only once, before the loop begins. If its
result is not an object, execution jumps immediately to the line
following the loop's body; otherwise, the object's
>
_NewEnum()
<
method is called to retrieve an enumerator object. At the beginning of
each iteration, the enumerator's Next() method is used to retrieve the
next key-value pair. If Next() returns zero or an empty string, the
loop terminates.
Although not exactly equivalent to a for-loop, the following
demonstrates this process:
>
_enum := (Expression)._NewEnum()
if IsObject(_enum)
while _enum.Next(Key, Value)
{
...
}
<
Existing key-value pairs may be modified during the loop, but
inserting or removing keys may cause some items to be skipped or
enumerated multiple times. One workaround is to build a list of keys
to remove, then use a second loop to remove the keys after the first
loop completes. Note that
>
Object.Remove(first, last)
<
can be used to remove a range of keys without looping.
A for-loop is usually followed by a block, which is a collection of
statements that form the body of the loop. However, a loop with only a
single statement does not require a block (an "if" and its "else"
count as a single statement for this purpose). The One True Brace
(OTB) style may optionally be used, which allows the open-brace to
appear on the same line rather than underneath. For example:
>
for x, y in z {
<
As with all loops, |Break|, |Continue| and A_Index may be used.
COM Objects~
Since Key and Value are passed directly to the enumerator's Next()
method, the values they are assigned depends on what type of object is
being enumerated. For COM objects, Key contains the value returned by
IEnumVARIANT::Next() and Value contains a number which represents its
variant type. For example, when used with a Scripting.Dictionary
object, each Key contains a key from the dictionary and Value is
typically 8 for strings and 3 for integers. See ComObjType for a list
of type codes.
[v1.0.96.00+]: When enumerating a SafeArray, Key contains the current
element and Value contains its variant type.
Related~
Enumerator object, Object.NewEnum() , |While|-loop, |Loop|, |Until|,
|Break|, |Continue|, Blocks
Examples~
>
; List the key-value pairs of an object:
colours := Object("red", 0xFF0000, "blue", 0x0000FF, "green", 0x00FF00)
; The above expression could be used directly in place of "colours" below:
for k, v in colours
s .= k "=" v "`n"
MsgBox % s
<
>
>
; List all open Explorer and Internet Explorer windows:
for window in ComObjCreate("Shell.Application").Windows
windows .= window.LocationName " :: " window.LocationURL "`n"
MsgBox % windows
>
/*
Class: CEnumerator
Generic enumerator object that can be used for iterating over
numeric keys. The array must not be modified during
iteration, otherwise the iterated range will be invalid. It's
possible to define a custom MaxIndex() functions for array
boundaries. If there are missing array members between 1 and
max index, they will be iterated but will have a value of "".
This means that real sparse arrays are not supported by this
enumerator by design. To make an object use this iterator,
insert this function in the class definition:
_NewEnum()
{
return new CEnumerator(this)
}
Source: http://www.autohotkey.com/board/topic/2667-suggestions-on-documentation-improvements/?p=531509
*/
; Iterate over the enumerator
For k, v in Test
MsgBox %k%=%v%
; Test class for demonstrating usage
class Test
{
static Data := ["abc", "def", "ghi"]
_NewEnum()
{
return new CEnumerator(this.Data)
}
}
class CEnumerator
{
__New(Object)
{
this.Object := Object
this.first := true
; Cache for speed. Useful if custom MaxIndex() functions have poor performance.
; In return, that means that no key-value pairs may be inserted during iteration or the range will become invalid.
this.ObjMaxIndex := Object.MaxIndex()
}
Next(ByRef key, ByRef value)
{
if (this.first)
{
this.Remove("first")
key := 1
}
else
key ++
if (key <= this.ObjMaxIndex)
value := this.Object[key]
else
key := ""
return key != ""
}
}
<
==============================================================================
*SetTitleMatchMode*
+-------------------+~
| SetTitleMatchMode |~
+-------------------+~
Sets the matching behavior of the WinTitle parameter in commands such
as |WinWait|. Personal Note: seems to reset itself when you re-enter
the script e.g through a Hotkey
|SetTitleMatchMode|, MatchMode
|SetTitleMatchMode|, Fast | Slow
Parameters~
MatchMode
---------
One of the following digits or the word RegEx:
1: A window's title must start with the specified WinTitle to be a match.
2: A window's title can contain WinTitle anywhere inside it to be a match.
3: A window's title must exactly match WinTitle to be a match.
RegEx (v1.0.45+): Changes |WinTitle|, |WinText|, ExcludeTitle, and
ExcludeText to be regular expressions. Do not enclose such expressions
in quotes when using them with commands. For example:
>
WinActivate Untitled.*Notepad
<
RegEx also applies to ahk_class ; for example,
>
ahk_class IEFrame
<
searches for any window whose class name contains IEFrame anywhere
(this is because by default, regular expressions find a match
anywhere in the target string). Note: For |WinText|, each text element
(i.e. each control's text) is matched against the RegEx separately.
Therefore, it is not possible to have a match span more than one text
element.
The modes above also affect |ExcludeTitle| in the same way as |WinTitle|.
For example, mode 3 requires that a window's title exactly match
ExcludeTitle for that window to be excluded.
Fast | Slow ~
Fast
-----
This is the default behavior. Performance may be substantially better
than Slow, but certain WinText elements for some types of windows may
not be "seen" by the various window commands.
Slow
-----
Can be much slower, but all possible WinText is retrieved from every
window as a windowing command searches through them for a match.
Window Spy reveals which parts of a Window's text (if any) require the
slow mode.
Remarks~
This command affects the behavior of all windowing commands, e.g.
|IfWinExist| and |WinActivate|.
If unspecified, TitleMatchMode defaults to 1 and fast.
If a window group is used, the current title match mode applies to
each individual rule in the group.
Generally, the slow mode should be used only if the target window
cannot be uniquely identified by its title and fast-mode text. This is
because the slow mode can be extremely slow if there are any
application windows that are busy or "not responding".
The customized version of Window Spy distributed with AutoHotkey
reports slow text in a separate section so that its easy to determine
whether the slow mode is needed.
If you wish to change both attributes, run the command twice as in
this example:
>
SetTitleMatchMode, 2
SetTitleMatchMode, slow
<
The built-in variables A_TitleMatchMode and A_TitleMatchModeSpeed
contain the current settings.
Regardless of the current TitleMatchMode, |WinTitle|, |WinText|,
ExcludeTitle and ExcludeText are case sensitive. The only exception is
the case - insensitive option of the RegEx mode; for example:
>
"i)untitled - notepad"
<
Every newly launched thread (such as a hotkey, custom menu item, or
timed subroutine) starts off fresh with the default setting for this
command. That default may be changed by using this command in the
auto-execute section (top part of the script).
Related~
|SetWinDelay|, |IfWinExist|, |WinActivate|, |RegExMatch|()
Example~
>
SetTitleMatchMode 2
; OR:
SetTitleMatchMode RegEx
SetTitleMatchMode Slow ; Slow/Fast can be set independently of all the other modes.
<
==============================================================================
*SetTimer*
+----------+~
| SetTimer |~
+----------+~
Causes a subroutine to be launched automatically and repeatedly at a
specified time interval.
|SetTimer| [, Label, Period On Off, Priority ]
Parameters~
Label
-----
The name of the label or hotkey label to which to jump, which causes
the commands beneath Label to be executed until a |Return| or |Exit|
is encountered. As with the parameters of almost all other commands,
Label can be a variable reference such as %MyLabel%, in which case
the name stored in the variable is used as the target.
[v1.1.01+]: If Label is omitted,
>
A_ThisLabel
<
will be used. For example, |SetTimer|,, Off can be used inside a timer
subroutine to turn off the timer.
Period | On | Off ~
On
-----
Re-enables a previously disabled timer at its former period. If the
timer doesn't exist, it is created (with a default period of 250). If
the timer exists but was previously set to run-only-once mode, it will
again run only once.
Off
-----
Disables an existing timer.
Period
------
Creates or updates a timer using this parameter as the approximate
number of milliseconds that must pass since the last time the Label
subroutine was started. When this amount of time has passed, Label
will be run again (unless it is still running from the last time). The
timer will be automatically enabled. To prevent this, call the command
a second time immediately afterward, specifying OFF for this
parameter.
If this parameter is blank and: 1) the timer does not exist: it will
be created with a period of 250. 2) the timer already exists: it will
be enabled and reset at its former period unless a Priority is
specified.
Run only once [v1.0.46.16+]: Specify a negative Period to indicate
that the timer should run only once. For example, specifying -100
would run the timer 100 ms from now then disable the timer as though
>
SetTimer, Label, Off
<
had been used.
Priority
--------
This optional parameter is an integer between -2147483648 and
2147483647 (or an expression) to indicate this timer's thread
priority. If omitted, 0 will be used. See Threads for details.
To change the priority of an existing timer without affecting it in
any other way, leave the parameter before this one blank.
Remarks~
Timers are useful because they run asynchronously, meaning that they
will run at the specified frequency (interval) even when the script is
waiting for a window, displaying a dialog, or busy with another task.
Examples of their many uses include taking some action when the user
becomes idle (as reflected by A_TimeIdle) or closing unwanted windows
the moment they appear.
Although timers may give the illusion that the script is performing
more than one task simultaneously, this is not the case. Instead,
timed subroutines are treated just like other threads: they can
interrupt or be interrupted by another thread, such as a hotkey
subroutine. See Threads for details.
Whenever a timer is created, re-enabled, or updated with a new period,
its subroutine will not run right away; its time period must expire
first. If you wish the timer's first execution to be immediate, use
Gosub to execute the timer's subroutine (however, this will not start
a new thread like the timer itself does; so settings such as
|SendMode| will not start off at their defaults).
If SetTimer is used on an existing timer and parameter #2 is a number
or the word ON (or it is omitted), the timer's internal "time it was
last run" will be reset to the current time; in other words, the
entirety of its period must elapse before its subroutine will run
again.
Timer precision: Due to the granularity of the OS's time-keeping
system, Period is typically rounded up to the nearest multiple of 10
or 15.6 milliseconds (depending on the type of hardware and drivers
installed). For example, a Period between 1 and 10 (inclusive) is
usually equivalent to 10 or 15.6 on Windows NT/2000/XP (Windows 9x
uses ~55ms). A shorter delay may be achieved via Loop+Sleep as
demonstrated at DllCall+timeBeginPeriod+Sleep.
A timer might not be able to run as often as specified under the
following conditions:
1. Other applications are putting a heavy load on the CPU.
2. The timer subroutine itself takes longer than its own period to
run, or there are too many other competing timers (altering
|SetBatchLines| may help).
3. The timer has been interrupted by another thread, namely another
timed subroutine, hotkey subroutine, or custom menu item (this can be
avoided via Critical). If this happens and the interrupting thread
takes a long time to finish, the interrupted timer will be effectively
disabled for the duration. However, any other timers will continue to
run by interrupting the thread that interrupted the first timer.
4. The script is uninterruptible as a result of Critical or Thread
Interrupt /Priority. During such times, timers will not run. Later,
when the script becomes interruptible again, any overdue timer will
run once as soon as possible and then resume its normal schedule.
Although timers will operate when the script is suspended, they will
not run if the current thread has "Thread NoTimers" in effect or
whenever any thread is paused. In addition, they do not operate when
the user is navigating through one of the script's menus (such as the
tray icon menu or a menu bar).
Because timers operate by temporarily interrupting the script's
current activity, their subroutines should be kept short (so that they
finish quickly) whenever a long interruption would be undesirable.
Timers that stay in effect for the duration of a script should usually
be created in the auto-execute section. By contrast, a temporary timer
might often be disabled by its own subroutine (see examples at the
bottom of this page).
Whenever a timed subroutine is run, it starts off fresh with the
default values for settings such as |SendMode|. These defaults can be
changed in the auto-execute section.
If hotkey response time is crucial (such as in games) and the script
contains any timers whose subroutines take longer than about 5 ms to
execute, use the following command to avoid any chance of a 15 ms
delay. Such a delay would otherwise happen if a hotkey is pressed at
the exact moment a timer thread is in its period of
uninterruptibility:
>
Thread, interrupt, 0 ; Make all threads always-interruptible.
<
If a timer is disabled while its subroutine is currently running, that
subroutine will continue until it completes.
The KeyHistory feature shows how many timers exist and how many are
currently enabled.
A timer's period can be no larger than 4294967295 milliseconds (49.7
days).
To keep a script running -- such as one that contains only timers --
use #Persistent.
Related~
|Gosub|, |Return|, Threads, |Thread| (command), |Critical|,
|IsLabel|(), |Menu|, |#Persistent|
Examples~
>
; Example #1: Close unwanted windows whenever they appear:
#Persistent
SetTimer, CloseMailWarnings, 250
return
CloseMailWarnings:
WinClose, Microsoft Outlook, A timeout occured while communicating
WinClose, Microsoft Outlook, A connection to the server could not be established
return
<
>
; Example #2: Wait for a certain window to appear and then alert the user:
#Persistent
SetTimer, Alert1, 500
return
Alert1:
IfWinNotExist, Video Conversion, Process Complete
return
; Otherwise:
SetTimer, Alert1, Off ; i.e. the timer turns itself off here.
SplashTextOn, , , The video conversion is finished.
Sleep, 3000
SplashTextOff
return
<
>
; Example #3: Detection of single, double, and triple-presses of a hotkey. This
; allows a hotkey to perform a different operation depending on how many times
; you press it:
#c::
if winc_presses > 0 ; SetTimer already started, so we log the keypress instead.
{
winc_presses += 1
return
}
; Otherwise, this is the first press of a new series. Set count to 1 and start
; the timer:
winc_presses = 1
SetTimer, KeyWinC, 400 ; Wait for more presses within a 400 millisecond window.
return
KeyWinC:
SetTimer, KeyWinC, off
if winc_presses = 1 ; The key was pressed once.
{
Run, m:\ ; Open a folder.
}
else if winc_presses = 2 ; The key was pressed twice.
{
Run, m:\multimedia ; Open a different folder.
}
else if winc_presses > 2
{
MsgBox, Three or more clicks detected.
}
; Regardless of which action above was triggered, reset the count to
; prepare for the next series of presses:
winc_presses = 0
return
<
==============================================================================
*WinTitle_Parameter_and_Last_Found_Window*
The WinTitle Parameter & the Last Found Window~
------------------------------------------------------------------------------
Many commands and a few functions have a |WinTitle| parameter, used to
identify which window (or windows) to operate on. This parameter can
be the title or partial title of the window, and/or any other criteria
described on this page.
Quick Reference: ~
Title Matching Behaviour ~
A The Active Window
ahk_class Window Class
ahk_id Unique ID/HWND
ahk_pid Process ID
ahk_exe Process Name/Path
ahk_group Window Group
Multiple Criteria
(All empty) Last Found Window
Matching Behaviour~
SetTitleMatchMode controls how a partial or complete title is compared
against the title of each window. Depending on the setting, WinTitle
can be an exact title, or it can contain a prefix, a substring which
occurs anywhere in the title, or a RegEx pattern. This setting also
controls whether ahk_class is interpreted as an exact class name or a
RegEx pattern.
Hidden windows are only detected if DetectHiddenWindows is On, except
with |WinShow|, which always detects hidden windows.
If multiple windows match the |WinTitle| and any other criteria, the
topmost matching window is used. If the active window matches the
criteria, it usually takes precedence since it is usually above all
other windows. However, if an always-on-top window also matches (and
the active window is not always-on-top), it may be used instead.
Active Window (A)~
If WinTitle is the letter A and the other 3 window parameters
(|WinText|, ExcludeTitle and ExcludeText) are blank or omitted, the
active window will be used.
>
; Retrieve the ID/HWND of the active window
id := WinExist("A")
MsgBox % id
; Press Win+? to maximize the active window
#Up::WinMaximize, A
<
ahk_class Window Class~
A window class is a set of attributes that the system uses as a
template to create a window. In other words, the class name of the
window identifies what type of window it is. To use a window class,
specify
>
ahk_class ExactClassName
<
as shown by Window Spy. ExactClassName can be retrieved by
|WinGetClass|.
If the RegEx title matching mode is active, ahk_class accepts a
regular expression.
>
; Activate a console window (e.g. cmd.exe)
WinActivate, ahk_class ConsoleWindowClass
<
ahk_id Unique ID / HWND~
Each window or control has a unique ID, also known as a HWND (short
for handle to window). This ID can be used to identify the window or
control even if its title changes. The ID of a window is typically
retrieved via |WinExist|() or WinGet. The ID of a control is typically
retrieved via |ControlGet| Hwnd, |MouseGetPos|, or |DllCall|. Also,
ahk_id will operate on controls even if they are hidden; that is, the
setting of DetectHiddenWindows does not matter for controls.
>
WinActivate, ahk_id %VarContainingID%
<
ahk_pid Process ID~
Use ahk_pid to identify a window belonging to a specific process. The
process identifier (PID) is typically retrieved by |WinGet|, |Run| or
|Process|.
>
WinActivate, ahk_pid %VarContainingPID%
<
ahk_exe Process Name/Path [v1.1.01+]~
Use ahk_exe to identify a window belonging to any process with the
given name or path.
While ahk_pid is limited to one specific process, ahk_exe considers
all processes with name or full path matching a given string. If the
RegEx title matching mode is active, ahk_exe accepts a regular
expression. Otherwise, ahk_exe accepts a case-insensitive name or full
path; for example,
>
ahk_exe notepad.exe
<
covers ahk_exe C:\Windows\Notepad.exe, ahk_exe
C:\Windows\System32\Notepad.exe and other variations.
>
; Activate an existing notepad.exe window, or open a new one
if WinExist("ahk_exe notepad.exe")
WinActivate, ahk_exe notepad.exe
else
Run, notepad.exe
<
ahk_group Window Group~
Use ahk_group to identify a window or windows matching the rules
contained by a previously defined window group.
The commands |WinMinimize|, |WinMaximize|, |WinRestore|, |WinHide|,
|WinShow|, |WinClose|, and |WinKill| will act on all the group's
windows. By contrast, the other window commands such as |WinActivate|
and |IfWinExist| will operate only on the topmost window of the group.
>
; Define the group: Windows Explorer windows
GroupAdd, Explorer, ahk_class ExploreWClass ; Unused on Vista and later
GroupAdd, Explorer, ahk_class CabinetWClass
; Activate any window matching the above criteria
WinActivate, ahk_group Explorer
<
Multiple Criteria~
By contrast with ahk_group (which broadens the search), the search may
be narrowed by specifying more than one criterion within the WinTitle
parameter. In the following example, the script waits for a window
whose title contains My File.txt and whose class is Notepad:
>
WinWait My File.txt ahk_class Notepad
WinActivate ; Activate the window it found.
<
When using this method, the text of the title (if any is desired)
should be listed first, followed by one or more additional criteria.
Criteria beyond the first should be separated from the previous with
exactly one space or tab (any other spaces or tabs are treated as a
literal part of the previous criterion).
ahk_id can be combined with other criteria to test a window's title,
class or other attributes:
>
MouseGetPos,,, id
if WinExist("ahk_class Notepad ahk_id " id)
MsgBox The mouse is over Notepad.
<
The "Last Found" Window~
This is the window most recently found by |IfWinExist|,
|IfWinNotExist|, |WinExist|(), |IfWinActive|, |IfWinNotActive|,
|WinActive|(), |WinWaitActive|, |WinWaitNotActive| or |WinWait|. It
can make scripts easier to create and maintain since the WinTitle and
WinText of the target window do not need to be repeated for every
windowing command. In addition, scripts perform better because they
don't need to search for the target window again after it has been
found the first time.
The "last found" window can be used by all of the windowing commands
except |WinWait|, |WinActivateBottom|, and |GroupAdd|. To use it,
simply omit all four window parameters (WinTitle, WinText,
ExcludeTitle, and ExcludeText).
Each thread retains its own value of the "last found" window, meaning
that if the current thread is interrupted by another, when the
original thread is resumed it will still have its original value of
the "last found" window, not that of the interrupting thread.
If the last found window is a hidden Gui window, it can be used even
when DetectHiddenWindows is Off. This is often used in conjunction
with >
Gui +LastFound.
<
>
Run Notepad
WinWait Untitled - Notepad
WinActivate ; Uses the last found window.
IfWinExist, Untitled - Notepad
{
WinActivate ; Automatically uses the window found above.
WinMaximize ; same
Send, Some text.{Enter}
return
}
IfWinNotExist, Calculator
return
else
{
WinActivate ; The above "IfWinNotExist" also set the "last found" window for us.
WinMove, 40, 40 ; Move it to a new position.
return
}
<
==============================================================================
*GUI*
GUI~
------------------------------------------------------------------------------
see also: |Gui_Control_Types|
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~
- New ~
Creates a new window
- 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 name
- 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
Gui, New [, Options, Title] [v1.1.04]~
Creates a new window
>
Gui,New ; Creates a new unnamed GUI.
Gui,Name :New ; Creates a new GUI, destroying any existing GUI with that name.
<
For convenience, the new window is set as the default for the current
thread.
If no name is given, special labels such as |GuiClose| have the
default "Gui" prefix unless overridden by +LabelPrefix in the options.
If the GUI which launched the current thread was created this way,
A_Gui contains a HWND instead of a name. On a related note, if
+HwndOutputVar is used in the options, the HWND of the new window is
stored in OutputVar.
If a name is specified, any existing GUI with that name is destroyed.
Options can contain any of the options supported by the main GUI
command.
If Title is omitted, the script's file name is used.
Although this command is recommended for clarity, it is not mandatory.
If one of the other |Gui| sub-commands (such as |Gui,| |Add)| is used
and the GUI does not exist, it is automatically created.
Note: Prior to v1.1.08, this command did not set the default |Gui| if a
name was specified.
Gui, Add, ControlType [, Options, Text]~
Adds a control to a GUI window (first creating the GUI window itself,
if necessary).
ControlType is one of the following:
- Text, Edit, UpDown, Picture
- Button, Checkbox, Radio
- DropDownList, ComboBox
- ListBox, ListView, TreeView
- Link, Hotkey, DateTime, MonthCal
- Slider, Progress
- GroupBox, Tab, StatusBar
- ActiveX (e.g. Internet Explorer Control)
- Custom
For example:
>
Gui, Add, Text,, Please enter your name:
Gui, Add, Edit, vName
Gui, Show
<
Gui, Show [, Options, Title]~
Unless otherwise specified in |Options|, this command makes the window
visible, unminimizes it (if necessary), activates it, and sets its
title. If Title is omitted, the previous title is retained (or if
none, the script's file name is used).
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
<
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, Submit [, NoHide]~
Saves the contents of each control to its associated variable (if any)
and hides the window unless the NoHide option is present. For controls
that produce multiple fields of output, such as a multi-select
ListBox, the output uses the window's current delimiter. If the window
does not exist -- perhaps due to having been destroyed via |Gui| Destroy
-- this command has no effect.
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.
Gui, Font [, Options, FontName]~
NOTE that these options need to be specified before you Gui,Add,Text
unless you use GuiControl to make changes to the text with like
GuiControl,Font,myThisThatTextControl.
Sets the font typeface, size, style, and/or color for controls created
from this point onward. For example:
>
gui, font, s10, Verdana ; Set 10-point Verdana
<
NOTE if you wanna set the color for this font you gotta include this
in where the size is, e.g ..,s12 cRed,.. (c = color) it won't work if
you put it in with the Verdana (!! i.e WRONG ..,s12,Verdana cRed !!)
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.
Q
-----
[AHK_L 19+]: Text rendering quality. For example:
>
q3
<
Q should be followed by a number from the following table:
0 = DEFAULT_QUALITY~
Appearance of the font does not matter.
1 = DRAFT_QUALITY~
Appearance of the font is less important than when the PROOF_QUALITY
value is used.
2 = PROOF_QUALITY~
Character quality of the font is more important than exact matching of
the logical-font attributes.
3 = NONANTIALIASED_QUALITY~
Font is never antialiased, that is, font smoothing is not done.
4 = ANTIALIASED_QUALITY ~
ont is antialiased, or smoothed, if the font supports it and the size
of the font is not too small or too large.
5 = CLEARTYPE_QUALITY~
Windows XP and later: If set, text is rendered (when possible) using
ClearType antialiasing method.
For more details of what these values mean, see MSDN: |CreateFont|.
Since the highest quality setting is usually the default, this feature
is more typically used to disable anti-aliasing in specific cases
where doing so makes the text clearer.
Gui, Color [, WindowColor, ControlColor]~
Sets the background color of the window and/or its controls.
WindowColor is used as the background for the GUI window itself.
ControlColor is applied to all present and future controls in the
window (though some types of controls do not support a custom color).
Although ControlColor is initially obeyed by ListViews and
TreeViews, subsequent changes to ControlColor do not affect them. In
such cases, use
>
GuiControl +BackgroundFF9977, MyListView
<
to explicitly change the color.
Leave either parameter blank to retain the current color. Otherwise,
specify one of the 16 primary HTML color names or a 6-digit RGB color
value (the 0x prefix is optional), or specify the word Default to
return either to its default color. Example values:
>
Silver
FFFFAA
0xFFFFAA
Default
<
By default, the window's background color is the system's color for
the face of buttons, and the controls' background color is the
system's default window color (usually white).
The color of the menu bar and its submenus can be changed as in this
example:
>
Menu, MyMenuBar, Color, White
<
To make the background transparent on Windows 2000/XP or later, use
|WinSet| TransColor. However, if you do this without first having
assigned a custom window via |Gui|, Color, buttons will also become
transparent. To prevent this, first assign a custom color and then
make that color transparent. For example:
>
Gui, Color, EEAA99
Gui +LastFound
; Make the GUI window the last found window for use by
; the line below.
WinSet, TransColor, EEAA99
<
To additionally remove the border and title bar from a window with a
transparent background, use the following after the window has been
made transparent:
>
Gui -Caption ; Or use Gui, GuiName:-Caption if it isn't the default window.
<
To illustrate the above, there is an example of an on-screen display
(OSD) near the bottom of this page.
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 auto-positioning 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 font-height 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.
Gui, +/-Option1 +/-Option2 ...~
One or more options may be specified immediately after the GUI
command. For performance reasons, it is better to set all options in a
single line, and to do so before creating the window (that is, before
any use of other sub-commands such as |Gui| Add).
The effect of this command is cumulative; that is, it alters only
those settings that are explicitly specified, leaving all the others
unchanged.
Specify a plus sign to add the option and a minus sign to remove it.
For example:
>
Gui +Resize -MaximizeBox ; Change the settings of the default GUI window.
Gui MyGui:+Resize -MaximizeBox ; Change the settings of the
; GUI named MyGui.
<
AlwaysOnTop
-----------
Makes the window stay on top of all other windows, which is the same
effect as WinSet AlwaysOnTop.
Border
------
Provides a thin-line border around the window. This is not common.
Caption
-------
(present by default): Provides a title bar and a thick window
border/edge. When removing the caption from a window that will use
|WinSet| TransColor, remove it only after setting the |TransColor|.
Delimiter
---------
Specifies that the window should use a field separator other than pipe
(|) whenever controls' contents are added via |Gui| Add, modified via
|GuiControl|, or retrieved via |Gui| Submit or |GuiControlGet|.
Specify a single character immediately after the word Delimiter. For
example,
>
Gui +Delimiter`n
<
would use a linefeed character, which might be especially appropriate
with continuation sections. Similarly,
>
Gui +Delimiter|
<
would revert to the default delimiter. To use space or tab, specify
Gui +DelimiterSpace or
>
Gui +DelimiterTab
<
Once the delimiter is changed, it affects all existing and subsequent
threads that operate on this particular window.
Disabled
--------
Disables the window, which prevents the user from interacting with its
controls. This is often used on a window that owns other windows (see
Owner).
HwndOutputVar
-------------
[v1.1.04+]: This option stores the window handle (HWND) of the GUI in
OutputVar. For example:
>
Gui +HwndMyGuiHwnd
<
When within a function, MyGuiHwnd is treated as a function dynamic
variable. A GUI's HWND is often used with |PostMessage|,
|SendMessage|, and |DllCall|. It can also be used directly as an
ahk_id WinTitle or in place of a GUI name; for example,
>
Gui %MyGuiHwnd%:Destroy
<
Label
-----
[v1.0.44.09+]: Sets custom names for this window's special labels for
example,
>
Gui MyGui:+LabelMyGui_On
<
would use the labels MyGui_OnClose and MyGui_OnSize (if they exist)
instead of MyGuiGuiClose and MyGuiGuiSize. In other words, the string
"MyGuiGui" is replaced by "MyGui_On" in the names of all special
labels. This can also be used to make multiple windows share the same
set of labels (in which case the script may consult A_Gui to
determine which window launched the subroutine).
LastFound
---------
Sets the window to be the last found window (though this is
unnecessary in a Gui thread because it is done automatically), which
allows commands such as |WinSet| to operate on it even if it is
hidden (that is, DetectHiddenWindows is not necessary). This is
especially useful for changing the properties of the window before
showing it. For example:
>
Gui +LastFound
WinSet, TransColor, %CustomColor% 150
Gui Show
<
LastFoundExist [v1.0.43.09+]: Unlike other options, LastFoundExist is
recognized only when no other options appear on the same line.
+LastFoundExist is the same as +LastFound except that the window is
not created if it does not already exist. The main use for this is to
detect whether a particular GUI window exists. For example:
>
Gui MyGui:+LastFoundExist
IfWinExist
MsgBox GUI "MyGui" already exists.
<
MaximizeBox
-----------
Enables the maximize button in the title bar. This is also included as
part of Resize below.
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 name prefix is specified -- such as using
>
Gui +OwnDialogs
<
rather than
>
Gui MyGui:+OwnDialogs
<
-- the thread's default window will own the dialogs.
Owner
-----
Use +Owner to make the window owned by another. 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 v1.1.05
and later allow it to be used before or after the owned window is
created. There are two ways to use +Owner as shown in these examples:
>
Gui, MyGui:+OwnerMyOtherGui ; Make MyGui owned by MyOtherGui.
Gui, MyGui:+Owner ; Make MyGui owned by script's main window to
; prevent display of a taskbar button.
[v1.1.03+]: +Owner can be immediately followed by the name or number
of an existing Gui or the HWND of any top-level window.
Compatibility note: In v1.1.03 and later, +Owner removes the WS_CHILD
style and sets the WS_POPUP style. To set the parent window of a Gui,
scripts must either use the +Parent option, or override the
appropriate styles after the +Owner option.
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.
Parent [v1.1.03+]
------------------
Use +Parent immediately followed by the name or number of an existing
Gui or the HWND of any window or control to use it as the parent of
this window. To convert the Gui back into a top-level window, use
>
-Parent
<
This option works even after the window is created.
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
when it is created.
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.
Gui, Menu [, MenuName]~
Attaches a menu bar to the window. Use the Menu command to create an
ordinary menu for this purpose. For example:
>
Menu, FileMenu, Add, &Open`tCtrl+O, MenuFileOpen ; See remarks below about Ctrl+O.
Menu, FileMenu, Add, E&xit, MenuHandler
Menu, HelpMenu, Add, &About, MenuHandler
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.
[v1.1.04+]: If the shortcut uses only the standard modifier key names
Ctrl, Alt and Shift, it is automatically registered as a keyboard
accelerator for the GUI. Single-character accelerators with no
modifiers are case-sensitive and can be triggered by unusual means
such as IME or Alt+NNNN.
If a particular key combination does not work automatically, the use
of a context-sensitive hotkey may be required. However, such hotkeys
typically cannot be triggered by Send and are more likely to interfere
with other scripts than a standard keyboard accelerator.
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, Hide / Minimize / Maximize / Restore~
>
Gui Hide
<
is equivalent to |Gui| Cancel. The other three commands unhide the
window (if necessary) then perform the indicated operation on it. If
the window does not exist -- perhaps due to having been destroyed via
Gui Destroy -- these commands have no effect.
Gui, Flash [, Off]~
Blinks the window's button in the taskbar. This is done by inverting
the color of the window's title bar and/or taskbar button (if it has
one). The optional word OFF causes the title bar and taskbar button to
return to their original colors (but the actual behavior might vary
depending on OS version). In the below example, the window will blink
three times because each pair of flashes inverts then restores its
appearance:
>
Loop 6
{
Gui Flash
Sleep 500 ; It's quite sensitive to this value ; altering
it may change the behavior in unexpected ways.
}
<
Gui, GuiName :Default ~
Changes the current thread's default GUI window name, which is used
whenever a window name is not specified for |GuiControl|,
|GuiControlGet|, and the Gui command itself. In the following example,
the default window name is changed to "MyGui":
>
Gui MyGui:Default
<
See thread's default window for more information about the default
window
Positioning and Layout via SmartGUI Creator ~
Although the options described in the next section are suitable for
simple layouts, you may find it easier to use Rajat's SmartGUI Creator
because it's entirely visual; that is, "what you see is what you get".
SmartGUI Creator is free and can be downloaded from
www.autohotkey.com/docs/SmartGUI/
*GUI_Positioning_and_Sizing_of_Controls*
Positioning and Sizing of Controls~
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
H
-----
Height, in pixels. If both the H and R options are absent,
DropDownLists, ComboBoxes, ListBoxes, and empty multi-line 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:
gui, add, edit, ys ; Start a new column within this section.
gui, add, edit
gui, show
<
The converse of the above (specifying xs but omitting the y-position)
is also true.
xs and ys may optionally be followed by a plus/minus sign and a
number. Also, it is possible to specify both the word Section and
xs/ys in a control's options; this uses the previous section for
itself but establishes a new section for subsequent controls.
*GUI_Storing_and_Responding_to_User_Input*
Storing and Responding to User Input~
V
-----
Variable. Associates a variable with a control. Immediately after the
letter V, specify the name of a global variable (or a ByRef local that
points to a global, or a static variable in v1.0.46.01+). For example,
specifying
>
vMyEdit
<
would store the control's contents in the variable MyEdit whenever the
|Gui| Submit command is used. If a control is not input-capable --
such as a Text control or GroupBox -- associating a variable with it
can still be helpful since that variable's name serves as the
control's unique identifier for use with |GuiControl|, GuiControlGet,
and A_GuiControl. Note: |Gui| Submit does not change the contents of
variables of non-input-capable controls (such as Text and GroupBox),
nor certain others as documented in their sections (such as ListView
and TreeView).
G
-----
Gosub (g-label). Launches a subroutine automatically when the user
clicks or changes a control. Immediately after the letter G, specify
the name of the label to execute.
>
gCancel
<
may be specified to perform an implicit |Gui| Cancel (but if a
label named "Cancel" exists in the script, it will be executed
instead). The subroutine may consult the following built-in variables:
A_Gui, A_GuiControl, A_GuiEvent, and A_EventInfo.
*GUI_Controls_Common_Styles_and_Other_Options*
Controls: Common Styles and Other Options~
Note: In the absence of a preceding sign, a plus sign is assumed; for
example, Wrap is the same as +Wrap. By contrast, -Wrap would remove
the word-wrapping property.
AltSubmit~
---------
Uses alternate submit method. For DropDownList, ComboBox, and ListBox
this causes the Gui Submit command to store the position of the
selected item rather than its text. If no item is selected, a ComboBox
will still store the text in its edit field; similarly, a DropDownList
or ListBox will still make its output variable blank. Note: AltSubmit
also affects the behavior of GuiControlGet when retrieves the contents
of such a control.
C~
-----
Color of text (has no effect on buttons). Specify the letter C
followed immediately by a color name (see color chart) or RGB value
(the 0x prefix is optional). Examples: cRed, cFF2211, c0xFF2211,
cDefault.
Disabled~
--------
Makes an input-capable control appear in a disabled state, which
prevents the user from focusing or modifying its contents. Use
GuiControl Enable to enable it later. Note: To make an Edit control
read-only, specify the string ReadOnly instead. Also, the word
Disabled may optionally be followed immediately by a 0 or 1 to
indicate the starting state (0 for enabled and 1 for disabled). In
other words, Disabled and Disabled%VarContainingOne% are the same.
Hidden~
------
The control is initially invisible. Use GuiControl Show to show it
later. The word Hidden may optionally be followed immediately by a 0
or 1 to indicate the starting state (0 for visible and 1 for hidden).
In other words, Hidden and Hidden%VarContainingOne% are the same.
Left~
-----
Left-justifies the control's text within its available width. This
option affects the following controls: Text, Edit, Button, Checkbox,
Radio, UpDown, Slider, Tab, Tab2, GroupBox, DateTime.
Right~
-----
Right-justifies the control's text within its available width. For
checkboxes and radio buttons, this also puts the box itself on the
right side of the control rather than the left. This option affects
the following controls: Text, Edit, Button, Checkbox, Radio, UpDown,
Slider, Tab, Tab2, GroupBox, DateTime, Link.
Center~
------
Centers the control's text within its available width. This option
affects the following controls: Text, Edit, Button, Checkbox, Radio,
Slider, GroupBox.
Section~
-------
Starts a new section and saves this control's position for later use
with the xs and ys positioning options described above.
Tabstop~
-------
Use -Tabstop (i.e. minus Tabstop) to have an input-capable control
skipped over when the user presses the TAB key to navigate.
Wrap~
-----
Enables word-wrapping of the control's contents within its available
width. Since nearly all control types start off with word-wrapping
enabled, use -Wrap to disable word-wrapping.
VScroll~
-------
Provides a vertical scroll bar if appropriate for this type of
control.
HScroll~
-------
Provides a horizontal scroll bar if appropriate for this type of
control. The rest of this paragraph applies to ListBox only. The
horizontal scrolling width defaults to 3 times the width of the
ListBox. To specify a different scrolling width, include a number
immediately after the word HScroll. For example, HScroll500 would
allow 500 pixels of scrolling inside the ListBox. However, if the
specified scrolling width is smaller than the width of the ListBox, no
scroll bar will be shown (though the mere presence of HScroll makes it
possible for the horizontal scroll bar to be added later via
GuiControl, +HScroll500, MyScrollBar, which is otherwise impossible).
*GUI_Controls_Uncommon_Styles_and_Options*
Controls: Uncommon Styles and Options~
BackgroundTrans
---------------
Uses a transparent background, which allows any control that lies
behind a Text, Picture, or GroupBox control to show through. For
example, a transparent Text control displayed on top of a Picture
control would make the text appear to be part of the picture. Use
GuiControl +Background to remove this option later. See Picture
control's AltSubmit section for more information about transparent
images. Known limitation: BackgroundTrans might not work properly for
controls inside a Tab control that contains a ListView.
-Background
-----------
(i.e. minus Background): Uses the standard background color rather
than the one set by the |Gui| Color command. This is most often used
to make a Tab control have its standard color rather than the window
color. Use
>
GuiControl +Background
<
to remove this option later.
Border
------
Provides a thin-line border around the control. Most controls do not
need this because they already have a type-specific border. When
adding a border to an existing control, it might be necessary to
increase the control's width and height by 1 pixel.
HwndOutputVar [v1.0.46.01+]
----------------------------
When used with Gui Add, this option stores the window handle (HWND) of
the newly created control in OutputVar. For example:
>
Gui, Add, Edit, vMyEdit HwndMyEditHwnd
<
When within a function, MyEditHwnd is treated as a function dynamic
variable. A control's HWND is often used with |PostMessage|,
|SendMessage|, and |DllCall|. It can also be used directly as an
ahk_id |WinTitle| (this also works on hidden controls even when
|DetectHiddenWindows| is Off) or [in v1.1.04+] with GuiControl and
GuiControlGet as the ControlID parameter. On a related note, a parent
window's HWND can be retrieved via
>
Gui MyGui:+HwndOutputVa
<
Theme
-----
This option can be used to override the window's current theme setting
for the newly created control. It has no effect when used on an
existing control; however, this may change in a future version. See
>
Gui +/-Theme
<
for details.
(Unnamed Style)
---------------
Specify a plus or minus sign followed immediately by a decimal or
hexadecimal style number. If the sign is omitted, a plus sign is
assumed.
(Unnamed ExStyle)
-----------------
Specify a plus or minus sign followed immediately by the letter E and
a decimal or hexadecimal extended style number. If the sign is
omitted, a plus sign is assumed. For example, E0x200 would add the
WS_EX_CLIENTEDGE style, which provides a border with a sunken edge
that might be appropriate for pictures and other controls. Although
the other extended styles are not documented here (since they are
rarely used), they can be discovered by searching for WS_EX_CLIENTEDGE
at www.microsoft.com.
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.
Creating Multiple GUI Windows~
For windows other than number 1, the window's name or number (if it
has one) is used as a prefix for the special labels mentioned above;
for example, 2GuiEscape and 2GuiClose would be the default labels for
window number 2, while MyGuiGuiEscape and MyGuiGuiClose would be the
default labels for MyGui. To use custom label names, see
>
Gui +Label
<
To operate upon a window other than the default, include its name or
number (or in v1.1.03+, its HWND) followed by a colon in front of the
sub-command, as in these examples:
>
Gui, MyGui:Add, Text,, Text for about-box.
Gui, MyGui:Show
<
|Gui| MyGui:Default can be used to avoid the need for the "MyGui:"
prefix above. In addition, the prefix is not necessary inside a GUI
thread that operates upon the same window that launched the thread.
[v1.1.03+]: Gui names must conform to the same rules as variable
names. Any number which is either not between 1 and 99 or is longer
than two characters (such as 0x01) must be the HWND of an existing
Gui, or the command will fail. The number of windows that can be
created is limited only by available system resources.
[v1.1.04+]: Any number of unnamed GUI windows can be created using
|Gui|, New.
GUI Events, Threads, and Subroutines~
A GUI thread is defined as any thread launched as a result of a GUI
action. GUI actions include selecting an item from a GUI window's
menu bar, or triggering one of its g-labels (such as by pressing a
button).
The |default| window name for a GUI thread is that of the window that
launched the thread. Non-GUI threads use 1 as their default.
Whenever a GUI thread is launched, that thread's last found window
starts off as the GUI window itself. This allows commands for
windows and controls -- such as |WinMove|, |WinHide|, |WinSet|, |WinSetTitle|,
and |ControlGetFocus| -- to omit WinTitle and WinText when operating
upon the GUI window itself (even if it is hidden).
Clicking on a control while its g-label is already running from a
prior click will have no effect and the event is discarded. To prevent
this, use Critical as the subroutine's first line (however, this will
also buffer/defer other threads such as the press of a hotkey).
The built-in variables A_Gui and A_GuiControl contain the window name
and Control ID that launched the current thread. For details see A_Gui
and A_GuiControl.
To have multiple events perform the same subroutine, specify their
labels consecutively above the subroutine. For example:
>
GuiEscape:
GuiClose:
ButtonCancel:
ExitApp ; All of the above labels will do this.
<
All GUI threads start off fresh with the default values for
settings such as SendMode. These defaults can be changed in the
auto-execute section.
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: Tab control:
Gui, Add, Tab2,, First Tab|Second Tab|Third Tab ; Tab2 vs. Tab requires v1.0.47.05.
Gui, Add, Checkbox, vMyCheckbox, Sample checkbox
Gui, Tab, 2
Gui, Add, Radio, vMyRadio, Sample radio1
Gui, Add, Radio,, Sample radio2
Gui, Tab, 3
Gui, Add, Edit, vMyEdit r5 ; r5 means 5 rows tall.
Gui, Tab ; i.e. subsequently-added controls will not belong to the tab control.
Gui, Add, Button, default xm, OK ; xm puts it at the bottom left corner.
Gui, Show
return
ButtonOK:
GuiClose:
GuiEscape:
Gui, Submit ; Save each control's contents to its associated variable.
MsgBox You entered:`n%MyCheckbox%`n%MyRadio%`n%MyEdit%
ExitApp
; Example: ListBox containing files in a directory:
Gui, Add, Text,, Pick a file to launch from the list below.`nTo cancel, press ESCAPE or close this window.
Gui, Add, ListBox, vMyListBox gMyListBox w640 r10
Gui, Add, Button, Default, OK
Loop, C:\*.* ; Change this folder and wildcard pattern to suit your preferences.
{
GuiControl,, MyListBox, %A_LoopFileFullPath%
}
Gui, Show
return
MyListBox:
if A_GuiEvent <> DoubleClick
return
; Otherwise, the user double-clicked a list item, so treat that the same as pressing OK.
; So fall through to the next label.
ButtonOK:
GuiControlGet, MyListBox ; Retrieve the ListBox's current selection.
MsgBox, 4,, Would you you like to launch the file or document below?`n`n%MyListBox%
IfMsgBox, No
return
; Otherwise, try to launch it:
Run, %MyListBox%,, UseErrorLevel
if ErrorLevel = ERROR
MsgBox Could not launch the specified file. Perhaps it is not associated with anything.
return
GuiClose:
GuiEscape:
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
; Example: On-screen display (OSD) via transparent window:
CustomColor = EEAA99 ; Can be any RGB color (it will be made transparent below).
Gui +LastFound +AlwaysOnTop -Caption +ToolWindow ; +ToolWindow avoids a taskbar button and an alt-tab menu item.
Gui, Color, %CustomColor%
Gui, Font, s32 ; Set a large font size (32-point).
Gui, Add, Text, vMyText cLime, XXXXX YYYYY ; XX & YY serve to auto-size the window.
; Make all pixels of this color transparent and make the text itself translucent (150):
WinSet, TransColor, %CustomColor% 150
SetTimer, UpdateOSD, 200
Gosub, UpdateOSD ; Make the first update immediate rather than waiting for the timer.
Gui, Show, x0 y400 NoActivate ; NoActivate avoids deactivating the currently active window.
return
UpdateOSD:
MouseGetPos, MouseX, MouseY
GuiControl,, MyText, X%MouseX%, Y%MouseY%
return
; Example: A moving progress bar overlayed on a background image.
Gui, Color, White
Gui, Add, Picture, x0 y0 h350 w450, %A_WinDir%\system32\ntimage.gif
Gui, Add, Button, Default xp+20 yp+250, Start the Bar Moving
Gui, Add, Progress, vMyProgress w416
Gui, Add, Text, vMyText wp ; wp means "use width of previous".
Gui, Show
return
ButtonStartTheBarMoving:
Loop, %A_WinDir%\*.*
{
if A_Index > 100
break
GuiControl,, MyProgress, %A_Index%
GuiControl,, MyText, %A_LoopFileName%
Sleep 50
}
GuiControl,, MyText, Bar finished.
return
GuiClose:
ExitApp
; Example: Simple image viewer:
Gui, +Resize
Gui, Add, Button, default, &Load New Image
Gui, Add, Radio, ym+5 x+10 vRadio checked, Load &actual size
Gui, Add, Radio, ym+5 x+10, Load to &fit screen
Gui, Add, Pic, xm vPic
Gui, Show
return
ButtonLoadNewImage:
FileSelectFile, file,,, Select an image:, Images (*.gif; *.jpg; *.bmp; *.png; *.tif; *.ico; *.cur; *.ani; *.exe; *.dll)
if file =
return
Gui, Submit, NoHide ; Save the values of the radio buttons.
if Radio = 1 ; Display image at its actual size.
{
Width = 0
Height = 0
}
else ; Second radio is selected: Resize the image to fit the screen.
{
Width := A_ScreenWidth - 28 ; Minus 28 to allow room for borders and margins inside.
Height = -1 ; "Keep aspect ratio" seems best.
}
GuiControl,, Pic, *w%width% *h%height% %file% ; Load the image.
Gui, Show, xCenter y0 AutoSize, %file% ; Resize the window to match the picture size.
return
GuiClose:
ExitApp
; Example: Simple text editor with menu bar.
; Create the sub-menus for the menu bar:
Menu, FileMenu, Add, &New, FileNew
Menu, FileMenu, Add, &Open, FileOpen
Menu, FileMenu, Add, &Save, FileSave
Menu, FileMenu, Add, Save &As, FileSaveAs
Menu, FileMenu, Add ; Separator line.
Menu, FileMenu, Add, E&xit, FileExit
Menu, HelpMenu, Add, &About, HelpAbout
; Create the menu bar by attaching the sub-menus to it:
Menu, MyMenuBar, Add, &File, :FileMenu
Menu, MyMenuBar, Add, &Help, :HelpMenu
; Attach the menu bar to the window:
Gui, Menu, MyMenuBar
; Create the main Edit control and display the window:
Gui, +Resize ; Make the window resizable.
Gui, Add, Edit, vMainEdit WantTab W600 R20
Gui, Show,, Untitled
CurrentFileName = ; Indicate that there is no current file.
return
FileNew:
GuiControl,, MainEdit ; Clear the Edit control.
return
FileOpen:
Gui +OwnDialogs
; Force the user to dismiss the FileSelectFile dialog before
; returning to the main window.
FileSelectFile, SelectedFileName, 3,, Open File, Text Documents (*.txt)
if SelectedFileName = ; No file selected.
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, About:+owner1 ; Make the main window (Gui #1) the owner of the "about box".
Gui +Disabled ; Disable main window.
Gui, About:Add, Text,, Text for about box.
Gui, About:Add, Button, Default, OK
Gui, About:Show
return
AboutButtonOK: ; This section is used by the "about box" above.
AboutGuiClose:
AboutGuiEscape:
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
<
==============================================================================
*Gui_Control_Types*
GUI Control Types~
------------------------------------------------------------------------------
Table of Contents~
- Text , Edit , UpDown , Picture ~
- Button , Checkbox , Radio ~
- DropDownList , ComboBox ~
- ListBox , ListView , TreeView ~
- Link , Hotkey , DateTime ~
- MonthCal , Slider , Progress ~
- GroupBox , Tab2 , StatusBar ~
- ActiveX (e.g. Internet Explorer Control) ~
- Custom ~
Text~
Description: A region containing borderless text that the user cannot
edit. Often used to label other controls. Example:
>
Gui, Add, Text,, Please enter your name:
<
In this case, the last parameter is the string to display. It may
contain linefeeds (`n) to start new lines. In addition, a single long
line can be broken up into several shorter ones by means of a
continuation section.
If a width (W) is specified in Options but no rows (R) or
height (H), the text will be word-wrapped as needed, and the
control's height will be set automatically.
Since the control's contents are in the last parameter of the Gui
command, literal commas do not need to be escaped. This is also true
for the last parameter of all other commands.
A g-label such as gMySubroutine may be listed in the control's
options. This would cause the MySubroutine label to be launched
automatically whenever the user clicks the text. This can be used to
simulate an underlined, blue hyperlink as shown in the following
working script:
>
Gui, Font, underline
Gui, Add, Text, cBlue gLaunchGoogle, Click here to launch Google.
; Alternatively, Link controls can be used:
Gui, Add, Link,, Click here to launch Google.
Gui, Font, norm
Gui, Show
return
LaunchGoogle:
Run www.google.com
return
<
A double-click can be detected by checking whether A_GuiEvent contains
the word DoubleClick.
An ampersand (&) may be used in the text to underline one of its
letters. For example:
>
Gui, Add, Text,, &First Name:
Gui, Add, Edit
<
In the example above, the letter F will be underlined, which allows
the user to press the shortcut key Alt+F to set keyboard focus to the
first input-capable control that was added after the text control. To
instead display a literal ampersand, specify two consecutive
ampersands (&&). To disable all special treatment of ampersands,
include 0x80 in the control's options.
See |Controls__common_styles_and_other_options| for other options like
Right, Center, and Hidden. See also:
|Positioning_and_Sizing_of_Controls|
Edit~
Description: An area where free-form text can be typed by the user.
Example:
>
Gui, Add, Edit, r9 vMyEdit, Text to appear inside the edit control (omit this parameter to start off empty)
<
The control will be multi-line if it has more than one row of text.
For example, specifying r3 in Options will create a 3-line edit
control with the following default properties: a vertical scroll bar,
word-wrapping enabled, and the Enter key captured as part of the input
rather than triggering the window's default button.
To start a new line in a multi-line edit control, the last parameter
(contents) may contain either a solitary linefeed (`n) or a carriage
return and linefeed (`r`n). Both methods produce literal `r`n pairs
inside the Edit control. However, when the control is saved to its
variable via |Gui| Submit or |GuiControlGet| , each `r`n in the text
is always translated to a plain linefeed (`n). To write the text to a
file, follow this example:
>
FileAppend, %MyEdit%, C:\Saved File.txt.
<
If the control has word-wrapping enabled (which is the default for
multi-line edit controls), any wrapping that occurs as the user types
will not produce linefeed characters (only the Enter keystroke can do
that).
Although multi-line edit controls are limited to 64 KB of text on
Windows 95/98/Me, they may have as much as 4 GB of text on Windows
NT/2k/XP or later. As the user enters text, more memory is allocated
as needed.
A g-label such as gMySubroutine may be listed in the control's
options. This would cause the MySubroutine label to be launched
automatically whenever the user or the script changes the contents of
the control.
TIP: To load a text file into an Edit control, use FileRead and
|GuiControl|. For example:
>
Gui, Add, Edit, R20 vMyEdit
FileRead, FileContents, C:\My File.txt
GuiControl,, MyEdit, %FileContents%Edit Options (to remove an option rather than adding it, precede it with a minus sign):
<
Limit
-----
Restricts the user's input to the visible width of the edit field.
Alternatively, to limit input to a specific number of characters,
include a number immediately afterward. For example, Limit10 would
allow no more than 10 characters to be entered.
Lowercase : The characters typed by the user are automatically
converted to lowercase.
Multi
-----
Makes it possible to have more than one line of text. However, it is
usually not necessary to specify this because it will be auto-detected
based on height (H), rows (R), or contents (Text).
Number
------
Prevents the user from typing anything other than digits into the
field (however, it is still possible to paste non-digits into it). An
alternate way of forcing a numeric entry is to attach an UpDown
control to the Edit.
Password
--------
Hides the user's input (such as for password entry) by substituting
masking characters for what the user types. If a non-default masking
character is desired, include it immediately after the word Password.
For example, >
Password*
<
would make the masking character an asterisk rather than the black
circle (bullet), which is the default on Windows XP. Note: This option
has no effect for multi-line edit controls.
ReadOnly
--------
Prevents the user from changing the control's contents. However, the
text can still be scrolled, selected and copied to the clipboard.
Tn
-----
The letter T may be used to set tab stops inside a multi-line edit
control (since tab stops determine the column positions to which
literal TAB characters will jump, they can be used to format the text
into columns). If the letter T is not used, tab stops are set at every
32 dialog units (the width of each "dialog unit" is determined by the
operating system). If the letter T is used only once, tab stops are
set at every n units across the entire width of the control. For
example,
>
Gui, Add, Edit, vMyEdit r16 t64
<
would double the default distance between tab stops. To have custom
tab stops, specify the letter T multiple times as in the following
example: >
Gui, Add, Edit, vMyEdit r16 t8 t16 t32 t64 t128
<
One tab stop is set for each of the absolute column positions in the
list, up to a maximum of 50 tab stops. Note: Tab stops require a
multiline edit control.
Uppercase
---------
The characters typed by the user are automatically converted to
uppercase.
WantCtrlA [v1.0.44+]
---------------------
Specify -WantCtrlA (minus WantCtrlA) to prevent the user's press of
Control-A from selecting all text in the edit control.
WantReturn
----------
Specify -WantReturn (that is, a minus sign followed by WantReturn) to
prevent a multi-line edit control from capturing the Enter keystroke.
Pressing Enter will then be the same as pressing the window's
default button (if any). In this case, the user may press
Control-Enter to start a new line.
WantTab
-------
Causes a tab keystroke to produce a tab character rather than
navigating to the next control. Without this option, the user may
press Control-Tab to produce a tab character inside a multi-line edit
control. Note: Although WantTab also works in a single-line edit
control, each tab character is displayed as an empty-box character
(though it is stored as a real tab).
-Wrap (minus wrap)
-------------------
Turns off word-wrapping in a multi-line edit control. Since this style
cannot be changed after the control has been created, use one of the
following to change it: 1) Destroy then recreate the window and its
control; or 2) Create two overlapping edit controls, one with wrapping
enabled and the other without it. The one not currently in use can be
kept empty and/or hidden.
See general options for other options like Right, Center, and Hidden.
See also: position and sizing of controls.
A more powerful edit control : HiEdit is a free, multitabbed,
large-file edit control consuming very little memory. It can edit both
text and binary files. For details and a demonstration, see
www.autohotkey.com/forum/topic19141.html
UpDown~
Description: A pair of arrow buttons that the user can click to
increase or decrease a value. By default, an UpDown control
automatically snaps onto the previously added control. This previous
control is known as the UpDown's buddy control. The most common
example is a "spinner", which is an UpDown attached to an Edit
control. For example:
>
Gui, Add, Edit
Gui, Add, UpDown, vMyUpDown Range1-10, 5
<
In the example above, the Edit control is the UpDown's buddy control.
Whenever the user presses one of the arrow buttons, the number in the
Edit control is automatically increased or decreased.
An UpDown's buddy control can also be a Text control or ListBox.
However, due to OS limitations, controls other than than these (such
as ComboBox and DropDownList) might not work properly with g-labels
and other features.
Specify the UpDown's starting position as the last parameter (if
omitted, it starts off at 0 or the number in the allowable range that
is closest to 0).
When the |Gui| Submit command is used, the control's associated output
variable (if any) receives the current numeric position of the UpDown.
If the UpDown is attached to an Edit control and you do not wish to
validate the user's input, it is best to use the UpDown's value rather
than the Edit's. This is because the UpDown will always yield an
in-range number, even when the user has typed something non-numeric or
out-of-range in the Edit control. On a related note, numbers with more
than three digits get a thousands separator (such as comma) by
default. These separators are stored in the Edit's output variable but
not that of the UpDown.
If the UpDown has a g-label, it will be launched whenever the user
clicks one of the arrow buttons or presses an arrow key on the
keyboard. Each launch of the g-label also stores the UpDown's position
in its associated output variable (if any).
UpDown Options:~
Horz
-----
Make's the control's buttons point left/right rather than
up/down. By default, Horz also makes the control isolated (no buddy).
This can be overridden by specifying
>
Horz 16
<
in the control's options.
Left
-----
Puts the UpDown on the left side of its buddy rather than the right.
Range
-----
Sets the range to be something other than 0 to 100. After the word
Range, specify the minimum, a dash, and maximum. For example,
Range1-1000 would allow a number between 1 and 1000 to be selected;
Range-50-50 would allow a number between -50 and 50; and Range-10--5
would allow a number between -10 and -5. The minimum and maximum may
be swapped to cause the arrows to move in the opposite of their normal
direction. The broadest allowable range is -2147483648-2147483647.
However, Windows 95 and NT4 require Internet Explorer 5.0 or later to
support a range broader than -32767-32767. Finally, if the buddy
control is a ListBox , the range defaults to 32767-0 for verticals and
the inverse for horizontals (Horz).
Wrap
-----
Causes the control to wrap around to the other end of its range when
the user attempts to go beyond the minimum or maximum. Without Wrap,
the control stops when the minimum or maximum is reached.
-16 (minus 16)
---------------
Causes a vertical UpDown to be isolated; that is, it will have no
buddy. This also causes the control to obey any specified width,
height, and position rather than conforming to the size of its buddy
control. In addition, an isolated UpDown tracks its own position
internally. This position can be retrieved normally by means such as
Gui Submit.
0x80
-----
Include >
0x80
<
in Options to omit the thousands separator that is normally present
between every three decimal digits in the buddy control. However, this
style is normally not used because the separators are omitted from the
number whenever the script retrieves it from the UpDown control itself
(rather than its buddy control).
Increments other than 1: In this script, NumEric demonstrates how
to change an UpDown's increment to a value other than 1 (such as 5 or
0.1).
See also: position and sizing of controls.
Picture (or Pic)~
Description: An area containing an image (see last two paragraphs for
supported file types). The last parameter is the filename of the
image, which is assumed to be in A_WorkingDir if an absolute path
isn't specified. Example:
>
Gui, Add, Picture, w300 h-1, C:\My Pictures\Company Logo.gif
<
To retain the image's actual width and/or height, omit the W and/or H
options. Otherwise, the image is scaled to the specified width and/or
height (this width and height also determines which icon to load from
a multi-icon .ICO file). To shrink or enlarge the image while
preserving its aspect ratio, specify -1 for one of the dimensions and
a positive number for the other. For example, specifying
>
w200 h-1
<
would make the image 200 pixels wide and cause its height to be set
automatically. If the picture cannot be loaded or displayed (e.g. file
not found), the control is left empty and its width and height are set
to zero.
A g-label such as gMySubroutine may be listed in the control's
options. This would cause the MySubroutine label to be launched
automatically whenever the user clicks the picture. A double-click can
be detected by checking whether A_GuiEvent contains the word
DoubleClick.
To use a picture as a background for other controls, the picture
should normally be added prior to those controls. However, if those
controls are input-capable and the picture has a g-label, create the
picture after the other controls and include
>
0x4000000
<
(which is WS_CLIPSIBLINGS) in the picture's Options. This trick also
allows a picture to be the background behind a Tab control or
ListView.
Icons, cursors, and animated cursors ~
Icons and cursors may be loaded from the following types of files:
ICO, CUR, ANI, EXE, DLL, CPL, SCR, and other types that contain icon
resources. To use an icon group other than the first one in the file,
include in Options the word Icon followed by the number of the group.
In the following example, the default icon from the second icon group
would be used:
>
Gui, Add, Picture, Icon2, C:\My Application.exe
<
Specifying the word AltSubmit in Options tells the program to use
Microsoft's GDIPlus.dll to load the image, which might result in a
different appearance for GIF, BMP, and icon images. For example, it
would load an ICO/GIF that has a transparent background as a
transparent bitmap, which allows the BackgroundTrans option to take
effect. If GDIPlus is not available (see next paragraph), AltSubmit is
ignored and the image is loaded using the normal method.
All operating systems support GIF, JPG, BMP, ICO, CUR, and ANI images.
On Windows XP or later, additional image formats such as PNG, TIF,
Exif, WMF, and EMF are supported. Operating systems older than XP can
be given support by copying Microsoft's free GDI+ DLL into the
AutoHotkey.exe folder (but in the case of a compiled script, copy the
DLL into the script's folder). To download the DLL, search for the
following phrase at www.microsoft.com: gdi redistributable
Due to an OS bug, animated cursors scaled to a size greater than 90x90
on Windows 95/98/Me might crash the script.
Animated GIFs ~
Although animated GIF files can be displayed in a picture control,
they will not actually be animated. To solve this, use the AniGIF DLL
(which is free for non-commercial use) as demonstrated at
www.autohotkey.com/forum/topic19264.html
Button~
Description: A pushbutton, which can be pressed to trigger an action.
In this case, the last parameter is the name of the button (shown on
the button itself), which may include linefeeds (`n) to start new
lines. Example:
>
Gui, Add, Button, Default, OK
<
The example above includes the word Default in its Options to make
"OK" the default button. The default button's action is automatically
triggered whenever the user presses ENTER, except when the keyboard
focus is on a different button or a multi-line edit control having the
WantReturn style. To later change the default button to another
button, follow this example, which makes the Cancel button become the
default: >
GuiControl, +Default, Cancel
<
To later change the window to have no default button, follow this
example: >
GuiControl, -default, OK
<
An ampersand (&) may be used in the name button to underline one of
its letters. For example:
>
Gui, Add, Button,, &Pause
<
In the example above, the letter P will be underlined, which allows
the user to press Alt+P as shortcut key. To display a literal
ampersand, specify two consecutive ampersands (&&).
If a button lacks an explicit g-label, an automatic label is
assumed. For example, if the first GUI window contains an OK button,
the ButtonOK label (if it exists) will be launched when the button is
pressed. For GUI windows other than the first, the window number is
included in front of the button's automatic label; for example:
2ButtonOK.
If the text on the button contains spaces or any of the characters in
the set &`r`n`t`, its automatic label omits those characters. For
example, a button titled "&Pause" would have an automatic label of
ButtonPause. Similarly, a button titled "Save && Exit" would have an
automatic label of ButtonSaveExit (the double-ampersand is used to
display a single, literal ampersand).
Known limitation: Certain desktop themes might not display a button's
text properly. If this occurs, try including -Wrap (minus Wrap) in the
button's options. However, this also prevents having more than one
line of text.
Checkbox~
Description: A small box that can be checked or unchecked to
represent On/Off, Yes/No, etc. Example:
>
Gui, Add, Checkbox, vShipToBillingAddress, Ship to billing address?
<
The last parameter is a label displayed next to the box, which is
typically used as a prompt or description of what the checkbox does.
It may include linefeeds (`n) to start new lines. If a width (W) is
specified in Options but no rows (R) or height (H), the control's text
will be word-wrapped as needed, and the control's height will be set
automatically. The checkbox's associated output variable (if any)
receives the number 1 for checked, 0 for unchecked, and -1 for
gray/indeterminate.
Specify the word Check3 in Options to enable a third state that
displays a gray checkmark instead of a black one (the gray state
indicates that the checkbox is neither checked nor unchecked). Specify
the word Checked or CheckedGray in Options to have the checkbox start
off with a black or gray checkmark, respectively. The word Checked may
optionally be followed immediately by a 0, 1, or -1 to indicate the
starting state. In other words, Checked and Checked%VarContainingOne%
are the same.
A g-label such as gMySubroutine may be listed in the control's
options. This would cause the MySubroutine label to be launched
automatically whenever the user clicks or changes the checkbox.
Known limitation: Certain desktop themes might not display a button's
text properly. If this occurs, try including -Wrap (minus Wrap) in the
button's options. However, this also prevents having more than one
line of text.
Radio~
A Radio button is a small empty circle that can be checked (on) or
unchecked (off). Example:
>
Gui, Add, Radio, vMyRadioGroup, Wait for all items to be in stock before shipping
<
These controls usually appear in radio groups, each of which contains
two or more radio buttons. When the user clicks a radio button to turn
it on, any others in its radio group are turned off automatically (the
user may also navigate inside a group with the arrow keys). A radio
group is created automatically around all consecutively added radio
buttons. To start a new group, specify the word Group in the Options
of the first button of the new group -- or simply add a non-radio
control in between, since that automatically starts a new group.
For the last parameter, specify the label to display to the right of
the radio button. This label is typically used as a prompt or
description, and it may include linefeeds (`n) to start new lines. If
a width (W) is specified in Options but no rows (R) or height (H), the
control's text will be word-wrapped as needed, and the control's
height will be set automatically.
Specify the word Checked in Options to have the button start off in
the "on" state. The word Checked may optionally be followed
immediately by a 0 or 1 to indicate the starting state: 0 for
unchecked and 1 for checked. In other words, Checked and
Checked%VarContainingOne% are the same.
The radio button's associated output variable (if any)
receives the number 1 for "on" and 0 for "off". However, if only one
button in a radio group has a variable, that variable will instead
receive the number of the currently selected button: 1 is the first
radio button (according to original creation order), 2 is the second,
and so on. If there is no button selected, 0 is stored.
A g-label such as gMySubroutine may be listed in the control's
options. This would cause the MySubroutine label to be launched
automatically whenever the user turns on the button. Unlike the
single-variable mode in the previous paragraph, the g-label must be
specified for each button in a radio group for which the label should
be launched. This allows the flexibility to ignore the clicks of
certain buttons. Finally, a double-click can be detected by checking
whether A_GuiEvent contains the word DoubleClick.
Known limitation: Certain desktop themes might not display a button's
text properly. If this occurs, try including -Wrap (minus Wrap) in the
button's options. However, this also prevents having more than one
line of text.
DropDownList (or DDL)~
Description: A list of choices that is displayed in response to
pressing a small button. In this case, the last parameter is is a
pipe-delimited list of choices such as |Choice1| | |Choice2| | |Choice3|.
Example:
>
Gui, Add, DropDownList, vColorChoice, Black|White|Red|Green|Blue
<
To have one of the items pre-selected when the window first appears,
include two pipe characters after it. Alternatively, include in
Options the word Choose followed immediately by the number to
pre-select. For example, Choose5 would pre-select the fifth item (as
with other options, it can also be a variable such as Choose%Var%).
To change the choice or add/remove entries from the list after the
control has been created, use GuiControl.
Specify either the word Uppercase or Lowercase in Options to
automatically convert all items in the list to uppercase or lowercase.
Specify the word Sort to automatically sort the contents of the list
alphabetically (this also affects any items added later via
GuiControl). The Sort option also enables incremental searching
whenever the list is dropped down; this allows an item to be selected
by typing the first few characters of its name.
When the |Gui| Submit command is used, the control's associated
output variable* (if any) receives the text of the currently
selected item. However, if the control has the AltSubmit property,
the output variable will receive the item's position number instead
(the first item is 1, the second is 2, etc.).
A g-label such as gMySubroutine may be listed in the control's
options. This would cause the MySubroutine label to be launched
automatically whenever the user selects a new item.
Use the R or H option to control the height of the popup list. For
example, specifying R5 would make the list 5 rows tall. If both R and
H are omitted, the list will automatically expand to take advantage of
the available height of the user's desktop (however, operating systems
older than Windows XP will show 3 rows by default).
The separator between fields may be changed to something other than
pipe (|). For example
>
Gui +Delimiter`n
<
would change it to linefeed and
>
Gui +DelimiterTab
<
would change it to tab (`t).
ComboBox~
Description: Same as DropDownList but also permits free-form text to
be entered as an alternative to picking an item from the list.
Example:
>
Gui, Add, ComboBox, vColorChoice, Red|Green|Blue|Black|White
<
In addition to allowing all the same options as DropDownList above,
the word Limit may be included in Options to restrict the user's input
to the visible width of the ComboBox's edit field. Also, the word
Simple may be specified to make the ComboBox behave as though it is an
Edit field with a ListBox beneath it.
When the Gui Submit command is used, the control's associated output
variable (if any) receives the text of the currently selected item.
However, if the control has the AltSubmit property, the output
variable will receive the item's position number instead (the first
item is 1, the second is 2, etc.). If either case, if there is no
selected item, the output variable will be set to the contents of the
ComboBox's edit field.
A g-label such as gMySubroutine may be listed in the control's
options. This would cause the MySubroutine label to be launched
automatically whenever the user selects a new item.
ListBox~
Description: A relatively tall box containing a list of choices that
can be selected. In this case, the last parameter is is a
pipe-delimited list of choices such as Choice1 | Choice2 | Choice3.
Example:
>
Gui, Add, ListBox, vColorChoice, Red|Green|Blue|Black|White
<
To have list item(s) pre-selected when the window first appears,
include two pipe characters after each (the Multi option is required
if more than one item is to be pre-selected). Alternatively, include
in Options the word Choose followed immediately by a single item
number to pre-select. For example, Choose5 would pre-select the fifth
item. To change the choice or add/remove entries from the list after
the control has been created, use GuiControl.
When the |Gui| Submit command is used, the control's associated output
variable (if any) receives the text of the currently selected item.
However, if the control has the AltSubmit property, the output
variable instead receives the item's position number (the first item
is 1, the second is 2, etc.).
A g-label such as gMySubroutine may be listed in the control's
options. This would cause the MySubroutine label to be launched
automatically whenever the user selects a new item. If the user
double-clicks an item, the built-in variable A_GuiEvent will contain
the string DoubleClick rather than Normal. Also, the variable
A_EventInfo will contain the position of the item that was
double-clicked (1 is the first item, 2 is the second, etc.).
When adding a large number of items to a ListBox, performance may be
improved by using
>
GuiControl, -Redraw, MyListBox
<
prior to the operation, and
>
GuiControl, +Redraw, MyListBox
<
afterward.
ListBox Options:~
Choose: See above.
Multi
-----
Allows more than one item to be selected simultaneously via
shift-click and control-click (to avoid the need for
shift/control-click, specify the number 8 instead of the word Multi).
In this case, |Gui| Submit stores a pipe delimited list of
item-strings in the control's output variable. However, if the
AltSubmit option is in effect, Gui Submit stores a pipe-delimited
list of item numbers instead. For example,
>
1 | 2 | 3
<
would indicate that the first three items are selected. To extract
the individual items from the string, use a parsing loop such as this
example:
>
Loop, parse, MyListBox, |
{
MsgBox Selection number %A_Index% is %A_LoopField%.
}
<
The separator between fields may be changed to something other than
pipe (|). For example
>
Gui +Delimiter`n
<
would change it to linefeed and
>
Gui +DelimiterTab
<
would change it to tab (`t).
ReadOnly
--------
Prevents items from being visibly highlighted when they are selected
(but Gui Submit will still store the selected item).
Sort
-----
Automatically sorts the contents of the list alphabetically (this also
affects any items added later via |GuiControl|). The Sort option also
enables incremental searching, which allows an item to be selected by
typing the first few characters of its name.
Tn
-----
The letter T may be used to set tab stops, which can be used to format
the text into columns. If the letter T is not used, tab stops are set
at every 32 dialog units (the width of each "dialog unit" is
determined by the operating system). If the letter T is used only
once, tab stops are set at every n units across the entire width of
the control. For example,
>
Gui, Add, ListBox, vMyListBox t64
<
would double the default distance between tab stops. To have custom
tab stops, specify the letter T multiple times as in the following
example:
>
Gui, Add, ListBox, vMyListBox t8 t16 t32 t64 t128
<
One tab stop is set for each of the absolute column positions in the
list, up to a maximum of 50 tab stops.
0x100
-----
Include 0x100 in options to turn on the LBS_NOINTEGRALHEIGHT style.
This forces the ListBox to be exactly the height specified rather than
a height that prevents a partial row from appearing at the bottom.
This option also prevents the ListBox from shrinking when its font is
changed.
To specify the number of rows of text (or the height and width), see
position and sizing of controls.
ListView and TreeView~
See separate pages ListView and TreeView.
Link [v1.1.06+]~
Description: A text control that can contain links that can be
clicked. Link controls use HTML-like markup language, but they only
support the tag. Inside the opening tag, an attribute of the form
Attribute="value" may be specified. This is typically an ID or a HREF
attribute, e.g.:
>
Gui, Add, Link,, This is a link
Gui, Add, Link,, Links may be used anywhere in the text like this or that
<
Clicks on a link will be handled automatically if the HREF attribute
is set and it is executable (like an URL or a command). If the HREF
attribute is not used or it couldn't be executed a g-label such as
gMySubroutine may be launched if it was provided. The ErrorLevel
variable then contains the value of the attribute so that the link
that was clicked can be identified.
Hotkey~
Description: A box that looks like a single-line edit control but
instead accepts a keyboard combination pressed by the user. For
example, if the user presses Control+Alt+C on an English keyboard
layout, the box would display "Ctrl + Alt + C".
>
Gui, Add, Hotkey, vChosenHotkey
<
When the Gui Submit command is used, the control's associated
output variable (if any) receives the hotkey modifiers and name,
which are compatible with the Hotkey command. Examples:
>
^!C, +!Home, +^Down, ^Numpad1, !NumpadEnd
<
If there is no hotkey in the control, the output variable is made
blank. Note: Some keys are displayed the same even though they are
retrieved as different names. For example, both ^Numpad7 and
^NumpadHome might be displayed as Ctrl + Num 7.
By default, the control starts off with no hotkey specified. To
instead have a default, specify its modifiers and name as the last
parameter as in this example: >
Gui, Add, Hotkey, vChosenHotkey, ^!p
<
The only modifiers supported are ^ (Control), ! (Alt), and +
(Shift). See the key list for available key names.
A g-label such as gMySubroutine may be listed in the control's
options. This would cause the MySubroutine label to be launched
automatically whenever the user changes the hotkey. Each launch of the
g-label also stores the hotkey in control's associated output
variable (if any). Note: the g-label is launched even when an
incomplete hotkey is present. For example, if the user holds down the
Control key, the g-label is launched once and the output variable
contains only a circumflex (^). When the user completes the hotkey,
the label is launched again and the variable contains the complete
hotkey.
To restrict the types of hotkeys the user may enter, include the word
Limit followed by the sum of one or more of the following numbers:
1
-----
Prevent unmodified keys
2
-----
Prevent Shift-only keys
4
-----
Prevent Control-only keys
8
-----
Prevent Alt-only keys
16
-----
Prevent Shift-Control keys
32
-----
Prevent Shift-Alt keys
64
-----
This value is not supported (it will not behave correctly).
128
-----
Prevent Shift-Control-Alt keys.
For example, Limit1 would prevent unmodified hotkeys such as letters
and numbers from being entered, and Limit15* would require at least two
modifier keys. If the user types a forbidden modifier combination, the
Control+Alt combination is automatically and visibly substituted.
The Hotkey control has limited capabilities. For example, it does not
support mouse/joystick hotkeys or the Windows key (LWin and RWin). One
way to work around this is to provide one or more checkboxes as a
means for the user to enable extra modifiers such as the Windows key.
DateTime~
Description: A box that looks like a single-line edit control but
instead accepts a date and/or time. A drop-down calendar is also
provided. Example:
>
Gui, Add, DateTime, vMyDateTime, LongDate
<
The last parameter may be one of the following:
(omitted)
---------
When omitted, the locale's short date format is used. For example, in
some locales it would look like: 6/1/2005
LongDate
--------
Uses the locale's long date format. For example, in some locales it
would look like: Wednesday, June 01, 2005
Time
-----
Shows only the time using the locale's time format. Although the date
is not shown, it is still present in the control and will be retrieved
along with the time in the YYYYMMDDHH24MISS format.
(custom format)
---------------
Specify any combination of date and time formats. For example,
>
M/d/yy HH:mm
<
would look like 6/1/05 21:37. Similarly,
>
dddd MMMM d, yyyy hh:mm:ss tt
<
would look like Wednesday June 1, 2005 09:37:45 PM. Letters and
numbers to be displayed literally should be enclosed in single quotes
as in this example:
>
'Date:' MM/dd/yy 'Time:' hh:mm:ss tt
<
By contrast, non-alphanumeric characters such as spaces, tabs,
slashes, colons, commas, and other punctuation do not need to be
enclosed in single quotes. The exception to this is the single quote
character itself: to produce it literally, use four consecutive single
quotes (''''), or just two if the quote is already inside an outer
pair of quotes.
DateTime Usage~
To have a date other than today pre-selected, include in Options the
word Choose followed immediately by a date in YYYYMMDD format. For
example, Choose20050531 would pre-select May 31, 2005 (as with other
options, it can also be a variable such as Choose%Var% ). To have no
date/time selected, specify ChooseNone. ChooseNone also creates a
checkbox inside the control that is unchecked whenever the control has
no date. Whenever the control has no date, |Gui| Submit and
|GuiControlGet| will retrieve a blank value (empty string).
The time of day may optionally be present. However, it must always be
preceded by a date when going into or coming out of the control. The
format of the time portion is HH24MISS (hours, minutes, seconds),
where HH24 is expressed in 24-hour format; for example, 09 is 9am and
21 is 9pm. Thus, a complete date-time string would have the format
YYYYMMDDHH24MISS.
When specifying dates in the YYYYMMDDHH24MISS format, only the leading
part needs to be present. Any remaining element that has been omitted
will be supplied with the following default values:
MM
-----
Month 01
DD
-----
Day 01
HH24
-----
Hour 00
MI
-----
Minute 00
SS
-----
Second 00
Within the drop-down calendar, the today-string at the bottom can be
clicked to select today's date. In addition, the year and month name
are clickable and allow easy navigation to a new month or year.
Keyboard navigation: Use the Up/Down arrow keys, NumpadPlus/Minus, and
Home/End to increase or decrease the control's values. Use LeftArrow
and RightArrow to move from field to field inside the control. Within
the drop-down calendar, use the arrow keys to move from day to day;
use PageUp/Down to move backward/forward by one month; use
Ctrl-PageUp/Down to move backward/forward by one year; and use
Home/End to select the first/last day of the month.
When the |Gui| Submit command is used, the control's associated
output variable (if any) receives the selected date and time in
YYYYMMDDHH24MISS format. Both the date and the time are present
regardless of whether they were actually visible in the control.
If the control has a g-label, the label is launched whenever the user
changes the date or time. For each launch, the control's associated
output variable (if any) is automatically updated with the currently
selected date/time.
Windows 95 and NT4 require DLL versions at least as new as those
distributed with Internet Explorer 3.0 to support DateTime controls.
DateTime Options:~
Choose: See above.
Range: Restricts how far back or forward in time the selected date can
be. After the word Range, specify the minimum and maximum dates in
YYYYMMDD format (with a dash between them). For example,
>
Range20050101-20050615
<
would restrict the date to the first 5.5 months of 2005. Either the
minimum or maximum may be omitted to leave the control unrestricted in
that direction. For example, Range20010101 would prevent a date prior
to 2001 from being selected and Range-20091231 (leading dash) would
prevent a date later than 2009 from being selected. Without the Range
option, any date between the years 1601 and 9999 can be selected. The
time of day cannot be restricted.
Right: Causes the drop-down calendar to drop down on the right side of
the control instead of the left.
1: Specify the number 1 in Options to provide an up-down control to
the right of the control to modify date-time values, which replaces
the of the drop-down month calendar that would otherwise be available.
2: Specify the number 2 in Options to provide a checkbox inside the
control that the user may uncheck to indicate that no date/time is
selected. Once the control is created, this option cannot be changed.
MonthCal~
Description: A tall and wide control that displays all the days of the
month in calendar format. The user may select a single date or a range
of dates.
>
Example: Gui, Add, MonthCal, vMyCalendar
<
To have a date other than today pre-selected, specify it as the last
parameter in YYYYMMDD format (e.g. 20050531). A range of dates may
also be pre-selected by including a dash between two dates (e.g.
20050525-20050531).
It is usually best to omit width (W) and height (H) for a MonthCal
because it automatically sizes itself to fit exactly one month. To
display more than one month vertically, specify R2 or higher in
Options. To display more than one month horizontally, specify W-2 (W
negative two) or higher. These options may both be present to expand
in both directions.
The today-string at the bottom of the control can be clicked to select
today's date. In addition, the year and month name are clickable and
allow easy selection of a new year or month.
Unlike DateTime's drop-down calendar, keyboard navigation is generally
not supported in a MonthCal.
When the |Gui| Submit command is used, the control's associated output
variable (if any) receives the selected date in YYYYMMDD format
(without any time portion). However, when the multi-select option is
in effect, the minimum and maximum dates are retrieved with a dash
between them (e.g. 20050101-20050108). If only a single date was
selected in a multi-select calendar, the minimum and maximum are both
present but identical. |StringSplit| can be used to separate the dates.
For example, the following would put the minimum in Date1 and the
maximum in Date2: |StringSplit|, Date, MyMonthCal, -
If the MonthCal has a g-label, each launch of it updates the
control's associated output variable (if any) with the
currently selected date or range. By default, the label is launched
only when: 1) the user changes the selection; or 2) every two minutes
in case a new day has arrived (this behavior is a quirk of the OS).
However, if the word AltSubmit is in the control's Options, the
g-label is launched more often and the built-in variable A_GuiEvent
will contain the word Normal for a change of the date, the number 1
for a click of a date, and the number 2 when the MonthCal releases
"mouse capture". For example, if the user double-clicks a new date,
the label would be launched five times: Once with with Normal, twice
with 0, and twice with 2. This can be used to detect double clicks by
measuring the time between instances of the number 1.
When specifying dates in the YYYYMMDD format, the MM and/or DD
portions may be omitted, in which case they are assumed to be 1. For
example, 200205 is seen as 20020501, and 2005 is seen as
20050101.
Windows 95 and NT4 require DLL versions at least as new as those
distributed with Internet Explorer 3.0 to support MonthCal controls.
MonthCal Options:~
Multi: Multi-select. Allows the user to shift-click or click-drag to
select a range of adjacent dates (the user may still select a single
date too). This option may be specified explicitly or put into effect
automatically by means of specifying a selection range when the
control is created. For example:
>
Gui, Add, MonthCal, vMyCal, 20050101-20050108
<
Once the control is created, this option cannot be changed.
Range: Restricts how far back or forward in time the calendar can go.
After the word Range, specify the minimum and maximum dates in
YYYYMMDD format (with a dash between them). For example,
Range20050101-20050615 would restrict the selection to the first 5.5
months of 2005. Either the minimum or maximum may be omitted to leave
the calendar unrestricted in that direction. For example,
Range20010101 would prevent a date prior to 2001 from being selected
and Range-20091231 (leading dash) would prevent a date later than 2009
from being selected. Without the Range option, any date between the
years 1601 and 9999 can be selected.
4: Specify the number 4 in Options to display week numbers (1-52) to
the left of each row of days. Week 1 is defined as the first week that
contains at least four days.
8: Specify the number 8 in Options to prevent the circling of today's
date within the control.
16: Specify the number 16 in Options to prevent the display of today's
date at the bottom of the control.
Slider~
Description: A sliding bar that the user can move along a vertical or
horizontal track. The standard volume control in the taskbar's tray is
an example of a slider. Example:
>
Gui, Add, Slider, vMySlider, 50
<
Specify the starting position of the slider as the last parameter. If
the last parameter is omitted, the slider starts off at 0 or the
number in the allowable range that is closest to 0.
The user may slide the control by the following means: 1) dragging the
bar with the mouse; 2) clicking inside the bar's track area with the
mouse; 3) turning the mouse wheel while the control has focus; or 4)
pressing the following keys while the control has focus: Arrow keys,
Page-up, Page-down, Home, and End.
When the |Gui| Submit command is used, the control's associated output
variable (if any) receives the current numeric position of the slider.
The position is also stored in the output variable whenever the
control's g-label is launched.
If the slider has a g-label, by default it will be launched only when
the user has stopped moving the slider (such as by releasing the mouse
button after having dragging it). However, if the word AltSubmit is in
the control's Options, the g-label is launched for all slider events
and the built-in variable A_GuiEvent will contain one of the following
digits or strings:
0: The user pressed the Left-arrow or Up-arrow key.
1: The user pressed the Right-arrow or Down-arrow key.
2: The user pressed the Page-up key.
3: The user pressed the Page-down key.
4: The user moved the slider via the mouse wheel, or finished a
drag-and-drop to a new position. 5: The user is currently dragging
the slider via the mouse; that is, the mouse button is currently down.
6: The user pressed the Home key to send the slider to the left or top
side. 7: The user pressed the End key to send the slider to the right
or bottom side.
Normal: The user has finished moving the slider, either via the mouse
or the keyboard. Note: With the exception of mouse wheel movement
(#4), the g-label is launched again for the "normal" event even though
it was already launched for one of the digit-events above.
Slider Options~
Buddy1 and Buddy2
-----------------
Specifies up to two existing controls to automatically reposition at
the ends of the slider. Buddy1 is displayed at the left or top side
(depending on whether the Vertical option is present). Buddy2 is
displayed at the right or bottom side. After the word Buddy1 or
Buddy2, specify the variable name of an existing control. For example,
Buddy1MyTopText would assign the control whose variable name is
MyTopText. Windows 95 and NT4 require Internet Explorer 3.0 or later
to support this option.
Center
------
The thumb (the bar moved by the user) will be blunt on both ends
rather than pointed at one end.
Invert
------
Reverses the control so that the lower value is considered to be on
the right/bottom rather than the left/top. This is typically used to
make a vertical slider move in the direction of a traditional volume
control. Note: The ToolTip option described below will not obey the
inversion and therefore should not be used in this case.
Left
-----
The thumb (the bar moved by the user) will point to the top rather
than the bottom. But if the Vertical option is in effect, the thumb
will point to the left rather than the right.
Line
-----
Specifies the number of positions to move when the user presses one of
the arrow keys. After the word Line, specify number of positions to
move. For example: Line2
NoTicks
-------
Omits tickmarks alongside the track.
Page
-----
Specifies the number of positions to move when the user presses the
Page-up or Page-down key. After the word Page, specify number of
positions to move. For example: Page10
Range
-----
Sets the range to be something other than 0 to 100. After the word
Range, specify the minimum, a dash, and maximum. For example, >
Range1-1000
<
would allow a number between 1 and 1000 to be selected; >
Range-50-50
<
would allow a number between -50 and 50; and >
Range-10--5
<
would allow a number between -10 and -5.
Thick
-----
Specifies the length of the thumb (the bar moved by the user). After
the word Thick, specify the thickness in pixels (e.g. Thick30). To go
beyond a certain thickness on Windows XP or later, it is probably
necessary to either specify the Center option or remove the theme from
the control (which can be done by specifying -Theme in the control's
options).
TickInterval
------------
Provides tickmarks alongside the track at the specified interval.
After the word TickInterval, specify the interval at which to display
additional tickmarks (if the interval is omitted, it is assumed to be
1). For example, TickInterval10 would display a tickmark once every
10 positions.
ToolTip
-------
Creates a tooltip that reports the numeric position of the slider as
the user is dragging it. To have the tooltip appear in a non-default
position, specify one of the following instead: ToolTipLeft or
ToolTipRight (for horizontal sliders); ToolTipTop or ToolTipBottom
(for vertical sliders). Windows 95 and NT4 require Internet Explorer
3.0 or later to support this option.
Vertical
--------
Makes the control slide up and down rather than left and right.
The above options can be changed after the control is created via
GuiControl.
Progress~
Description
-----------
A dual-color bar typically used to indicate how much progress has been
made toward the completion of an operation. Example:
>
Gui, Add, Progress, w300 h20 cBlue vMyProgress
<
Specify the starting position of the bar as the last parameter (if
omitted, the bar starts off at 0 or the number in the allowable range
that is closest to 0). To later change the position of the bar,
follow these examples, all of which operate upon a progress bar whose
associated variable name is MyProgress:
>
GuiControl,, MyProgress, +20 ; Increase the current position by 20.
GuiControl,, MyProgress, 50 ; Set the current position to 50.
<
For horizontal Progress Bars, the thickness of the bar is equal to the
control's height. For vertical Progress Bars it is equal to the
control's width.
Progress Options:~
Cn
-----
Changes the bar's color. Specify for n one of the 16 primary HTML
color names or a 6-digit RGB color value. Examples:
>
cRed
cFFFF33
cDefault
<
If the C option is never used (or cDefault is specified), the
system's default bar color will be used.
BackgroundN
-----------
Changes the bar's background color. Specify for n one of the 16
primary HTML color names or a 6-digit RGB color value. Examples:
BackgroundGreen, BackgroundFFFF33, BackgroundDefault. If the
Background option is never used (or BackgroundDefault is
specified), the background color will be that of the window or tab
control behind it.
Range
------
Sets the range to be something other than 0 to 100. After the word
Range, specify the minimum, a dash, and maximum. For example,
Range0-1000 would allow a numbers between 0 and 1000; Range-50-50
would allow numbers between -50 and 50; and Range-10--5 would allow
numbers between -10 and -5. On Windows 95 and NT4, negative ranges and
ranges beyond 65535 will not behave correctly unless Internet Explorer
3.0 or later is installed.
-Smooth (minus Smooth)
-----------------------
Displays a length of segments rather than a smooth continuous bar.
Specifying -Smooth is also one of the requirements to show a themed
progress bar on Windows XP or later. The other requirement is that the
bar not have any custom colors; that is, that the C and Background
options be omitted. Windows 95 and NT4 require Internet Explorer 3.0
or later to support this option.
Vertical
--------
Makes the bar rise or fall vertically rather than move along
horizontally. Windows 95 and NT4 require Internet Explorer 3.0 or
later to support this option.
The above options can be changed after the control is created via
|GuiControl|.
GroupBox~
Description
-----------
A rectangular border/frame, often used around other controls to
indicate they are related. In this case, the last parameter is the
title of the box, which if present is displayed at its upper-left
edge. Example:
>
Gui, Add, GroupBox, w400 h300, Geographic Criteria
<
By default, a GroupBox's title may have only one line of text. This
can be overridden by specifying Wrap in Options.
To specify the number of rows inside the control (or its height and
width), see position and sizing of controls.
Tab2~
Description: A large control containing multiple pages, each of which
contains other controls. From this point forward, these pages are
referred to as "tabs".
Tab2 vs. Tab ~
v1.0.47.05 adds the "Tab2" control that fixes rare redrawing problems
in the original "Tab" control (e.g. activating a GUI window by
clicking certain parts of its controls, such as scrollbars, might
redraw improperly). The original Tab control is retained for backward
compatibility because Tab2 puts its tab control after its contained
controls in the tab-key navigation order. New scripts should use Tab2
whenever possible. Example:
>
Gui, Add, Tab2,, General|View|Appearance|Settings
<
The last parameter above is a pipe-delimited list of tab names. To
have one of the tabs pre-selected when the window first appears,
include two pipe characters after it. Alternatively, include in
Options the word Choose followed immediately by the number to
pre-select. For example, Choose5 would pre-select the fifth tab (as
with other options, it can also be a variable such as Choose%Var%).
To change the selected tab, add tabs, or remove tabs after the control
has been created, use GuiControl.
After creating a Tab control, subsequently added controls
automatically belong to its first tab. This can be changed at any time
by following these examples:
>
Gui, Tab
; Future controls are not part of any tab control.
Gui, Tab, 3
; Future controls are owned by the third tab of the current
; tab control.
Gui, Tab, 3, 2
; Future controls are owned by the third tab of the second tab
; control.
Gui, Tab, Name
; Future controls are owned by the tab whose name starts with
; Name (not case sensitive).
Gui, Tab, Name,, Exact
; Same as above but requires exact match (case sensitive too)
<
It is also possible to use any of the examples above to assign
controls to a tab or tab-control that does not yet exist (except in
the case of the Name method). But in that case, the relative
positioning options described below are not supported.
Positioning
-----------
When each tab of a Tab control receives its first sub-control, that
sub-control will have a special default position under the following
conditions: 1) The X and Y coordinates are both omitted, in which case
the first sub-control is positioned at the upper-left corner of the
tab control's interior (with a standard margin), and sub-controls
beyond the first are positioned beneath the previous control; 2) The
X+n and/or Y+n positioning options are specified, in which case
the sub-control is positioned relative to the upper-left corner of the
tab control's interior. For example, specifying x+10 y+10 would
position the control 10 pixels right and 10 pixels down from the upper
left corner.
Sub-controls do not necessarily need to exist within their Tab
control's boundaries: they will still be hidden and shown whenever
their tab is selected or de-selected. This behavior is especially
appropriate for the "buttons" style described below.
When the |Gui| Submit command is used, the control's associated output
variable (if any) receives the name of the currently selected tab.
However, if the control has the AltSubmit property, the output
variable will receive the tab's position number instead (the first tab
is 1, the second is 2, etc.).
A g-label such as gMySubroutine may be listed in the control's
options. This would cause the MySubroutine label to be launched
automatically whenever the user changes to a new tab. If the tab
control has both a g-label and an output variable, whenever the user
switches to a new tab, the output variable will be set to the
previously selected tab name (or number in the case of AltSubmit).
Keyboard navigation: The user may press Control-PageDown/PageUp to
navigate from page to page in a tab control; if the keyboard focus is
on a control that does not belong to a Tab control, the window's first
Tab control will be navigated. Control-Tab and Control-Shift-Tab may
also be used except that they will not work if the currently focused
control is a multi-line Edit control.
Each window may have no more than 255 tab controls. Each tab control
may have no more than 256 tabs (pages). In addition, a tab control may
not contain other tab controls.
Tab Options~
Choose: See above.
-Background
-----------
(minus followed by the word background): Overrides the window's
custom background color and uses the system's default Tab control
color. Specify +Theme -Background to make the Tab control conform
to the current desktop theme. However, most control types will look
strange inside such a Tab control because their backgrounds will not
match that of the tab control. This can be fixed for some control
types (such as Text) by adding BackgroundTrans to their options.
Buttons
-------
Creates a series of buttons at the top of the control rather than a
series of tabs (in this case, there will be no border by default
because the display area does not typically contain controls).
Left /Right /Bottom
-------------------
Specify one of these words to have the tabs on the left, right, or
bottom side instead of the top. See TCS_VERTICAL for limitations on
Left and Right.
-Wrap
-----
Prevents the tabs from taking up more than a single row (in which case
if there are too many tabs to fit, arrow buttons are displayed to
allow the user to slide more tabs into view).
To specify the number of rows of text inside the control (or its
height and width), see position and sizing of controls.
Icons in Tabs
-------------
An icon may be displayed next to each tab's name/text via
|SendMessage|. This is demonstrated in the forum topic Icons in
tabs.
StatusBar[v1.0.44+]~
Description: A row of text and/or icons attached to the bottom of a
window, which is typically used to report changing conditions.
Example:
>
Gui, Add, StatusBar,, Bar's starting text (omit to start off empty).
SB_SetText("There are " . RowCount . " rows selected.")
<
The simplest use of a status bar is to call |SB_SetText|() whenever
something changes that should be reported to the user. To report more
than one piece of information, divide the bar into sections via
|SB_SetParts|(). To display icon(s) in the bar, call |SB_SetIcon|().
All of the following StatusBar functions operate upon the current
thread's default GUI window (which can be changed via Gui, 2:Default).
If the default window does not exist or has no status bar, all SB
functions return 0 to indicate the problem.
|SB_SetText|(NewText [, PartNumber, Style])
Displays NewText in the specified part of the status bar. If
PartNumber is omitted, it defaults to 1. Otherwise, specify an integer
between 1 and 256. If Style is omitted, it defaults to 0, which uses a
traditional border that makes that part of the bar look sunken.
Otherwise, specify 1 to have no border or 2 to have border that makes
that part of the bar look raised. Finally, up to two tab characters
(`t) may be present anywhere in NewText: anything to the right of
the first tab is centered within the part, and anything to the right
of the second tab is right-justified. SB_SetText() returns 1 upon
success and 0 upon failure.
|SB_SetParts|([Width1, Width2, ... Width255])
Divides the bar into multiple sections according to the specified
widths (in pixels). If all parameters are omitted, the bar is restored
to having only a single, long part. Otherwise, specify the width of
each part except the last (the last will fill the remaining width of
the bar). For example, >
SB_SetParts(50, 50)
<
would create three parts: the first two of width 50 and the last one
of all the remaining width. Note: Any parts "deleted" by SB_SetParts()
will start off with no text the next time they are shown (furthermore,
their icons are automatically destroyed). Upon success,
|SB_SetParts|() returns a non-zero value (the status bar's HWND). Upon
failure it returns 0.
|SB_SetIcon|(Filename [, IconNumber, PartNumber ])
Displays a small icon to the left of the text in the specified part
(if PartNumber is omitted, it defaults to 1). Filename is the name of
an icon (.ICO), cursor (.CUR), or animated cursor (.ANI) file
(animated cursors will not actually be animated in the bar). Other
sources of icons include the following types of files: EXE, DLL, CPL,
SCR, and other types that contain icon resources. To use an icon group
other than the first one in the file, specify its number for
IconNumber. For example, >
SB_SetIcon("Shell32.dll", 2)
<
would use the default icon from the second icon group. SB_SetIcon()
returns the icon's HICON upon success and 0 upon failure. The HICON is
a system resource that can be safely ignored by most scripts because
it is destroyed automatically when the status bar's window is
destroyed. Similarly, any old icon is destroyed when SB_SetIcon()
replaces it with a new one. This can be avoided via:
>
Gui +LastFound
SendMessage, 0x40F, part_number - 1, my_hIcon, msctls_statusbar321
; 0x40F is SB_SETICON
<
|SB_SetProgress|()
Creates and controls a progress bar inside the status bar. This
function is available at www.autohotkey.com/forum/topic37754.html
G-Label Notifications
A g-label such as gMySubroutine may be listed in the control's
options. This would cause the MySubroutine label to be launched
automatically whenever the user clicks on the bar. This subroutine may
consult the built-in variables A_Gui and A_GuiControl. More
importantly, it may consult |A_GuiEvent|, which contains one of the
following strings (for compatibility with future versions, a script
should not assume these are the only possible values):
- Normal*
---------
The user left-clicked the bar. The variable A_EventInfo contains the
part number (however, the part number might be a very large integer if
the user clicks near the sizing grip at the right side of the bar)
- RightClick
------------
The user right-clicked the bar. The variable A_EventInfo contains the
part number. NOTE: GuiContextMenu will not be called for the status
bar if it has a g-label. Also, the g-label's RightClick event should
be used instead of GuiContextMenu when the script needs to know which
part number the user clicked on (A_EventInfo).
- DoubleClick
-------------
The user double-clicked the bar. The variable A_EventInfo contains the
part number.
- R
-----
The user double-right-clicked the bar. The variable A_EventInfo
contains the part number.
Font and Color ~
Although the font size, face, and style can be set via Gui Font
(just like normal controls), the text color cannot be changed. Also,
Gui Color is not obeyed; instead, the status bar's background color
may be changed by specifying in Options the word Background followed
immediately by a color name (see color chart) or RGB value (the
0x prefix is optional). Examples: BackgroundSilver, BackgroundFFDD99,
BackgroundDefault.
Hiding the StatusBar ~
Upon creation, the bar can be hidden via >
Gui, Add, StatusBar, Hidden vMyStatusBar
<
To hide it sometime after creation, use >
GuiControl, Hide, MyStatusBar
<
To show it, use >
GuiControl, Show, MyStatusBar
<
Note: Hiding the bar does not reduce the height of the window. If
that is desired, one easy way is >
Gui, Show, AutoSize
<
Styles (rarely used)
See the StatusBar styles table.
Known Limitations:
1) Any control that overlaps the status bar might sometimes get drawn
on top of it. One way to avoid this is to dynamically shrink such
controls via the GuiSize label. 2) There is a limit of one status
bar per window.
Example
The bottom of the TreeView page demonstrates a multipart status
bar.
ActiveX [v1.1.03+]~
ActiveX components such as the MSIE browser control can be embedded
into a GUI window by following this example:
>
Gui Add, ActiveX, w980 h640 vWB, Shell.Explorer
; The final parameter is the name of the ActiveX component
WB.Navigate("http://www.autohotkey.com/forum/")
; This is specific to the web browser control
Gui Show
<
When the control is created, an ActiveX object is stored in the
control's associated variable, if it has one. |GuiControlGet| can also
be used to retrieve the object.
To handle events exposed by the object, use |ComObjConnect| as
demonstrated below:
>
Gui Add, Edit, w930 r1 vURL, http://www.autohotkey.com/forum/
Gui Add, Button, x+6 yp w44 Default, Go
Gui Add, ActiveX, xm w980 h640 vWB, Shell.Explorer
ComObjConnect(WB, WB_events)
; Connect WB's events to the WB_events class object.
Gui Show
; Continue on to load the initial page:
ButtonGo:
Gui Submit, NoHide
WB.Navigate(URL)
return
class WB_events
{
NavigateComplete2(wb, NewURL)
{
GuiControl,, URL, %NewURL% ; Update the URL edit control.
}
}
GuiClose:
ExitApp
<
ComObjType can be used to determine the type of object stored in the
control's variable.
Custom [v1.1.10+]~
Other controls which are not directly supported by AutoHotkey can be
also embedded into a GUI window. In order to do so, the Win32 class
name must be specified through the Class option in |Gui|, Add.
Examples:
>
Gui, Add, Custom, ClassComboBoxEx32
; Adds a ComboBoxEx control.
Gui, Add, Custom, ClassScintilla
; Adds a Scintilla control. Note that the SciLexer.dll
; library must be loaded before the control can be added
<
AutoHotkey uses the standard Windows control text routines when text
is to be retrieved/replaced in the control via >
Gui, Add
< or >
GuiControl/Get
<
G-Label Notifications
A g-label such as gMySubroutine may be listed in the control's options
in order to capture events coming from the control. This subroutine
may consult the built-in variables A_Gui and A_GuiControl. More
importantly, it may consult A_GuiEvent, which contains one of the
following strings (for compatibility with future versions, a script
should not assume these are the only possible
values):
Normal
------
A WM_COMMAND message was received. A_EventInfo contains a
control-defined notification code (equivalent to HIWORD(wParam) in
C/C++)
N
A WM_NOTIFY message was received. A_EventInfo contains a pointer to
the control notification structure (NMHDR). A 32-bit signed integer
value may be returned to the control by assigning it to ErrorLevel
(by default, the g-label thread's ErrorLevel is set to zero). Invalid
values are treated as zero.
Here is an example that shows how to add and use an IP address
control:
>
Gui, Add, Custom, ClassSysIPAddress32 r1 w150 hwndhIPControl gIPControlEvent
Gui, Add, Button, Default, OK
IPCtrlSetAddress(hIPControl, A_IPAddress1)
Gui, Show
return
GuiClose:
ExitApp
ButtonOK:
Gui, Hide
ToolTip
MsgBox % "You chose " IPCtrlGetAddress(hIPControl)
ExitApp
IPControlEvent:
if A_GuiEvent = Normal
{
; WM_COMMAND was received.
if (A_EventInfo = 0x0300) ; EN_CHANGE
ToolTip Control changed!
}
else if A_GuiEvent = N
{
; WM_NOTIFY was received.
; Get the notification code. Normally this field is UInt
; but the IP address control uses negative codes, so
; for convenience we read it as a signed int.
nmhdr_code := NumGet(A_EventInfo + 2*A_PtrSize, "int")
if (nmhdr_code != -860) ; IPN_FIELDCHANGED
return
; Extract info from the NMIPADDRESS structure
iField := NumGet(A_EventInfo + 2*A_PtrSize + 4, "int")
iValue := NumGet(A_EventInfo + 2*A_PtrSize + 8, "int")
if iValue >= 0
ToolTip Field #%iField% modified: %iValue%
else
ToolTip Field #%iField% left empty
}
return
IPCtrlSetAddress(hControl, ipaddress)
{
static WM_USER := 0x400
static IPM_SETADDRESS := WM_USER + 101
; Pack the IP address into a 32-bit word for use with
; SendMessage.
ipaddrword := 0
Loop, Parse, ipaddress, .
ipaddrword := (ipaddrword * 256) + A_LoopField
SendMessage IPM_SETADDRESS, 0, ipaddrword,, ahk_id %hControl%
}
IPCtrlGetAddress(hControl)
{
static WM_USER := 0x400
static IPM_GETADDRESS := WM_USER + 102
VarSetCapacity(addrword, 4)
SendMessage IPM_GETADDRESS, 0, &addrword,, ahk_id %hControl%
return NumGet(addrword, 3, "UChar") "." NumGet(addrword, 2, "UChar") "." NumGet(addrword, 1, "UChar") "." NumGet(addrword, 0, "UChar")
}
<
Related Pages~
|ListView|, |TreeView|, |Gui|, |GuiControl|, |GuiControlGet|, |Menu|
==============================================================================
*GuiControl*
+------------+~
| GuiControl |~
+------------+~
Makes a variety of changes to a control in a GUI window.
|GuiControl|, Sub-command, ControlID [, Param3 ]
Parameters~
Sub-command
-----------
See list below.
ControlID
---------
If the target control has an associated variable, specify the
variable's name as the ControlID (this method takes precedence over
the ones described next). For this reason, it is usually best to
assign a variable to any control that will later be accessed via
GuiControl or GuiControlGet, even if that control is not an
input-capable type (such as GroupBox or Text).
Otherwise, ControlID can be either ClassNN (the classname and instance
number of the control) or the name/text of the control, both of which
can be determined via Window Spy. When using name/text, the matching
behavior is determined by |SetTitleMatchMode|. Note: a picture control's
file name (as it was specified at the time the control was created)
may be used as its ControlID.
[v1.1.04+]
----------
ControlID can be the HWND of a control. As with any other value for
ControlID, the Gui must also be specified if the control is not on the
default Gui. Note: How do you do this if you're trying to update a
Text control? (Because the sub-command needs to be empty.) The
answer is to use something like this:
>
Gui,New ; imagine 2nd Gui
Gui,Add,Text,vmytext W120 H20 X20 Y20,hello text control here
; ...
; update
GuiControl,2:,mytext,hello text control update
<
If you don't need to use additional GUIs' then it's easy. The 'v'
parameter lets you associate a variable with the control as it
mentions in the doco quite rightly which then you can refer to with
GuiControl. The tricky bit is if it's a GUI other than the default GUI
you're referring to. End Note
Param3
------
This parameter is omitted except where noted in the list of
sub-commands below.
ErrorLevel~
[v1.1.04+]
----------
This command is able to throw an exception on failure. For more
information, see Runtime Errors.
ErrorLevel is set to 1 if the specified window/control does not exist
or some other problem prevented the command from working. Otherwise,
it is set to 0.
Sub-commands~
(Blank)
-------
Leave Sub-command blank to put new contents into the control
via Param3. Specifically:
Picture
-------
|Param3| should be the filename of the new image to load (see |Gui|
Picture for supported file types). Zero or more of the following
options may be specified immediately in front of the filename: >
*wN
<
(width N), >
*hN
<
(height N), and >
*IconN
<
(icon group number N in a DLL or EXE file). In the following example,
the default icon from the second icon group is loaded with a width of
100 and an automatic height via "keep aspect ratio": >
GuiControl,, MyPic, *icon2 *w100 *h-1 C:\My Application.exe
<
Specify >
*w0 *h0
<
to use the image's actual width and height. If >
*w
<
and >
*h
<
are omitted, the image will be scaled to fit the current size of the
control. When loading from a multi-icon .ICO file, specifying a width
and height also determines which icon to load. Note: Use only one
space or tab between the final option and the filename itself; any
other spaces and tabs are treated as part of the filename.
Text /Button /GroupBox /StatusBar
---------------------------------
Specify for Param3 the control's new text. Since the control will
not expand automatically, use >
GuiControl, Move, MyText, W300
<
if the control needs to be widened. For StatusBar, this sets the
text of the first part only. (use SB_SetText() for greater
flexibility).
Edit
-----
Any linefeeds (`n) in Param3 that lack a preceding carriage return
(`r) are automatically translated to CR+LF (`r`n) to make them display
properly. However, this is usually not a concern because the |Gui|
Submit and |GuiControlGet| OutputVar commands will automatically
undo this translation by replacing CR+LF with LF (`n).
Hotkey
------
Param3 can be blank to clear the control, or a set of modifiers with a
key name. Examples: >
^!c
^Numpad1
+Home
<
The only modifiers supported are ^ (Control), ! (Alt), and + (Shift).
See the key list for available key names.
Checkbox
--------
Param3 can be 0 to uncheck the button, 1 to check it, or -1 to give it
a gray checkmark. Otherwise, Param3 is assumed to be the control's new
caption/text. See Text below for how to override this behavior.
Radio
-----
Same as Checkbox above. However, if the radio button is being checked
(turned on) and it is a member of a multi-radio group, the other radio
buttons in its group will be automatically unchecked. To check a new
button within a radio group that only has one variable, specify for
ControlID the name/text of the button if it is not the
button with which the variable is directly associated.
DateTime /MonthCal
------------------
Specify for Param3 a date-time stamp in YYYYMMDDHH24MISS format.
Specify %A_Now% to use the current date and time (today). For
DateTime controls, Param3 may be omitted to cause the control to have
no date/time selected (if it was created with that ability). For
MonthCal controls, a range may be specified if the
control is multi-select.
UpDown /Slider /Progress
------------------------
Param3 should be the new position of the control. If a Param3's first
character is a plus sign, the number will be assumed to be an offset
from the current position. For example, +10 would increase the
position by 10 and >
+-10
<
(plus minus ten) would decrease it by 10. If the new position would
be outside the range of the control, the control is generally set to
the nearest valid value.
Tab /DropDownList /ComboBox /ListBox
------------------------------------
Param3 should contain a pipe-delimited list of entries to be
appended at the end of the control's list. To replace (overwrite) the
list instead, include a pipe as the first character (e.g. Red | Green
| Blue). To make the control empty, specify only a pipe character (|).
To have one of the entries pre-selected, include two pipes after it
(e.g. Red|Green||Blue). The separator between fields may be changed
to something other than pipe. For example, >
Gui +Delimiter`n
<
would change it to linefeed and Gui +DelimiterTab would change it to
tab (`t).
Tab controls
------------
In addition to the behavior described in the paragraph above, a tab's
sub-controls stay associated with their original tab number; that is,
they are never associated with their tab's actual display-name. For
this reason, renaming or removing a tab will not change the tab number
to which the sub-controls belong. For example, if there are three tabs
"Red | Green | Blue" and the second tab is removed by means of >
GuiControl,, MyTab, |Red|Blue
<
the sub-controls originally associated with Green will now be
associated with Blue. Because of this behavior, only tabs at the end
should generally be removed. Tabs that are removed in this way can be
added back later, at which time they will reclaim their original set
of controls.
|ListView| and |TreeView|: These are not supported when Sub-command is
blank. Instead, use the built-in |ListView| functions and |TreeView|
functions.
|GuiControl| , Text
-----------------
Behaves the same as the above except for: Checkbox /Radio : Param3
is treated as the new text/caption even if it is -1, 0, or 1.
DateTime : Param3 is treated as the new date /time format
displayed by the control. If Param3 is omitted, any custom format is
removed and the short-date format is put into effect. ComboBox:
Param3 is treated as the text to put directly into the
ComboBox's Edit control.
|GuiControl|, Move
----------------
Moves and/or resizes the control. Specify one or more of the following
option letters in Param3: X (the x-coordinate relative to the GUI
window's client area, which is the area not including title bar, menu
bar, and borders); Y (the y-coordinate), W (Width), H (Height).
(Specify each number as decimal, not hexadecimal.) For example:
>
GuiControl, Move, MyEdit, x10 y20 w200 h100
GuiControl, Move, MyEdit, % "x" VarX+10 "y" VarY+5 "w" VarW*2 "h" VarH*1.5
; Uses an expression via "% " prefix
<
|GuiControl|, MoveDraw
--------------------
Same as "Move" (above) except that it also repaints the region of the
GUI window occupied by the control. Although this may cause an
unwanted flickering effect when called repeatedly and rapidly, it
solves painting artifacts for certain control types such as
GroupBoxes. In v1.0.48.04+, the last parameter may be omitted to
redraw the control without moving it.
|GuiControl|, Focus
-----------------
Sets keyboard focus to the control. To be effective, the window
generally must not be minimized or hidden.
|GuiControl|, Enable / Disable
----------------------------
Enables or disables (grays out) the control. For Tab controls, this
will also enable or disable all of the tab's sub-controls. However,
any sub-control explicitly disabled via >
GuiControl Disable
<
will remember that setting and thus remain disabled even after its Tab
control is re-enabled. The word Disable or Enable may optionally be
followed immediately by a 0 or 1. A zero causes the effect to be
inverted. For example, Enable and Enable%VarContainingOne% would
both enable the control, but Enable%VarContainingZero% would disable
it.
|GuiControl|, Hide / Show
-----------------------
Hides or shows the control. For Tab controls, this will also show or
hide all of the tab's sub-controls. If you additionally want to
prevent a control's shortcut key (underlined letter) from working,
disable the control via >
GuiControl Disable
<
The word Hide or Show may optionally be followed immediately by a 0
or 1. A zero causes the effect to be inverted. For example, Show and
Show%VarContainingOne% would both show the control, but
Show%VarContainingZero% would hide it.
|GuiControl|, Delete (not yet implemented)
-----------------------------------------
This sub-command does not yet exist. As a workaround, use Hide and/or
Disable (above), or destroy and recreate the entire window via Gui
Destroy.
|GuiControl|, Choose, ControlID, N
--------------------------------
Sets the selection in a ListBox, DropDownList, ComboBox, or Tab
control to be the Nth entry. N should be 1 for the first entry, 2 for
the second, etc. If N is not an integer, the ChooseString method
described below will be used instead. [v1.1.06+]: If N is zero, the
ListBox, DropDownList or ComboBox's current selection is removed.
Unlike Control Choose, this sub-command will not trigger any
g-label associated with the control unless N is preceded by a pipe
character (even then, the g-label is triggered only when the new
selection is different than the old one, at least for Tab controls).
For example: >
GuiControl, Choose, MyListBox, |3
<
To additionally cause a finishing event to occur (a double-click in
the case of ListBox), include two leading pipes instead of one (this
is not supported for Tab controls).
To select or deselect all items in a multi-select ListBox, follow this
example:
>
Gui +LastFound ; Avoids the need to specify WinTitle below.
PostMessage, 0x185, 1, -1, ListBox1 ; Select all items. 0x185 is LB_SETSEL.
PostMessage, 0x185, 0, -1, ListBox1 ; Deselect all items.
GuiControl, Choose, ListBox1, 0 ; Deselect all items (requires v1.1.06+)
<
|GuiControl|, |ChooseString|, ControlID, String
-------------------------------------------
Sets the selection (choice) in a ListBox, DropDownList, ComboBox, or
Tab control to be the entry whose leading part matches String. The
search is not case sensitive. For example, if a the control contains
the item "UNIX Text", specifying the word unix (lowercase) would be
enough to select it. The pipe and double-pipe prefix are also
supported (see "Choose" above for details).
|GuiControl|, Font
----------------
Changes the control's font to the typeface, size, color, and style
currently in effect for its window. For example:
>
Gui, Font, s18 cRed Bold, Verdana
; If desired, use a line like this to set a new
; default font for the window.
GuiControl, Font, MyEdit ; Put the above font into effect for a control
<
|GuiControl|, +/-Option1 +/-Option2 ...
---------------------------------------
Add or remove various control-specific or general options and styles.
In the following example, the AltSubmit option is enabled but
control's g-label is removed:
>
GuiControl, +AltSubmit -g, MyListBox
<
In the next example, the OK button is made the new default button:
>
GuiControl, +Default, OK
<
Although styles and extended styles are also recognized, some of
them cannot be applied or removed after a control has been created.
ErrorLevel is set to 0 if at least one of the specified changes was
successfully applied. Otherwise, it is set to 1 to indicate that none
of the changes could be applied. Even if a change is successfully
applied, the control might choose to ignore it.
Remarks~
To operate upon a window other than the default (see below), include
its name or number followed by a colon in front of the sub-command as
in these examples:
>
GuiControl, MyGui:Show, MyButton
GuiControl, MyGui:, MyListBox, Item1|Item2
<
This is required even if ControlID is a control's associated variable
or HWND.
A GUI thread is defined as any thread launched as a result of a GUI
action. GUI actions include selecting an item from a GUI window's menu
bar, or triggering one of its g-labels (such as by pressing a button).
The default window name for a GUI thread is that of the window
that launched the thread. Non-GUI threads use 1 as their default.
Related~
|Gui|, GuiControlGet, Control
Examples~
>
GuiControl,, MyListBox, |Red|Green|Blue
; Replace the current list with a new list.
GuiControl,, MyEdit, New text line 1.`nNew text line 2.
GuiControl,, MyRadio2, 1
; Turn on this radio button and turn off all the others in its
; group.
GuiControl, Move, OK, x100 y200
; Move the OK button to a new location.
GuiControl, Focus, LastName
; Set keyboard focus to the control whose variable or text is
; "LastName".
<
==============================================================================
*GuiControlGet*
+---------------+~
| GuiControlGet |~
+---------------+~
Retrieves various types of information about a control in a GUI
window.
|GuiControlGet|, OutputVar [, Sub-command, ControlID, Param4 ]
Parameters~
OutputVar
---------
The name of the variable in which to store the result. If the command
cannot complete (see ErrorLevel below), this variable is made blank.
Sub-command~
See list below.
ControlID
---------
If blank or omitted, it behaves as though the name of the output
variable was specified. For example, |GuiControlGet|, MyEdit is the same
as >
GuiControlGet, MyEdit,, MyEdit.
<
If the target control has an associated variable, specify the
variable's name as the ControlID (this method takes precedence over
the ones described next). For this reason, it is usually best to
assign a variable to any control that will later be accessed via
GuiControl or GuiControlGet, even if that control is not input-capable
(such as GroupBox or Text).
Otherwise, ControlID can be either ClassNN (the classname and instance
number of the control) or the name/text of the control, both of which
can be determined via Window Spy. When using name/text, the matching
behavior is determined by |SetTitleMatchMode|. Note: a picture control's
file name (as it was specified at the time the control was created)
may be used as its ControlID.
[v1.1.04+]: ControlID can be the HWND of a control. As with any other
value for ControlID, the Gui must also be specified if the control is
not on the default Gui.
Param4
------
This parameter is omitted except where noted in the list of
sub-commands below.
ErrorLevel~
[v1.1.04+] This command is able to throw an exception on failure. For
more information, see Runtime Errors.
ErrorLevel is set to 1 if the specified window/control does not exist
or some other problem prevented the command from working. Otherwise,
it is set to 0.
Sub-commands~
(Blank)
-------
Leave Sub-command blank to retrieve the control's contents. All
control types are self-explanatory except the following:
Picture
-------
Retrieves the picture's file name as it was originally specified when
the control was created. This name does not change even if a new
picture file name is specified.
Edit
-----
Retrieves the contents but any line breaks in the text will be
represented as plain linefeeds (`n) rather than the traditional CR+LF
(`r`n) used by non-GUI commands such as |ControlGetText| and
|ControlSetText|.
Hotkey
------
Retrieves a blank value if there is no hotkey in the control.
Otherwise it retrieves the modifiers and key name. Examples:
>
^!C, ^Home, +^NumpadHome
<
Checkbox /Radio
---------------
Retrieves 1 if the control is checked, 0 if it is unchecked, or -1 if
it has a gray checkmark. To retrieve the control's text/caption
instead, specify the word Text for Param4. Note: Unlike the |Gui|
Submit command, radio buttons are always retrieved individually,
regardless of whether they are in a radio group.
UpDown /Slider /Progress
------------------------
Retrieves the control's current position.
Tab /DropDownList/ComboBox /ListBox
-----------------------------------
Retrieves the text of the currently selected item/tab (or its position
if the control has the AltSubmit property). For a ComboBox, if there
is no selected item, the text in the control's edit field is retrieved
instead. For a multi-select ListBox, the output uses the
window's current delimiter.
ListView and TreeView
---------------------
These are not supported when Sub-command is blank. Instead, use the
built-in ListView functions and TreeView functions.
StatusBar
---------
Retrieves only the first part's text.
ActiveX
-------
Retrieves a new wrapper object for the control's ActiveX component.
Note: To unconditionally retrieve any control's text/caption rather
than its contents, specify the word Text for Param4.
|GuiControlGet|, OutputVar, Pos
-----------------------------
Retrieves the position and size of the control. The position is
relative to the GUI window's client area, which is the area not
including title bar, menu bar, and borders. The information is stored
in four variables whose names all start with OutputVar. For example:
>
GuiControlGet, MyEdit, Pos
MsgBox The X coordinate is %MyEditX%. The Y coordinate is %MyEditY% The width is %MyEditW%. The height is %MyEditH%
<
Within a function, to create a set of variables that is global instead
of local, declare OutputVar as a global variable prior to using this
command (the converse is true for assume-global functions).
|GuiControlGet|, OutputVar, Focus
-------------------------------
Retrieves the control identifier (ClassNN) for the control that
currently has keyboard focus. Since the specified GUI window must be
active for one of its controls to have focus, OutputVar will be made
blank if it is not active. Example usage: >
GuiControlGet, focused_control, focus
<
|GuiControlGet|, OutputVar, FocusV [v1.0.43.06+]
-----------------------------------------------
Same as Focus (above) except that it retrieves the name of the focused
control's associated variable. If that control lacks an associated
variable, the first 63 characters of the control's text/caption is
retrieved instead (this is most often used to avoid giving each button
a variable name).
|GuiControlGet|, OutputVar, Enabled
---------------------------------
Retrieves 1 if the control is enabled or 0 if it is disabled.
|GuiControlGet|, OutputVar, Visible
---------------------------------
Retrieves 1 if the control is visible or 0 if it is hidden.
|GuiControlGet|, OutputVar, Hwnd [v1.0.46.16+]
---------------------------------------------
Retrieves the window handle (HWND) of the control. A control's HWND is
often used with |PostMessage|, |SendMessage|, and |DllCall|. Note:
HwndOutputVar is usually a more concise way to get the HWND.
|GuiControlGet|, OutputVar, Name [v1.1.03+]
-----------------------------------------
Retrieves the name of the control's associated variable if it
has one, otherwise OutputVar is made blank.
Remarks~
To operate upon a window other than the default (see below), include
its name or number followed by a colon in front of the sub-command as
in these examples:
>
GuiControlGet, MyEdit, MyGui:
GuiControlGet, MyEdit, MyGui:Pos
GuiControlGet, Outputvar, MyGui:Focus
<
This is required even if ControlID is a control's associated variable
or HWND
A GUI thread is defined as any thread launched as a result of a GUI
action. GUI actions include selecting an item from a GUI window's menu
bar, or triggering one of its g-labels (such as by pressing a
button).
The default window name for a GUI thread is that of the window
that launched the thread. Non-GUI threads use 1 as their default.
Related~
|Gui|, |GuiControl|, |ControlGet|
Examples~
>
GuiControlGet, MyEdit
GuiControlGet, CtrlContents,, MyEdit
; Same as the above except uses a non-default output variable.
GuiControlGet, MyCheckbox1
; Retrieves 1 if it is checked, 0 if it is unchecked.
GuiControlGet, MyCheckbox1,,, Text
; Retrieves the caption/text of the checkbox.
GuiControlGet, Pic, Pos, Static4
; The position/size will be stored in PicX, PicY, PicW, and PicH
<
==============================================================================
*Styles_Usable_by_Gui_and_GuiControl_Commands*
Styles Usable by the Gui and GuiControl Commands~
------------------------------------------------------------------------------
Table of Contents~
Styles Common to Gui /Parent Windows and Most Control Types
Text | Edit | UpDown | Picture
Button | Checkbox | Radio | GroupBox
DropDownList | ComboBox
ListBox | ListView | TreeView
DateTime | MonthCal
Slider | Progress | Tab | StatusBar*
Common styles~
default for GUI window
WS_POPUP, WS_CAPTION, WS_SYSMENU, WS_MINIMIZEBOX
forced for GUI window WS_CLIPSIBLINGS
*WS_BORDER* 0x800000
+/-Border. Creates a window that has a thin-line border.
*WS_POPUP*
0x80000000
Creates a pop-up window. This style cannot be used with the WS_CHILD
style.
*WS_CAPTION*
0xC00000
+/-Caption. Creates a window that has a title bar. This style is a
numerical combination of WS_BORDER and WS_DLGFRAME.
*WS_DISABLED* 0x8000000
+/-Disabled. Creates a window that is initially disabled.
*WS_DLGFRAME* 0x400000
Creates a window that has a border of a style typically used with
dialog boxes.
*WS_GROUP* 0x20000
+/-Group. Indicates that this control is the first one in a group of
controls. This style is automatically applied to manage the "only one
at a time" behavior of radio buttons. In the rare case where two
groups of radio buttons are added consecutively (with no other control
types in between them), this style may be applied manually to the
first control of the second radio group, which splits it off from the
first.
*WS_HSCROLL* 0x100000
Creates a window that has a horizontal scroll bar.
*WS_MAXIMIZE* 0x1000000
Creates a window that is initially maximized.
*WS_MAXIMIZEBOX* 0x10000
+/-MaximizeBox. Creates a window that has a maximize button. Cannot be
combined with the WS_EX_CONTEXTHELP style. The WS_SYSMENU style must
also be specified.
*WS_MINIMIZE* 0x20000000
Creates a window that is initially minimized.
*WS_MINIMIZEBOX* 0x20000
+/-MinimizeBox. Creates a window that has a minimize button. Cannot be
combined with the WS_EX_CONTEXTHELP style. The WS_SYSMENU style must
also be specified.
*WS_OVERLAPPED* 0
Creates an overlapped window. An overlapped window has a title bar and
a border. Same as the WS_TILED style.
*WS_OVERLAPPEDWINDOW* 0xCF0000
Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION,
WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles.
Same as the WS_TILEDWINDOW style.
*WS_POPUPWINDOW* 0x80880000
Creates a pop-up window with WS_BORDER, WS_POPUP, and WS_SYSMENU
styles. The WS_CAPTION and WS_POPUPWINDOW styles must be combined to
make the window menu visible.
*WS_SIZEBOX* 0x40000
+/-Resize. Creates a window that has a sizing border. Same as the
WS_THICKFRAME style.
*WS_SYSMENU* 0x80000
+/-SysMenu. Creates a window that has a window menu on its title bar.
The WS_CAPTION style must also be specified.
*WS_TABSTOP* 0x10000
+/-Tabstop. Specifies a control that can receive the keyboard focus
when the user presses the TAB key. Pressing the TAB key changes the
keyboard focus to the next control with the WS_TABSTOP style.
*WS_THICKFRAME* 0x40000
Creates a window that has a sizing border. Same as the WS_SIZEBOX style
*WS_VSCROLL* 0x200000
Creates a window that has a vertical scroll bar.
*WS_VISIBLE* 0x10000000
Creates a window that is initially visible.
*WS_CHILD* 0x40000000
Creates a child window. A window with this style cannot have a menu
bar. This style cannot be used with the WS_POPUP style.
Text styles ~
default ~
None
forced ~
None
*SS_BLACKFRAME* 0x7
Specifies a box with a frame drawn in the same color as the window
frames. This color is black in the default color scheme.
*SS_BLACKRECT* 0x4
Specifies a rectangle filled with the current window frame color. This
color is black in the default color scheme.
*SS_CENTER* 0x1
+/-Center. Specifies a simple rectangle and centers the error value
text in the rectangle. The control automatically wraps words that
extend past the end of a line to the beginning of the next centered
line.
*SS_ETCHEDFRAME* 0x12
Draws the frame of the static control using the EDGE_ETCHED edge style.
*SS_ETCHEDHORZ* 0x10
Draws the top and bottom edges of the static control using the
EDGE_ETCHED edge style.
*SS_ETCHEDVERT* 0x11
Draws the left and right edges of the static control using the
EDGE_ETCHED edge style.
*SS_GRAYFRAME* 0x8
Specifies a box with a frame drawn with the same color as the screen
background (desktop). This color is gray in the default color scheme
*SS_GRAYRECT* 0x5
Specifies a rectangle filled with the current screen background color.
This color is gray in the default color scheme.
*SS_LEFT* 0
+/-Left. This is the default. It specifies a simple rectangle and
left-aligns the text in the rectangle. The text is formatted before it
is displayed. Words that extend past the end of a line are
automatically wrapped to the beginning of the next left-aligned line.
Words that are longer than the width of the control are truncated.
*SS_LEFTNOWORDWRAP* 0xC
+/-Wrap. Specifies a rectangle and left-aligns the text in the
rectangle. Tabs are expanded, but words are not wrapped. Text that
extends past the end of a line is clipped.
*SS_NOPREFIX* 0x80
Prevents interpretation of any ampersand (&) characters in the
control's text as accelerator prefix characters. This can be useful
when file names or other strings that might contain an ampersand (&)
must be displayed within a text control
*SS_NOTIFY* 0x100
Sends the parent window the STN_CLICKED notification when the user
clicks the control.
*SS_RIGHT* 0x2
+/-Right. Specifies a rectangle and right-aligns the specified text in
the rectangle.
*SS_SUNKEN* 0x1000
Draws a half-sunken border around a static control.
*SS_WHITEFRAME* 0x9
Specifies a box with a frame drawn with the same color as the window
background. This color is white in the default color scheme.
*SS_WHITERECT* 0x6
Specifies a rectangle filled with the current window background color.
This color is white in the default color scheme.
Edit styles~
default ~
WS_TABSTOP and WS_EX_CLIENTEDGE (extended style E0x200)
If an Edit is auto-detected as multi-line due to its starting
contents containing multiple lines, its height being taller
than 1 row, or its row-count having been explicitly specified
as greater than 1, the following styles will be applied by
default: WS_VSCROLL, ES_WANTRETURN, and ES_AUTOVSCROLL
If an Edit is auto-detected as a single line, it defaults to
having ES_AUTOHSCROLL.
forced ~
None
*ES_AUTOHSCROLL* 0x80
+/-Wrap for multi-line edits, and +/-Limit for single-line edits.
Automatically scrolls text to the right by 10 characters when the user
types a character at the end of the line. When the user presses the
ENTER key, the control scrolls all text back to the zero position.
*ES_AUTOVSCROLL* 0x40
Scrolls text up one page when the user presses the ENTER key on the
last line.
*ES_CENTER* 0x1
+/-Center. Centers text in a multiline edit control.
*ES_LOWERCASE* 0x10
+/-Lowercase. Converts all characters to lowercase as they are typed
into the edit control.
*ES_NOHIDESEL* 0x100
Negates the default behavior for an edit control. The default behavior
hides the selection when the control loses the input focus and inverts
the selection when the control receives the input focus. If you
specify ES_NOHIDESEL, the selected text is inverted, even if the
control does not have the focus.
*ES_NUMBER* 0x2000
+/-Number. Prevents the user from typing anything other than digits in
the control.
*ES_OEMCONVERT* 0x400
This style is most useful for edit controls that contain file names.
*ES_MULTILINE* 0x4
+/-Multi. Designates a multiline edit control. The default is a
single-line edit control.
*ES_PASSWORD* 0x20
+/-Password. Displays a masking character in place of each character
that is typed into the edit control, which conceals the text.
*ES_READONLY* 0x800
+/-ReadOnly. Prevents the user from typing or editing text in the edit
control.
*ES_RIGHT* 0x2
+/-Right. Right-aligns text in a multiline edit control.
*ES_UPPERCASE* 0x8
+/-Uppercase. Converts all characters to uppercase as they are typed
into the edit control.
*ES_WANTRETURN* 0x1000
+/-WantReturn. Specifies that a carriage return be inserted when the
user presses the ENTER key while typing text into a multiline edit
control in a dialog box. If you do not specify this style, pressing
the ENTER key has the same effect as pressing the dialog box's default
push button. This style has no effect on a single-line edit control.
UpDown styles~
default ~
UDS_ARROWKEYS, UDS_ALIGNRIGHT, UDS_SETBUDDYINT, and
UDS_AUTOBUDDY.
forced ~
None
*UDS_WRAP* 0x1
Named option "Wrap". Causes the control to wrap around to the other
end of its range when the user attempts to go beyond the minimum or
maximum. Without Wrap, the control stops when the minimum or maximum
is reached.
*UDS_SETBUDDYINT* 0x2
Causes the UpDown control to set the text of the buddy control (using
the WM_SETTEXT message) when the position changes. However, if the
buddy is a ListBox, the ListBox's current selection is changed
instead.
*UDS_ALIGNRIGHT* 0x4
Named option "Right" (default). Positions UpDown on the right side of
its buddy control.
*UDS_ALIGNLEFT* 0x8
Named option "Left". Positions UpDown on the left side of its buddy
control.
*UDS_AUTOBUDDY* 0x10
Automatically selects the previous control in the z-order as the
UpDown control's buddy control.
*UDS_ARROWKEYS* 0x20
Allows the user to press the Up or Down arrow keys on the keyboard to
increase or decrease the UpDown control's position.
*UDS_HORZ* 0x40
Named option "Horz". Causes the control's arrows to point left and
right instead of up and down.
*UDS_NOTHOUSANDS* 0x80
Does not insert a thousands separator between every three decimal
digits in the buddy control.
*UDS_HOTTRACK* 0x100
Causes the control to exhibit "hot tracking" behavior. That is, it
highlights the control's buttons as the mouse passes over them. This
style requires Microsoft Windows 98 or Windows 2000. If the system is
running Windows 95 NT4, the flag is ignored. The flag is also ignored
on Windows XP when the desktop theme overrides it.
(hex)
The number format displayed inside the buddy control may be
changed from decimal
to hexadecimal by following this example:
>
Gui +LastFound
SendMessage, 1133, 16, 0, msctls_updown321
; 1133 is UDM_SETBASEHowever, this affects only the
; buddy control, not the UpDown's reported position.
<
Picture styles~
default ~
None
forced ~
*S_ICON* for icons and cursors.
*SS_BITMAP* for other image types.
*SS_REALSIZECONTROL* 0x40
[Windows XP or later] Adjusts the bitmap to fit the size of the
control.
*SS_CENTERIMAGE* 0x200
Centers the bitmap in the control. If the bitmap is too large, it will
be clipped. For text controls If the control contains a single line of
text, the text is centered vertically within the available height of
the control
Microsoft Windows XP: This style bit no longer results in unused
portions of the control being filled with the color of the top left
pixel of the bitmap or icon. Unused portions of the control will
remain the background color.
Button, Checkbox , Radio , and GroupBox styles~
default ~
BS_MULTILINE (except for GroupBox, and except for buttons,
checkboxes, and radios that have no explicitly set width or
height, nor any CR/LF characters in their text)
WS_TABSTOP (except for GroupBox) -- however, radio buttons
other than the first of each radio group lack WS_TABSTOP by
default. In addition, radio buttons have BS_NOTIFY so that
double clicks can be detected.
forced ~
Button
------
BS_PUSHBUTTON or BS_DEFPUSHBUTTON
Radio
-----
BS_AUTORADIOBUTTON
Checkbox
--------
BS_AUTOCHECKBOX or BS_AUTO3STATE
GroupBox
--------
BS_GROUPBOX
*BS_LEFT* 0x100
+/-Left. Left-aligns the text.
*BS_PUSHLIKE* 0x1000
Makes a checkbox or radio button look and act like a push button. The
button looks raised when it isn't pushed or checked, and sunken when
it is pushed or checked.
*BS_RIGHT* 0x200
+/-Right. Right-aligns the text.
*BS_RIGHTBUTTON* 0x20
+Right (i.e. +Right includes both BS_RIGHT and BS_RIGHTBUTTON, but
-Right removes only BS_RIGHT, not BS_RIGHTBUTTON). Positions a
checkbox square or radio button circle on the right side of the
control's available width instead of the left.
*BS_BOTTOM* 0x800
Places the text at the bottom of the control's available height.
*BS_CENTER* 0x300
+/-Center. Centers the text horizontally within the control's
available width.
*BS_DEFPUSHBUTTON* 0x1
+/-Default. Creates a push button with a heavy black border. If the
button is in a dialog box, the user can select the button by pressing
the ENTER key, even when the button does not have the input focus.
This style is useful for enabling the user to quickly select the most
likely option.
*BS_MULTILINE* 0x2000
+/-Wrap. Wraps the text to multiple lines if the text is too long to
fit on a single line in the control's available width. This also
allows linefeed (`n) to start new lines of text.
*BS_TOP* 0x400
Places text at the top of the control's available height.
*BS_VCENTER* 0xC00
Vertically centers text in the control's available height.
*BS_FLAT* 0x8000
Specifies that the button is two-dimensional; it does not use the
default shading to create a 3-D effect.
DropDownList and ComboBox styles~
default ~
WS_TABSTOP (+/-Tabstop)
DropDownList: WS_VSCROLL
ComboBox: WS_VSCROLL, CBS_AUTOHSCROLL
forced ~
DropDownList: CBS_DROPDOWNLIST
ComboBox: Either CBS_DROPDOWN or CBS_SIMPLE
*CBS_AUTOHSCROLL* 0x40
+/-Limit. Automatically scrolls the text in an edit control to the
right when the user types a character at the end of the line. If this
style is not set, only text that fits within the rectangular boundary
is enabled.
*CBS_DISABLENOSCROLL* 0x800
Shows a disabled vertical scroll bar in the list box when the box does
not contain enough items to scroll. Without this style, the scroll bar
is hidden when the list box does not contain enough items.
*CBS_LOWERCASE* 0x4000
+/-Lowercase. Converts to lowercase any uppercase characters that are
typed into the edit control of a combo box.
*CBS_NOINTEGRALHEIGHT* 0x400
Specifies that the combo box will be exactly the size specified by the
application when it created the combo box. Usually, Windows CE sizes a
combo box so that it does not display partial items.
*CBS_OEMCONVERT*
0x80
Converts text typed in the combo box edit control from the Windows CE
character set to the OEM character set and then back to the Windows CE
set. This style is most useful for combo boxes that contain file
names. It applies only to combo boxes created with the CBS_DROPDOWN
style.
*CBS_SIMPLE* 0x1
+/-Simple (ComboBox only). Displays the list box at all times. The
current selection in the list box is displayed in the edit control.
*CBS_SORT* 0x100
+/-Sort. Sorts the items in the drop-list alphabetically.
*CBS_UPPERCASE* 0x2000
+/-Uppercase. Converts to uppercase any lowercase characters that are
typed into the edit control of a ComboBox.
ListBox styles~
default ~
WS_TABSTOP, LBS_USETABSTOPS, WS_VSCROLL, and WS_EX_CLIENTEDGE
(extended style E0x200).
forced ~
*LBS_NOTIFY* (supports detection of double-clicks)
*LBS_DISABLENOSCROLL* 0x1000
Shows a disabled vertical scroll bar for the list box when the box
does not contain enough items to scroll. If you do not specify this
style, the scroll bar is hidden when the list box does not contain
enough items.
*LBS_NOINTEGRALHEIGHT* 0x100
Specifies that the list box will be exactly the size specified by the
application when it created the list box.
*LBS_EXTENDEDSEL* 0x800
+/-Multi. Allows multiple selections via control-click and
shift-click. LBS_MULTIPLESEL 0x8 A simplified version of multi-select
in which control-click and shift-click are not necessary because
normal left clicks serve to extend the selection or de-select a
selected item.
*LBS_NOSEL* 0x4000
+/-ReadOnly. Specifies that the user can view list box strings but
cannot select them.
*LBS_SORT* 0x2
+/-Sort. Sorts the items in the list box alphabetically.
*LBS_USETABSTOPS* 0x80
Enables a ListBox to recognize and expand tab characters when drawing
its strings. The default tab positions are 32 dialog box units. A
dialog box unit is equal to one-fourth of the current dialog box
base-width unit.
ListView styles~
default ~
WS_TABSTOP, LVS_REPORT, LVS_SHOWSELALWAYS, LVS_EX_FULLROWSELECT,
LVS_EX_HEADERDRAGDROP, WS_EX_CLIENTEDGE (E0x200)
forced ~
None
*LVS_ALIGNLEFT* 0x800
Items are left-aligned in icon and small icon view.
*LVS_ALIGNTOP* 0
Items are aligned with the top of the list-view control in icon and
small icon view. This is the default.
*LVS_AUTOARRANGE* 0x100
Icons are automatically kept arranged in icon and small icon view.
*LVS_EDITLABELS* 0x200
+/-ReadOnly. Specifying -ReadOnly (or +0x200) allows the user to edit
the first field of each row in place.
*LVS_ICON* 0
+Icon. Specifies large-icon view.
*LVS_LIST* 0x3
+List. Specifies list view.
*LVS_NOCOLUMNHEADER* 0x4000
+/-Hdr. Avoids displaying column headers in report view.
*LVS_NOLABELWRAP* 0x80
Item text is displayed on a single line in icon view. By default, item
text may wrap in icon view.
*LVS_NOSCROLL* 0x2000
Scrolling is disabled. All items must be within the client area. This
style is not compatible with the LVS_LIST or LVS_REPORT styles.
*LVS_NOSORTHEADER* 0x8000
+/-NoSortHdr. Column headers do not work like buttons. This style can
be used if clicking a column header in report view does not carry out
an action, such as sorting.
*LVS_OWNERDATA* 0x1000
This style specifies a virtual list-view control (not directly
supported by AutoHotkey).
*LVS_OWNERDRAWFIXED* 0x400
The owner window can paint items in report view in response to
WM_DRAWITEM messages (not directly supported by AutoHotkey).
*LVS_REPORT* 0x1
+Report. Specifies report view.
*LVS_SHAREIMAGELISTS* 0x40
The image list will not be deleted when the control is destroyed. This
style enables the use of the same image lists with multiple list-view
controls.
*LVS_SHOWSELALWAYS* 0x8
The selection, if any, is always shown, even if the control does not
have keyboard focus.
*LVS_SINGLESEL* 0x4
+/-Multi. Only one item at a time can be selected. By default,
multiple items can be selected.
*LVS_SMALLICON* 0x2
+IconSmall. Specifies small-icon view.
*LVS_SORTASCENDING* 0x10
+/-Sort. Rows are sorted in ascending order based on the contents of
the first field.
*LVS_SORTDESCENDING* 0x20
+/-SortDesc. Same as above but in descending order.
*LVS_EX_BORDERSELECT* LV0x8000
When an item is selected the border color of the item changes rather
than the item being highlighted (might be non-functional in recent
operating systems).
*LVS_EX_CHECKBOXES* LV0x4
+/-Checked. Displays a checkbox with each item. When set to this
style, the control creates and sets a state image list with two images
using DrawFrameControl. State image 1 is the unchecked box, and state
image 2 is the checked box. Setting the state image to zero removes
the check box altogether.
Windows XP or later: Checkboxes are visible and functional with all
list-view modes except the tile view mode introduced in Windows XP.
Clicking a checkbox in tile view mode only selects the item; the state
does not change.
*LVS_EX_FLATSB* LV0x100
Enables flat scroll bars in the list view.
*LVS_EX_FULLROWSELECT* LV0x20
When a row is selected, all its fields are highlighted. This style is
available only in conjunction with the LVS_REPORT style.
*LVS_EX_GRIDLINES* LV0x1
+/-Grid. Displays gridlines around rows and columns. This style is
available only in conjunction with the LVS_REPORT style.
*LVS_EX_HEADERDRAGDROP* LV0x10
Enables drag-and-drop reordering of columns in a list-view control.
This style is only available to list-view controls that use the
LVS_REPORT style.
*LVS_EX_INFOTIP* LV0x400
When a list-view control uses the LVS_EX_INFOTIP style, the
LVN_GETINFOTIP notification message is sent to the parent window
before displaying an item's ToolTip.
*LVS_EX_LABELTIP* LV0x4000
If a partially hidden label in any list-view mode lacks ToolTip text,
the list-view control will unfold the label. If this style is not set,
the list-view control will unfold partly hidden labels only for the
large icon mode. Requires Windows XP or later, or the DLLs distributed
with Internet Explorer 5.0 or later. Note: On some versions of
Windows, this style might not work properly if the GUI window is set
to be always-on-top.
*LVS_EX_MULTIWORKAREAS* LV0x2000
If the list-view control has the LVS_AUTOARRANGE style, the control
will not autoarrange its icons until one or more work areas are
defined (see LVM_SETWORKAREAS). To be effective, this style must be
set before any work areas are defined and any items have been added to
the control.
*LVS_EX_ONECLICKACTIVATE* LV0x40
The list-view control sends an LVN_ITEMACTIVATE notification message
to the parent window when the user clicks an item. This style also
enables hot tracking in the list-view control. Hot tracking means that
when the cursor moves over an item, it is highlighted but not
selected.
*LVS_EX_REGIONAL* LV0x200
Sets the list-view window region to include only the item icons and
text using SetWindowRgn. Any area that is not part of an item is
excluded from the window region. This style is only available to
list-view controls that use the LVS_ICON style.
*LVS_EX_SIMPLESELECT* LV0x100000
In icon view, moves the state image of the control to the top right of
the large icon rendering. In views other than icon view there is no
change. When the user changes the state by using the space bar, all
selected items cycle over, not the item with the focus. Requires
Windows XP or later.
*LVS_EX_SUBITEMIMAGES* LV0x2
Allows images to be displayed for fields beyond the first. This style
is available only in conjunction with the LVS_REPORT style.
*LVS_EX_TRACKSELECT* LV0x8
Enables hot-track selection in a list-view control. Hot track
selection means that an item is automatically selected when the cursor
remains over the item for a certain period of time. The delay can be
changed from the default system setting with a LVM_SETHOVERTIME
message. This style applies to all styles of list-view control. You
can check whether hot-track selection is enabled by calling
SystemParametersInfo.
*LVS_EX_TWOCLICKACTIVATE* LV0x80
The list-view control sends an LVN_ITEMACTIVATE notification message
to the parent window when the user double-clicks an item. This style
also enables hot tracking in the list-view control. Hot tracking means
that when the cursor moves over an item, it is highlighted but not
selected.
*LVS_EX_UNDERLINECOLD* LV0x1000
Causes those non-hot items that may be activated to be displayed with
underlined text. This style requires that LVS_EX_TWOCLICKACTIVATE be
set also.
*LVS_EX_UNDERLINEHOT* LV0x800
Causes those hot items that may be activated to be displayed with
underlined text. This style requires that LVS_EX_ONECLICKACTIVATE or
LVS_EX_TWOCLICKACTIVATE also be set.
TreeView styles~
default ~
WS_TABSTOP, TVS_SHOWSELALWAYS, TVS_HASLINES, TVS_LINESATROOT,
TVS_HASBUTTONS, WS_EX_CLIENTEDGE (E0x200)
forced ~
None
*TVS_CHECKBOXES* 0x100
+/-Checked. Displays a checkbox next to each item.
*TVS_DISABLEDRAGDROP* 0x10
Prevents the tree-view control from sending TVN_BEGINDRAG notification
messages.
*TVS_EDITLABELS* 0x8
+/-ReadOnly. Allows the user to edit the names of tree-view items.
*TVS_FULLROWSELECT* 0x1000
Enables full-row selection in the tree view. The entire row of the
selected item is highlighted, and clicking anywhere on an item's row
causes it to be selected. This style cannot be used in conjunction
with the TVS_HASLINES style. TVS_HASBUTTONS 0x1 +/-Buttons. Displays
plus (+) and minus (-) buttons next to parent items. The user clicks
the buttons to expand or collapse a parent item's list of child items.
To include buttons with items at the root of the tree view,
*TVS_LINESHASBUTTONS* 0x1
+/-Buttons. Displays plus (+) and minus (-) buttons next to parent
items. The user clicks the buttons to expand or collapse a parent
item's list of child items. To include buttons with items at the root
of the tree view, TVS_LINESATROOT must also be specified.
*TVS_HASLINES* 0x2
+/-Lines. Uses lines to show the hierarchy of items.
*TVS_INFOTIP* 0x800
Obtains ToolTip information by sending the TVN_GETINFOTIP notification.
*TVS_LINESATROOT* 0x4
+/-Lines. Uses lines to link items at the root of the tree-view
control. This value is ignored if TVS_HASLINES is not also specified.
*TVS_NOHSCROLL* 0x8000
+/-HScroll. Disables horizontal scrolling in the control. The control
will not display any horizontal scroll bars.
*TVS_NONEVENHEIGHT* 0x4000
Sets the height of the items to an odd height with the
TVM_SETITEMHEIGHT message. By default, the height of items must be an
even value.
*TVS_NOSCROLL* 0x2000
Disables both horizontal and vertical scrolling in the control. The
control will not display any scroll bars.
*TVS_NOTOOLTIPS* 0x80
Disables ToolTips.
*TVS_RTLREADING* 0x40
Causes text to be displayed from right-to-left (RTL). Usually, windows
display text left-to-right (LTR).
*TVS_SHOWSELALWAYS* 0x20
Causes a selected item to remain selected when the tree-view control
loses focus.
*TVS_SINGLEEXPAND* 0x400
Causes the item being selected to expand and the item being unselected
to collapse upon selection in the tree-view. If the user holds down
the CTRL key while selecting an item, the item being unselected will
not be collapsed.
*TVS_TRACKSELECT* 0x200
Enables hot tracking of the mouse in a tree-view control.
DateTime styles~
default ~
DTS_SHORTDATECENTURYFORMAT and WS_TABSTOP (+/-Tabstop)
forced ~
None
*DTS_UPDOWN* 0x1
Provides an up-down control to the right of the control to modify
date-time values, which replaces the of the drop-down month calendar
that would otherwise be available.
*DTS_SHOWNONE* 0x2
Displays a checkbox inside the control that users can uncheck to make
the control have no date/time selected. Whenever the control has no
date/time, Gui Submit and GuiControlGet will retrieve a blank value
(empty string).
*DTS_SHORTDATEFORMAT* 0x0
Displays the date in short format. In some locales, it looks like
6/1/05 or 6/1/2005. On older operating systems, a two-digit year might
be displayed. This is why DTS_SHORTDATECENTURYFORMAT is the default
and not DTS_SHORTDATEFORMAT.
*DTS_LONGDATEFORMAT* 0x4
Format option "LongDate". Displays the date in long format. In some
locales, it looks like Wednesday, June 01, 2005.
DTS_SHORTDATECENTURYFORMAT 0xC Format option blank/omitted. Displays
the date in short format with four-digit year. In some locales, it
looks like 6/1/2005. If the system's version of Comctl32.dll is older
than 5.8, this style is not supported and DTS_SHORTDATEFORMAT is
automatically substituted.
*DTS_TIMEFORMAT* 0x9
Format option "Time". Displays only the time, which in some locales
looks like 5:31:42 PM.
*DTS_APPCANPARSE* 0x10
Not yet supported. Allows the owner to parse user input and take
necessary action. It enables users to edit within the client area of
the control when they press the F2 key. The control sends
DTN_USERSTRING notification messages when users are finished.
*DTS_RIGHTALIGN* 0x20
+/-Right. The calendar will drop down on the right side of the control
instead of the left.
(colors inside the drop-down calendar)
The colors of the day numbers inside the drop-down calendar obey that
set by the Gui Font command or the c (Color) option. To change the
colors of other parts of the calendar, follow this example:
>
Gui +LastFound
SendMessage, 0x1006, 4, 0xFFAA99, SysDateTimePick321
; 0x1006 is DTM_SETMCCOLOR. 4 is MCSC_MONTHBK
; (background color). The color must be specified in
; BGR vs. RGB format (red and blue components swapped).
<
MonthCal styles~
default ~
None
forced ~
None
*MCS_DAYSTATE* 0x1
Makes the control send MCN_GETDAYSTATE notifications to request
information about which days should be displayed in bold. [Not yet
supported]
*MCS_MULTISELECT* 0x2
Named option "Multi". Allows the user to select a range of dates
rather than being limited to a single date. By default, the maximum
range is 366 days, which can be changed by sending the
MCM_SETMAXSELCOUNT message to the control. For example:
>
Gui +LastFound
SendMessage, 0x1004, 7, 0, SysMonthCal321
; 7 days. 0x1004 is MCM_SETMAXSELCOUNT.
<
*MCS_WEEKNUMBERS* 0x4
Displays week numbers (1-52) to the left of each row of days. Week 1
is defined as the first week that contains at least four days.
*MCS_NOTODAYCIRCLE* 0x8
Prevents the circling of today's date within the control.
*MCS_NOTODAY* 0x10
Prevents the display of today's date at the bottom of the control.
(colors)
--------
The colors of the day numbers inside the calendar obey that set by the
Gui Font command or the c (Color) option. To change the colors of
other parts of the calendar, follow this example:
>
Gui +LastFound
SendMessage, 0x100A, 5, 0xFFAA99, SysMonthCal321
; 0x100A is MCM_SETCOLOR. 5 is MCSC_TITLETEXT (color
; of title text). The color must be specified in BGR
; vs. RGB format (red and blue components swapped).
<
Slider styles~
default ~
WS_TABSTOP (+/-Tabstop)
forced ~
None
*TBS_VERT* 0x2
+/-Vertical. The control is oriented vertically.
*TBS_LEFT* 0x4
+/-Left. The control displays tick marks at the top of the control (or
to its left if TBS_VERT is present). Same as TBS_TOP
*TBS_TOP* 0x4
same as TBS_LEFT.
*TBS_BOTH* 0x8
+/-Center. The control displays tick marks on both sides of the
control. This will be both top and bottom when used with TBS_HORZ or
both left and right if used with TBS_VERT.
*TBS_AUTOTICKS* 0x1
The control has a tick mark for each increment in its range of values.
Use +/-TickInterval to have more flexibility.
*TBS_ENABLESELRANGE* 0x20
The control displays a selection range only. The tick marks at the
starting and ending positions of a selection range are displayed as
triangles (instead of vertical dashes), and the selection range is
highlighted (highlighting might require that the theme be removed via
Gui -theme).
To set the selection range, follow this example, which sets the
starting position to 55 and the ending position to 66:
>
SendMessage, 1035, 1, 55, msctls_trackbar321, WinTitle
SendMessage, 1036, 1, 66, msctls_trackbar321, WinTitle
<
*TBS_FIXEDLENGTH* 0x40
+/-Thick. Allows the thumb's size to be changed.
*TBS_NOTHUMB* 0x80
The control does not display the moveable bar.
*TBS_NOTICKS* 0x10
+/-NoTicks. The control does not display any tick marks.
*TBS_TOOLTIPS* 0x100
+/-Tooltip. The control supports ToolTips. When a control is created
using this style, it automatically creates a default ToolTip control
that displays the slider's current position. You can change where the
ToolTips are displayed by using the TBM_SETTIPSIDE message. Windows 95
and NT4 require Internet Explorer 3.0 or later to support this style.
TBS_REVERSED 0x200 Unfortunately, this style has no effect on the
actual behavior of the control, so there is probably no point in using
it (instead, use +Invert in the control's options to reverse it).
Depending on OS version, this style might require Internet Explorer
5.0 or greater.
*TBS_DOWNISLEFT* 0x400
Unfortunately, this style has no effect on the actual behavior of the
control, so there is probably no point in using it. Depending on OS
version, this style might require Internet Explorer 5.01 or greater.
Progress styles~
default ~
PBS_SMOOTH
forced ~
None
*PBS_SMOOTH* 0x1
+/-Smooth. The progress bar displays progress status in a smooth
scrolling bar instead of the default segmented bar. When this style is
present, the control automatically reverts to the Classic Theme
appearance on Windows XP or later. Windows 95 and NT4 require Internet
Explorer 3.0 or later to support this option.
*PBS_VERTICAL* 0x4
+/-Vertical. The progress bar displays progress status vertically,
from bottom to top. Windows 95 and NT4 require Internet Explorer 3.0
or later to support this option.
*PBS_MARQUEE* 0x8
[Requires Windows XP or later] The progress bar moves like a marquee;
that is, each change to its position causes the bar to slide further
along its available length until it wraps around to the other side. A
bar with this style has no defined position. Each attempt to change
its position will instead slide the bar by one increment.
This style is typically used to indicate an ongoing operation whose
completion time is unknown.
Tab styles~
default ~
WS_TABSTOP and TCS_MULTILINE
forced ~
*WS_CLIPSIBLINGS*
TCS_OWNERDRAWFIXED: forced on or off as required by the control's
background color and/or text color.
*TCS_SCROLLOPPOSITE* 0x1
Unneeded tabs scroll to the opposite side of the control when a tab is
selected.
*TCS_BOTTOM* 0x2
+/-Bottom. Tabs appear at the bottom of the control instead of the
top.
*TCS_RIGHT* 0x2
Tabs appear vertically on the right side of controls that use the
TCS_VERTICAL style.
*TCS_MULTISELECT* 0x4
Multiple tabs can be selected by holding down CTRL when clicking. This
style must be used with the TCS_BUTTONS style.
*TCS_FLATBUTTONS* 0x8
Selected tabs appear as being indented into the background while other
tabs appear as being on the same plane as the background. This style
only affects tab controls with the TCS_BUTTONS style.
*TCS_FORCEICONLEFT* 0x10
Icons are aligned with the left edge of each fixed-width tab. This
style can only be used with the TCS_FIXEDWIDTH style.
*TCS_FORCELABELLEFT* 0x20
Labels are aligned with the left edge of each fixed-width tab; that
is, the label is displayed immediately to the right of the icon
instead of being centered.
This style can only be used with the TCS_FIXEDWIDTH style, and it
implies the TCS_FORCEICONLEFT style.
*TCS_HOTTRACK* 0x40
Items under the pointer are automatically highlighted
*TCS_VERTICAL* 0x80
+/-Left or +/-Right. Tabs appear at the left side of the control, with
tab text displayed vertically. This style is valid only when used with
the TCS_MULTILINE style. To make tabs appear on the right side of the
control, also use the TCS_RIGHT style.
This style will not correctly display the tabs if a custom background
color or text color is in effect. To workaround this, specify
-Background and/or cDefault in the tab control's options.
*TCS_BUTTONS* 0x100
+/-Buttons. Tabs appear as buttons, and no border is drawn around the
display area.
*TCS_SINGLELINE* 0
+/-Wrap. Only one row of tabs is displayed. The user can scroll to see
more tabs, if necessary. This style is the default.
*TCS_MULTILINE* 0x200
+/-Wrap. Multiple rows of tabs are displayed, if necessary, so all
tabs are visible at once.
*TCS_RIGHTJUSTIFY* 0
This is the default. The width of each tab is increased, if necessary,
so that each row of tabs fills the entire width of the tab control.
This window style is ignored unless the TCS_MULTILINE style is also
specified.
*TCS_FIXEDWIDTH* 0x400
All tabs are the same width. This style cannot be combined with the
TCS_RIGHTJUSTIFY style.
*TCS_RAGGEDRIGHT* 0x800
Rows of tabs will not be stretched to fill the entire width of the
control. This style is the default.
*TCS_FOCUSONBUTTONDOWN* 0x1000
The tab control receives the input focus when clicked.
*TCS_OWNERDRAWFIXED* 0x2000
The parent window is responsible for drawing tabs.
*TCS_TOOLTIPS* 0x4000
The tab control has a tooltip control associated with it.
*TCS_FOCUSNEVER* 0x8000
The tab control does not receive the input focus when clicked.
StatusBar styles~
default ~
SBARS_TOOLTIPS and SBARS_SIZEGRIP (the latter only if the window is resizable).
forced ~
None
*SBARS_TOOLTIPS* 0x800
Displays a tooltip when the mouse hovers over a part of the status bar
that: 1) has too much text to be fully displayed; or 2) has an icon
but no text.
The text of the ToolTip can be set via:
>
Gui +LastFound
SendMessage, 0x410, 0, "Text to display", msctls_statusbar321
<
The bold 0 above is the zero-based part number. To use a part other
than the first, specify 1 for second, 2 for the third, etc. NOTE: The
ToolTip might never appear on certain OS versions.
*SBARS_SIZEGRIP* 0x100
Includes a sizing grip at the right end of the status bar. A sizing
grip is similar to a sizing border; it is a rectangular area that the
user can click and drag to resize the parent window.
==============================================================================
*WinMove*
+---------+~
| WinMove |~
+---------+~
Changes the position and/or size of the specified window.
|WinMove|, X , Y
|WinMove|, WinTitle , WinText, X, Y [, Width, Height, ExcludeTitle,
ExcludeText ]
Parameters~
X , Y
-----
The X and Y coordinates (in pixels) of the upper left corner of the
target window's new location, which can be expressions. The upper-left
pixel of the screen is at 0, 0.
If these are the only parameters given with the command, the Last
Found Window will be used as the target window.
Otherwise, X and/or Y can be omitted, in which case the current
position is used.
WinTitle
--------
A window title or other criteria identifying the target window. See
|WinTitle|.
WinText
-------
If present, this parameter must be a substring from a
single text element of the target window (as revealed by the included
Window Spy utility). Hidden text elements are detected if
DetectHiddenText is ON.
Width , Height
--------------
The new width and height of the window (in pixels), which can be
expressions. If either is omitted, blank, or the word DEFAULT, the
size in that dimension will not be changed.
ExcludeTitle
------------
Windows whose titles include this value will not be considered.
ExcludeText
-----------
Windows whose text include this value will not be considered.
Remarks~
If Width and Height are small (or negative), most windows with a title
bar will generally go no smaller than 112 x 27 pixels (however, some
types of windows may have a different minimum size). If Width and
Height are large, most windows will go no larger than approximately 12
pixels beyond the dimensions of the desktop.
Negative values are allowed for the x and y coordinates to support
multi-monitor systems and to allow a window to be moved entirely off
screen.
Although WinMove cannot move minimized windows, it can move hidden
windows if DetectHiddenWindows is on.
The speed of WinMove is affected by |SetWinDelay|.
Window titles and text are case sensitive. Hidden windows are not
detected unless DetectHiddenWindows has been turned on.
Related~
|ControlMove|, |WinGetPos|, |WinHide|, |WinMinimize|, |WinMaximize|, |WinSet|
Example~
>
Run, calc.exe
WinWait, Calculator
WinMove, 0, 0
; Move the window found by WinWait to the upper-left corner of
; the screen.
SplashTextOn, 400, 300, Clipboard, The clipboard contains:`n%clipboard%
WinMove, Clipboard, , 0, 0 ; Move the splash window to the top left corner.
Msgbox, Press OK to dismiss the SplashText
SplashTextOff
; The following function centers the specified window on the screen:
CenterWindow(WinTitle)
{
WinGetPos,,, Width, Height, %WinTitle%
WinMove, %WinTitle%,, (A_ScreenWidth/2)-(Width/2), (A_ScreenHeight/2)-(Height/2)
}
<
==============================================================================
*WinShow*
+---------+~
| WinShow |~
+---------+~
Unhides the specified window.
|WinShow| [, WinTitle, WinText, ExcludeTitle, ExcludeText ]
Parameters~
WinTitle
--------
A window title or other criteria identifying the target window. See
WinTitle.
WinText
-------
If present, this parameter must be a substring from a single text
element of the target window (as revealed by the included Window Spy
utility). Hidden text elements are detected if DetectHiddenText is ON.
ExcludeTitle
------------
Windows whose titles include this value will not be considered.
ExcludeText
-----------
Windows whose text include this value will not be considered.
Remarks~
By default, WinShow is the only command that can always detect hidden
windows. Other commands can detect them only if DetectHiddenWindows
has been turned on.
This command operates only upon the topmost matching window except
when WinTitle is ahk_group GroupName, in which case all windows
in the group are affected.
Related~
|WinHide|, |SetTitleMatchMode|, DetectHiddenWindows, Last Found Window
Example~
>
Run, notepad.exe
WinWait, Untitled - Notepad
Sleep, 500
WinHide ; Because its parameter is omitted, it uses the window found above.
Sleep, 1000
WinShow
<
==============================================================================
*WinWait*
+---------+~
| WinWait |~
+---------+~
Waits until the specified window exists.
|WinWait| [, WinTitle, WinText, Seconds, ExcludeTitle, ExcludeText ]
Parameters~
WinTitle
--------
A window title or other criteria identifying the target window. See
WinTitle.
WinTitle may be blank only when WinText, ExcludeTitle, or ExcludeText
is present.
WinText
-------
If present, this parameter must be a substring from a single text
element of the target window (as revealed by the included Window Spy
utility). Hidden text elements are detected if DetectHiddenText is
ON.
Seconds
-------
How many seconds to wait before timing out and setting ErrorLevel to
1. Leave blank to wait indefinitely. Specifying 0 is the same as
specifying 0.5. This parameter can be an expression.
ExcludeTitle
------------
Windows whose titles include this value will not be considered.
ExcludeText
-----------
Windows whose text include this value will not be considered.
ErrorLevel~
ErrorLevel is set to 1 if the command timed out or 0 otherwise.
Remarks~
If a matching window comes into existence, the command will not wait
for Seconds to expire. Instead, it will immediately set ErrorLevel to
0, update the Last Found Window, and the script will continue
executing.
While the command is in a waiting state, new threads can be launched
via hotkey, custom menu item, or timer.
If another thread changes the contents of any variable(s) that were
used for this command's parameters, the command will not see the
change -- it will continue to use the title and text that were
originally present in the variables when the command first started
waiting.
Window titles and text are case sensitive. Hidden windows are not
detected unless DetectHiddenWindows has been turned on.
Related~
|WinWaitActive|, |WinWaitClose|, |IfWinExist|, |IfWinActive|, |Process|,
|SetTitleMatchMode|, |DetectHiddenWindows|
Example~
>
Run, notepad.exe
WinWait, Untitled - Notepad, , 3
if ErrorLevel
{
MsgBox, WinWait timed out.
return
}
else
WinMinimize ; Minimize the window found by WinWait.
<
==============================================================================
*WinRestore*
+------------+~
| WinRestore |~
+------------+~
Unminimizes or unmaximizes the specified window if it is minimized or
maximized.
|WinRestore| [, WinTitle, WinText, ExcludeTitle, ExcludeText ]
Parameters~
WinTitle
--------
A window title or other criteria identifying the target window. See
WinTitle.
WinText
-------
If present, this parameter must be a substring from a single text
element of the target window (as revealed by the included Window Spy
utility). Hidden text elements are detected if DetectHiddenText is ON.
ExcludeTitle
------------
Windows whose titles include this value will not be considered.
ExcludeText
-----------
Windows whose text include this value will not be considered.
Remarks~
If a particular type of window does not respond correctly to
WinRestore, try using the following instead:
>
PostMessage, 0x112, 0xF120,,, WinTitle, WinText ; 0x112 =
; WM_SYSCOMMAND, 0xF120 = SC_RESTORE
<
This command operates only upon the topmost matching window except
when WinTitle is ahk_group GroupName, in which case all windows in the
group are affected.
Window titles and text are case sensitive. Hidden windows are not
detected unless DetectHiddenWindows has been turned on.
Related~
|WinMinimize|, |WinMaximize|
Example~
>
WinRestore, Untitled - Notepad
<
==============================================================================
*WinSetTitle*
+-------------+~
| WinSetTitle |~
+-------------+~
Changes the title of the specified window.
|WinSetTitle|, NewTitle
|WinSetTitle|, WinTitle, WinText, NewTitle [, ExcludeTitle ,
ExcludeText ]
Parameters~
NewTitle
--------
The new title for the window. If this is the only parameter given,
the Last Found Window will be used.
WinTitle
--------
A window title or other criteria identifying the target window. See
WinTitle.
WinText
-------
If present, this parameter must be a substring from a single text
element of the target window (as revealed by the included Window Spy
utility). Hidden text elements are detected if DetectHiddenText is ON.
ExcludeTitle
------------
Windows whose titles include this value will not be considered.
ExcludeText
-----------
Windows whose text include this value will not be considered.
Remarks~
A change to a window's title might be merely temporary if the
application that owns the window frequently changes the title.
Window titles and text are case sensitive. Hidden windows are not
detected unless DetectHiddenWindows has been turned on.
Related~
|WinMove|, |WinGetActiveStats|, |WinGetActiveTitle|, |WinGetText|,
|ControlGetText|, |WinGetPos|, |WinSet|
Example~
>
WinSetTitle, Untitled - Notepad, , This is a new title
; Alternate:
Run, notepad.exe
WinWaitActive, Untitled - Notepad
WinSetTitle, This is a new title ; Uses the window found above by WinWaitActive
<
==============================================================================
*WinWaitClose*
+--------------+~
| WinWaitClose |~
+--------------+~
Waits until the specified window does not exist.
|WinWaitClose| [, WinTitle, WinText, Seconds, ExcludeTitle,
ExcludeText ]
Parameters~
WinTitle
--------
A window title or other criteria identifying the target window. See
WinTitle.
WinText
-------
If present, this parameter must be a substring from a single text
element of the target window (as revealed by the included Window Spy
utility). Hidden text elements are detected if DetectHiddenText is ON.
Seconds
-------
How many seconds to wait before timing out and setting ErrorLevel to
1. Leave blank to wait indefinitely. Specifying 0 is the same as
specifying 0.5. This parameter can be an expression.
ExcludeTitle
------------
Windows whose titles include this value will not be considered.
ExcludeText
-----------
Windows whose text include this value will not be considered.
ErrorLevel~
ErrorLevel is set to 1 if the command timed out or 0 otherwise.
Remarks~
Whenever no instances of the specified window exist, the command will
not wait for Seconds to expire. Instead, it will immediately set
ErrorLevel to 0 and the script will continue executing.
While the command is in a waiting state, new threads can be launched
via hotkey, custom menu item, or timer.
If another thread changes the contents of any variable(s) that were
used for this command's parameters, the command will not see the
change -- it will continue to use the title and text that were
originally present in the variables when the command first started
waiting.
Window titles and text are case sensitive. Hidden windows are not
detected unless DetectHiddenWindows has been turned on.
Related~
|WinClose|, |WinWait|, |WinWaitActive|, |IfWinExist|, |IfWinActive|,
Process, |SetTitleMatchMode|, |DetectHiddenWindows|
Example~
>
Run, notepad.exe
WinWait, Untitled - Notepad
WinWaitClose ; Wait for the exact window found by WinWait to be closed.
MsgBox, Notepad is now closed.
<
==============================================================================
*SetWorkingDir*
+---------------+~
| SetWorkingDir |~
+---------------+~
Changes the script's current working directory.
|SetWorkingDir| , DirNameParameters
DirName
-------
The name of the new working directory, which is assumed to be a
subfolder of the current %A_WorkingDir% if an absolute path isn't
specified.
ErrorLevel~
[v1.1.04+] This command is able to throw an exception on failure. For
more information, see Runtime Errors.
ErrorLevel is set to 1 if there was a problem or 0 otherwise.
Remarks
-------
The script's working directory is the default directory that is used
to access files and folders when an absolute path has not been
specified. In the following example, the file My Filename.txt is
assumed to be in %A_WorkingDir%:
>
FileAppend, A Line of Text, My Filename.txt
<
A script's initial working directory is determined by how it was
launched. For example, if it was run via shortcut -- such as on the
Start Menu -- its working directory is determined by the "Start in"
field within the shortcut's properties.
To make a script unconditionally use its own folder as its working
directory, make its first line the following:
>
SetWorkingDir %A_ScriptDir%
<
Once changed, the new working directory is instantly and globally in
effect throughout the script. All interrupted, paused, and newly
launched threads are affected, including Timers.
Related~
%A_WorkingDir% , %A_ScriptDir% , |FileSelectFolder|
Example~
>
SetWorkingDir %A_ScriptDir%
SetWorkingDir, D:\My Folder\Temp
<
==============================================================================
*Scripts*
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.
Script File Codepage~
Using non-ASCII characters safely in scripts.
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.
The Top of the Script (the Auto-execute Section)~
After the script has been loaded, it begins executing at the top line,
continuing until a |Return|, |Exit|, hotkey /hotstring label, or the
physical end of the script is encountered (whichever comes first).
This top portion of the script is referred to as the auto-execute
section.
A script that is not persistent and that lacks hotkeys, hotstrings,
OnMessage, and GUI will terminate after the auto-execute section has
completed. Otherwise, it will stay running in an idle state,
responding to events such as hotkeys, hotstrings, GUI events, custom
menu items, and timers.
Every thread launched by a hotkey, hotstring, menu item, GUI event,
or timer starts off fresh with the default values for the following
attributes as set in the auto-execute section. If unset, the standard
defaults will apply (as documented on each of the following pages):
|DetectHiddenWindows|, |DetectHiddenText|, |SetTitleMatchMode|,
|SetBatchLines|, |SendMode|, |SetKeyDelay|, |SetMouseDelay|,
|SetWinDelay|, |SetControlDelay|, |SetDefaultMouseSpeed|, CoordMode,
|SetStoreCapslockMode|, |AutoTrim|, |SetFormat|, |StringCaseSense|,
Thread, and Critical.
If the auto-execute section takes a long time to complete (or never
completes), the default values for the above settings will be put into
effect after 100 milliseconds. When the auto-execute section finally
completes (if ever), the defaults are updated again to be those that
were in effect at the end of the auto-execute section. Thus, it's
usually best to make any desired changes to the defaults at the top of
scripts that contain hotkeys, hotstrings, timers, or custom menu
items. Also note that each thread retains its own collection of the
above settings. Changes made to those settings will not affect other
threads.
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:
>
MsgBox This is ok.
MsgBox, This is ok too (it has an explicit comma)
<
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.
Splitting a Long Line into a Series of Shorter Ones~
Long lines can be divided up into a collection of smaller ones to
improve readability and maintainability. This does not reduce the
script's execution speed because such lines are merged in memory the
moment the script launches.
Method #1~
A line that starts with "and", "or", ||, &&, a comma, or a period is
automatically merged with the line directly above it (in v1.0.46+, the
same is true for all other expression operators except ++ and --). In
the following example, the second line is appended to the first
because it begins with a comma:
>
FileAppend, This is the text to append.`n ; A comment is allowed here.
, %A_ProgramFiles%\SomeApplication\LogFile.txt ; Comment.
<
Similarly, the following lines would get merged into a single line
because the last two start with "and" or "or":
>
if (Color = "Red" or Color = "Green" or Color = "Blue" ; Comment
or Color = "Black" or Color = "Gray" or Color = "White") ; Comment
and ProductIsAvailableInColor(Product, Color) ; Comment
<
The ternary operator is also a good candidate:
>
ProductIsAvailable := (Color = "Red")
? false ; We don't have any red products, so don't bother calling the function
: ProductIsAvailableInColor(Product, Color)
<
Although the indentation used in the examples above is optional, it
might improve clarity by indicating which lines belong to ones above
them. Also, it is not necessary to include extra spaces for lines
starting with the words "AND" and "OR"; the program does this
automatically. Finally, blank lines or comments may be added
between or at the end of any of the lines in the above examples.
Method #2~
This method should be used to merge a large number of lines or when
the lines are not suitable for Method #1. Although this method is
especially useful for auto-replace hotstrings, it can also be
used with any command or expression. For example:
>
; EXAMPLE #1:
Var =
(
Line 1 of the text.
Line 2 of the text. By default, a linefeed (`n) is present between lines.
)
; EXAMPLE #2:
FileAppend, ; The comma is required in this case.
(
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.
)
-----
[v1.1.01+]: If a closing parenthesis appears in the continuation
section's options (except as a parameter of the Join option), the line
is reinterpreted as an expression instead of the beginning of a
continuation section. This allows expressions like >
(x.y)[z]()
<
to work without the need to escape the opening parenthesis.
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.
Convert a Script to an EXE (ahk2exe)~
A script compiler (courtesy of fincs) is included with the program.
Once a script is compiled, it becomes a standalone executable; that
is, it can be used even on machines where AutoHotkey is not installed
(and such EXEs can be distributed or sold with no restrictions). The
compilation process creates an executable file which contains the
following: the AutoHotkey interpreter, the script, any files it
|includes|, and any files it has incorporated via the |FileInstall|
command.
Ahk2Exe can be used in the following ways:
1. GUI Interface
Run the "Convert .ahk to .exe" item in the Start Menu.
2. Right-click
Within an open Explorer window, you can right-click any .ahk file and
select "Compile Script" (only available if the script compiler option
was chosen when AutoHotkey was installed). This creates an EXE file of
the same base filename as the script, which appears after a short time
in the same directory. Note: The EXE file is produced using the same
custom icon, .bin file and use MPRESS setting that were last used by
Method #1 above.
3. Command Line
The compiler can be run from the command line with the following
parameters:
>
Ahk2Exe.exe /in MyScript.ahk [/out MyScript.exe] [/icon MyIcon.ico] [/bin AutoHotkeySC.bin] [/mpress 0or1]<
For example:
>
Ahk2Exe.exe /in "MyScript.ahk" /icon "MyIcon.ico"
<
Usage: ~
- Parameters containing spaces should be enclosed in double quotes
- If the "out" file is omitted, the EXE will have the same base
filename as the script itself
Notes:
- Compiling does not typically improve the performance of a script.
- As of v1.1.01, password protection and the /NoDecompile switch are
not supported.
- If |mpress.exe| is present in the "Compiler" subfolder where
AutoHotkey was installed, it is used to compress the script
executable, unless it is disabled via >
/mpress 0
< or the GUI setting. This also compresses the script source code
(minus any comments), which can otherwise be extracted from the exe
file using a PE resource editor.
- The commands |#NoTrayIcon| and >
Menu, Tray, ShowMainWindow
< affect the behavior of compiled scripts.
- Custom version info (as seen in Explorer's file-properties dialog)
can be added to your compiled scripts by using a utility such as
Resource Hacker (freeware) to edit the file "AutoHotkeySC.bin". This
file is contained in the "Compiler" subfolder where AutoHotkey was
installed. Compile_AHK II can be used to facilitate this process. As
of v1.1.01, the compiled script can be edited instead of
AutoHotkeySC.bin.
- The method above can also be used to change existing icons or add
new ones to all compiled scripts.
- The built-in variable A_IsCompiled contains 1 if the script is
running in compiled form. Otherwise, it is blank.
- When parameters are passed to Ahk2Exe, a message indicating the
success or failure of the compiling process is written to stdout.
Although the message will not appear at the command prompt, it can be
"caught" by means such as redirecting output to a file. [v1.0.43+]
The compiler's source code and newer versions can be found at GitHub.
Passing Command Line Parameters to a Script~
Scripts support command line parameters. The format is:
>
AutoHotkey.exe [Switches] [Script Filename] [Script Parameters]
<
And for compiled scripts, the format is:
>
CompiledScript.exe [Switches] [Script Parameters]
<
Switches ~
Zero or more of the following:
/f or /force -- Launch unconditionally, skipping any warning dialogs.
/r or /restart -- Indicate that the script is being restarted (this is
also used by the Reload command, internally).
/ErrorStdOut -- Send syntax errors that prevent a script from
launching to stdout rather than displaying a dialog. See #ErrorStdOut
for details.
/Debug -- [AHK_L 11+]: Connect to a debugging client. For more
details, see Interactive Debugging.
/CPn -- [AHK_L 51+]: Overrides the default codepage used to read
script files. For more details, see Script File Codepage.
Script Filename ~
This can be omitted if there are no Script Parameters. If omitted, it
will run (or prompt you to create) a file in one of the following
default locations:
[AHK_L 51+]: >
%AhkExeDir%\%AhkExeName%.ahk
<
or >
%A_MyDocuments%\%AhkExeName%.ahk
<
where %AhkExeDir% and %AhkExeName% are replaced with the directory and
filename of the executable used to run the script, excluding the
".exe" extension.
[Earlier versions]: >
AutoHotkey.ini
<
(in the current working directory) or >
%A_MyDocuments%\AutoHotkey.ahk
<
Script Parameters ~
The string(s) you want to pass into the script, with each separated
from the next by a space. Any parameter that contains spaces should be
enclosed in quotation marks. A literal quotation mark may be passed in
by preceding it with a backslash (\"). Consequently, any trailing
slash in a quoted parameter (such as "C:\My Documents\") is treated as
a literal quotation mark (that is, the script would receive the string
C:\My Documents"). To remove such quotes, use >
StringReplace, 1, 1, ",, All
<
The script sees incoming parameters as the variables %1%, %2%, and so
on. In addition, %0% contains the number of parameters passed (0 if
none). However, these variables cannot be referenced directly in an
expression because they would be seen as numbers rather than
variables. The following example exits the script when too few
parameters are passed to it:
>
if 0 < 3 ; The left side of a non-expression if-statement is always the name of a variable.
{
MsgBox This script requires at least 3 incoming parameters but it only received %0%.
ExitApp
}
<
If the number of parameters passed into a script varies (perhaps due
to the user dragging and dropping a set of files onto a script), the
following example can be used to extract them one by one:
>
Loop, %0% ; For each parameter:
{
param := %A_Index%
; Fetch the contents of the variable whose name is
; contained in A_Index.
MsgBox, 4,, Parameter number %A_Index% is %param%. Continue?
IfMsgBox, No
break
}
<
If the parameters are file names, the following example can be used to
convert them to their case-corrected long names (as stored in the file
system), including complete/absolute path:
>
Loop %0% ; For each parameter (or file dropped onto a script):
{
GivenPath := %A_Index%
; Fetch the contents of the variable whose name is
; contained in A_Index.
Loop %GivenPath%, 1
LongPath = %A_LoopFileLongPath%
MsgBox The case-corrected long path name of file`n%GivenPath%`nis:`n%LongPath%
}
<
Known limitation~
dragging files onto a .ahk script may fail to work properly if 8-dot-3
(short) names have been turned off in an NTFS file system. One
work-around is to compile the script then drag the files onto the
resulting EXE.
Script File Codepage [AHK_L 51+]~
The characters a script file may contain are restricted by the
codepage used to load the file.
- If the file begins with a UTF-8 or UTF-16 (LE) byte order mark, the
appropriate codepage is used and the /CPn switch is ignored.
- If the /CPn switch is passed on the command-line, codepage n is
used. For a list of valid numeric codepage identifiers, see MSDN.
- In all other cases, the system default ANSI codepage is used.
Note that this applies only to script files loaded by AutoHotkey, not
to file I/O within the script itself. FileEncoding controls the
default encoding of files read or written by the script, while IniRead
and IniWrite always deal in UTF-16 or ANSI.
As all text is converted (where necessary) to the native string
format, characters which are invalid or don't exist in the native
codepage are replaced with a placeholder: ANSI '?' or Unicode '?'. In
Unicode builds, this should only occur if there are encoding errors in
the script file or the codepages used to save and load the file don't
match.
|RegWrite| may be used to set the default for scripts launched from
Explorer (e.g. by double-clicking a file):
>
; Uncomment the appropriate line below or leave them all commented to
; reset to the default of the current build. Modify as necessary:
; codepage = 0 ; System default ANSI codepage
; codepage = 65001 ; UTF-8
; codepage = 1200 ; UTF-16
; codepage = 1252 ; ANSI Latin 1; Western European (Windows)
if (codepage != "")
codepage := " /CP" . codepage
cmd="%A_AhkPath%"%codepage% "`%1" `%*
key=AutoHotkeyScript\Shell\Open\Command
if A_IsAdmin ; Set for all users.
RegWrite, REG_SZ, HKCR, %key%,, %cmd%
else ; Set for current user only.
RegWrite, REG_SZ, HKCU, Software\Classes\%key%,, %cmd%
<
This assumes AutoHotkey has already been installed. Results may be
less than ideal if it has not.
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|.
Some common errors, such as typos and missing "global" declarations,
can be detected by enabling warnings.
Interactive Debugging [AHK_L 11+]~
Interactive debugging is possible with a supported DBGp client.
Typically the following actions are possible:
- Set and remove breakpoints on lines - pause execution when a
breakpoint is reached
- Step through code line by line - step into, over or out of functions
and subroutines
- Inspect all variables or a specific variable
- View the stack of running subroutines and functions.
Note that this functionality is disabled for compiled scripts.
To enable interactive debugging, first launch a supported debugger
client then launch the script with the /Debug command-line switch.
AutoHotkey.exe /Debug[=SERVER:PORT] ...
SERVER and PORT may be omitted. For example, the following are
equivalent:
>
AutoHotkey /Debug "myscript.ahk"
AutoHotkey /Debug=localhost:9000 "myscript.ahk"
<
[AHK_L 59+]: To attach the debugger to a script which is already
running, send it a message as shown below:
>
ScriptPath = ; SET THIS TO THE FULL PATH OF THE SCRIPT
DetectHiddenWindows On
ifWinExist %ScriptPath% ahk_class AutoHotkey
; Optional parameters:
; wParam = the IPv4 address of the debugger client, as a 32-bit integer.
; lParam = the port which the debugger client is listening on.
PostMessage DllCall("RegisterWindowMessage", "str", "AHK_ATTACH_DEBUGGER")
<
Once the debugger client is connected, it may detach without
terminating the script by sending the "detach" DBGp command.
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.
[AHK_L 51+]: Renaming AutoHotkey.exe also changes which script it runs
by default, which can be an alternative to compiling a script for use
on a computer without AutoHotkey installed. For instance, MyScript.exe
automatically runs MyScript.ahk if a filename is not supplied, but is
also capable of running other scripts.
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. For example:
>
AutoHotkey110800_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:
>
AutoHotkey110800_Install.exe /S /D=C:\Program Files\AutoHotkey
<
If AutoHotkey was previously installed, the installer automatically
detects which version of AutoHotkey.exe to set as the default.
Otherwise, the default is Unicode 32-bit or Unicode 64-bit depending
on whether the OS is 64-bit. To override which version of
AutoHotkey.exe is set as the default, pass one of the following
switches:
- /A32 or /ANSI: ANSI 32-bit.
- /U64 or /x64: Unicode 64-bit (only valid on 64-bit systems).
- /U32: Unicode 32-bit.
For example, the following installs silently and sets ANSI 32-bit as
the default:
>
AutoHotkey110800_Install.exe /S /A32
<
To silently uninstall AutoHotkey, pass the /Uninstall parameter to
Installer.ahk. For example:
>
"C:\Program Files\AutoHotkey\AutoHotkey.exe" "C:\Program Files\AutoHotkey\Installer.ahk" /Uninstall
<
For AutoHotkey versions older than 1.1.08.00, use uninst.exe /S. For
example:
>
"C:\Program Files\AutoHotkey\uninst.exe" /S
<
Note: Installer.ahk must be run as admin to work correctly.
Later versions of the installer include a link in the bottom-right
corner to extract setup files without installing. If this function is
present, the /E switch can be used to invoke it from the command line.
For example:
>
AutoHotkey110903_Install.exe /D=F:\AutoHotkey /E
<
Script Showcase~
See this page for some useful scripts.
==============================================================================
*Control*
+---------+~
| Control |~
+---------+~
Makes a variety of changes to a control.
|Control|, Cmd [, Value, Control, WinTitle, WinText, ExcludeTitle,
ExcludeText ]
Parameters~
Cmd , Value
-----------
See list below.
Control
-------
Can be either ClassNN (the classname and instance number of the
control) or the name/text of the control, both of which can be
determined via Window Spy. When using name/text, the matching behavior
is determined by SetTitleMatchMode. If this parameter is blank, the
target window's topmost control will be used.
To operate upon a control's HWND (window handle), leave the Control
parameter blank and specify >
ahk_id %ControlHwnd%
<
for the WinTitle parameter (this also works on hidden controls
even when DetectHiddenWindows is Off) . The HWND of a control is
typically retrieved via |ControlGet| Hwnd, |MouseGetPos|, or |DllCall|.
WinTitle
--------
A window title or other criteria identifying the target window. See
|WinTitle|.
WinText
-------
If present, this parameter must be a substring from a single text
element of the target window (as revealed by the included Window Spy
utility). Hidden text elements are detected if DetectHiddenText is ON.
ExcludeTitle
------------
Windows whose titles include this value will not be considered.
ExcludeText
-----------
Windows whose text include this value will not be considered.
Cmd, Value
----------
The Cmd and Value parameters are dependent upon each other and their
usage is described below.
Check
------
Turns on (checks) a radio button or checkbox.
Uncheck*
--------
Turns off a radio button or checkbox.
Enable
------
Enables a control if it was previously disabled.
Disable
-------
Disables or "grays out" a control.
Show
-----
Shows a control if it was previously hidden.
Hide
-----
Hides a control. If you additionally want to prevent a control's
shortcut key (underlined letter) from working, disable the control via
Control Disable.
Style ,N or ExStyle ,N
----------------------
Changes the style or extended style of a control, respectively. If the
first character of N is a plus or minus sign, the style(s) in N are
added or removed, respectively. If the first character is a caret (^),
the style(s) in N are each toggled to the opposite state. If the first
character is a digit, the control's style is overwritten completely;
that is, it becomes N. ErrorLevel is set to 1 if the target
window/control is not found or the style is not allowed to be applied
(which happens more often on Windows 9x).
Certain style changes require that the entire window be redrawn using
WinSet Redraw. Also, the styles table lists some of the style numbers.
For example:
>
Control, Style, ^0x800000, Edit1, WinTitle
; Set the WS_BORDER style to its opposite state
ShowDropDown
------------
Drops a ComboBox so that its choices become visible.
HideDropDown
------------
Reverses the above.
TabLeft [, Count ] and TabRight [, Count ]
--------------------------------------------
Moves left or right by one or more tabs in a SysTabControl32. Count is
assumed to be 1 if omitted or blank. To instead select a tab directly
by number, replace the number 5 below with one less than the tab
number you wish to select. In other words, 0 selects the first tab, 1
selects the second, and so on:
>
SendMessage, 0x1330, 5,, SysTabControl321, WinTitle
; 0x1330 is TCM_SETCURFOCUS.
Sleep 0
; This line and the next are necessary only for
; certain tab controls.
SendMessage, 0x130C, 5,, SysTabControl321, WinTitle
; 0x130C is TCM_SETCURSEL
<
Add , String
------------
Adds String as a new entry at the bottom of a ListBox, ComboBox (and
possibly other types).
Delete , N
----------
Deletes the Nth entry from a ListBox or ComboBox. N should be 1 for
the first entry, 2 for the second, etc.
Choose , N
----------
Sets the selection in a ListBox or ComboBox to be the Nth entry. N
should be 1 for the first entry, 2 for the second, etc. To select or
deselect all items in a multi-select listbox, follow these examples:
>
PostMessage, 0x185, 1, -1, ListBox1, WinTitle
; Select all listbox items. 0x185 is LB_SETSEL
<
ChooseString , String
---------------------
Sets the selection (choice) in a ListBox or ComboBox to be the first
entry whose leading part matches String. The search is not case
sensitive. For example, if a ListBox/ComboBox contains the item "UNIX
Text", specifying the word unix (lowercase) would be enough to select
it.
EditPaste , String
------------------
Pastes String at the caret/insert position in an Edit control (this
does not affect the contents of the clipboard).
ErrorLevel~
[v1.1.04+] This command is able to throw an exception on failure. For
more information, see Runtime Errors.
ErrorLevel is set to 1 if there was a problem or 0 otherwise.
Remarks~
To improve reliability, a delay is done automatically after every use
of this command (except for Style and ExStyle ). That delay can be
changed via |SetControlDelay|.
To discover the name of the control that the mouse is currently
hovering over, use |MouseGetPos|.
Window titles and text are case sensitive. Hidden windows are not
detected unless DetectHiddenWindows has been turned on.
Related~
|SetControlDelay|, |ControlGet|, |GuiControl|, |ControlGetText|,
|ControlSetText|, |ControlMove|, |ControlGetPos|, |ControlClick|,
|ControlFocus|, |ControlSend|, |WinSet|
Example~
>
Control, HideDropDown, , ComboBox1, Some Window Title
<
==============================================================================
*ControlGet*
+------------+~
| ControlGet |~
+------------+~
Retrieves various types of information about a control.
|ControlGet|, OutputVar, Cmd [, Value, Control, WinTitle, WinText,
ExcludeTitle, ExcludeText ]
Parameters~
OutputVar
---------
The name of the variable in which to store the result of Cmd.
Cmd, Value
See list below.
Control
-------
Can be either ClassNN (the classname and instance number of the
control) or the name/text of the control, both of which can be
determined via Window Spy. When using name/text, the matching behavior
is determined by |SetTitleMatchMode|. If this parameter is blank, the
target window's topmost control will be used.
To operate upon a control's HWND (window handle), leave the Control
parameter blank and specify >
ahk_id %ControlHwnd%
<
for the |WinTitle| parameter (this also works on hidden controls even
when |DetectHiddenWindows| is Off) . The HWND of a control is typically
retrieved via |ControlGet| Hwnd , |MouseGetPos|, or |DllCall|.
WinTitle
--------
A window title or other criteria identifying the target window. See
WinTitle.
WinText
-------
If present, this parameter must be a substring from a single text
element of the target window (as revealed by the included Window Spy
utility). Hidden text elements are detected if DetectHiddenText is
ON.
ExcludeTitle
------------
Windows whose titles include this value will not be considered.
ExcludeText
-----------
Windows whose text include this value will not be considered.
Cmd, Value~
The Cmd and Value parameters are dependent upon each other and their
usage is described below.
List
-----
Retrieves a list of items from a ListView, ListBox, ComboBox, or
DropDownList.
ListView
--------
The most common example of a ListView is Explorer's list of files and
folders (the desktop is also a ListView). The syntax for ListView
retrieval is:
>
ControlGet, OutputVar, List, Options, SysListView321, WinTitle, WinText
<
If the Options parameter is blank or omitted, all the text in the
control is retrieved. Each row except the last will end with a
linefeed character (`n). Within each row, each field (column) except
the last will end with a tab character (`t).
Specify for Options zero or more of the following words, each
separated from the next with a space or tab:
Selected
--------
Retrieves only the selected (highlighted) rows rather than all rows.
If none, OutputVar is made blank.
Focused
-------
Retrieves only the focused row. If none, OutputVar is made blank.
Col4
-----
Retrieves only the fourth column (field) rather than all columns
(replace 4 with a number of your choice).
Count
-----
Retrieves a single number that is the total number of rows in the
control.
Count Selected
--------------
Retrieves the number of selected (highlighted) rows.
Count Focused
-------------
Retrieves the row number (position) of the focused row (0 if none).
Count Col
---------
Retrieves the number of columns in the control (or -1 if the count
cannot be determined).
NOTE: Some applications store their ListView text privately, which
prevents their text from being retrieved. In these cases, ErrorLevel
will usually be set to 0 (indicating success) but all the retrieved
fields will be empty. Also note that ListView text retrieval is not
restricted by #MaxMem.
Upon success, ErrorLevel is set to 0. Upon failure, it is set to 1 and
OutputVar is made blank. Failure occurs when: 1) the target window or
control does not exist; 2) the target control is not of type
SysListView32; 3) the process owning the ListView could not be opened,
perhaps due to a lack of user permissions or because it is locked; 4)
the ColN option specifies a nonexistent column.
To extract the individual rows and fields out of a ListView, use a
parsing loop as in this example:
>
ControlGet, List, List, Selected, SysListView321, WinTitle
Loop, Parse, List, `n ; Rows are delimited by linefeeds (`n).
{
RowNumber := A_Index
Loop, Parse, A_LoopField, %A_Tab%
; Fields (columns) in each row are delimited by tabs (A_Tab).
MsgBox Row #%RowNumber% Col #%A_Index% is %A_LoopField%.
}
<
On a related note, the columns in a ListView can be resized via
SendMessage as shown in this example:
>
SendMessage, 4126, 0, 80, SysListView321, WinTitle
; 4126 is the message LVM_SETCOLUMNWIDTH.
; In the above, 0 indicates the first column (specify
; 1 for the second, 2 for the third, etc.) Also, 80
; is the new width. ; Replace 80 with -1 to autosize
; the column. Replace it with -2 to do the same but
; also take into account the header text width
<
ListBox, ComboBox, DropDownList
All the text is retrieved from the control (that is, the ListView
options above such as Count and Selected are not supported).
Each row except the last will be terminated by a linefeed character
(`n). To access the items individually, use a parsing loop as in this
example:
>
ControlGet, List, List,, ComboBox1, WinTitle
Loop, Parse, List, `n
MsgBox Item number %A_Index% is %A_LoopField%
<
Checked
-------
Sets OutputVar to be 1 if the checkbox or radio button is checked or 0
if not
Enabled
-------
Sets OutputVar to be 1 if Control is enabled, or 0 if disabled.
Visible
-------
Sets OutputVar to be 1 if Control is visible, or 0 if hidden.
Tab
-----
Sets OutputVar to the tab number of a SysTabControl32 control. The
first tab is 1, the second is 2, etc. To instead discover how many
tabs (pages) exist in a tab control, follow this example:
>
SendMessage, 0x1304,,, SysTabControl321, WinTitle
; 0x1304 is TCM_GETITEMCOUNT.
TabCount = %ErrorLevel%
<
FindString, String
------------------
Sets OutputVar to the entry number of a ListBox or ComboBox that is an
exact match for String. The first entry in the control is 1, the
second 2, and so on. If no match is found, OutputVar is made blank and
ErrorLevel is set to 1.
Choice
------
Sets OutputVar to be the name of the currently selected entry in a
ListBox or ComboBox. To instead retrieve the position of the selected
item, follow this example (use only one of the first two lines):
>
SendMessage, 0x188, 0, 0, ListBox1, WinTitle
; 0x188 is LB_GETCURSEL (for a ListBox).
SendMessage, 0x147, 0, 0, ComboBox1, WinTitle
; 0x147 is CB_GETCURSEL (for a DropDownList or ComboBox).
ChoicePos = %ErrorLevel%
; It will be -1 if there is no item selected.
ChoicePos += 1
; Convert from 0-based to 1-based, i.e. so that the
; first item is known as 1, not 0.LineCount: Sets
; OutputVar to be the number of lines in an Edit
; control. All Edit controls have at least 1 line,
; even if the control is empty.
<
CurrentLine
-----------
Sets OutputVar to be the line number in an Edit control where the
caret (insert point) resides. The first line is 1. If there is text
selected in the control, OutputVar is set to the line number where the
selection begins.
CurrentCol
----------
Sets OutputVar to be the column number in an Edit control where the
caret (text insertion point) resides. The first column is 1. If there
is text selected in the control, OutputVar is set to the column number
where the selection begins.
Line , N
--------
Sets OutputVar to be the text of line N in an Edit control. Line 1 is
the first line. Depending on the nature of the control, OutputVar
might end in a carriage return (`r) or a carriage return + linefeed
(`r`n). If the specified line number is blank or does not exist,
ErrorLevel is set to 1 and OutputVar is made blank.
Selected
--------
Sets OutputVar to be the selected text in an Edit control. If no text
is selected, OutputVar will be made blank and ErrorLevel will be set
to 0 (i.e. no error). Certain types of controls, such as RichEdit20A,
might not produce the correct text in some cases (e.g. Metapad).
Style
-----
Retrieves an 8-digit hexadecimal number representing the style of the
control. See the styles table for a listing of some styles.
ExStyle
-------
Retrieves an 8-digit hexadecimal number representing the extended
style of the control.
Hwnd [v1.0.43.06+]
-------------------
Retrieves the window handle (HWND) of the specified control. For
example: >
ControlGet, OutputVar, Hwnd,, Edit1, WinTitle
<
A control's HWND is often used with |PostMessage|, |SendMessage|, and
|DllCall|. On a related note, a control's HWND can also be retrieved
via |MouseGetPos|. Finally, a control's HWND can be used directly as an
ahk_id WinTitle (this also works on hidden controls even when
DetectHiddenWindows is Off).
ErrorLevel~
[v1.1.04+] This command is able to throw an exception on failure. For
more information, see Runtime Errors.
Upon success, ErrorLevel is set to 0. If a problem occurred -- such as
a nonexistent window or control -- ErrorLevel is set to 1 and
OutputVar is made blank.
Remarks~
Unlike commands that change a control, ControlGet does not have an
automatic delay; that is, |SetControlDelay| does not affect it.
To discover the name of the control that the mouse is currently
hovering over, use |MouseGetPos|. To get a list of controls in a window,
use |WinGet| ControlList.
Window titles and text are case sensitive. Hidden windows are not
detected unless |DetectHiddenWindows| has been turned on.
Related~
|Control|, |GuiControlGet|, |ControlMove|, |ControlGetText|,
|ControlSetText|, |ControlGetPos|, |ControlClick|, |ControlFocus|,
|ControlSend|, |WinGet|
Example~
>
ControlGet, OutputVar, Line, 1, Edit1, Some Window Title
ControlGet, WhichTab, Tab, , SysTabControl321, Some Window Title
if ErrorLevel
MsgBox There was a problem.
else
MsgBox Tab #%WhichTab% is active.
<
==============================================================================
*WinGetText*
+------------+~
| WinGetText |~
+------------+~
Retrieves the text from the specified window.
|WinGetText|, OutputVar [, WinTitle, WinText, ExcludeTitle,
ExcludeText ]
Parameters~
OutputVar
---------
The name of the variable in which to store the retrieved text.
WinTitle
--------
A window title or other criteria identifying the target window. See
WinTitle.
WinText
-------
If present, this parameter must be a substring from a single text
element of the target window (as revealed by the included Window Spy
utility). Hidden text elements are detected if DetectHiddenText is ON.
ExcludeTitle
------------
Windows whose titles include this value will not be considered.
ExcludeText
-----------
Windows whose text include this value will not be considered.
ErrorLevel~
[v1.1.04+] This command is able to throw an exception on failure. For
more information, see Runtime Errors.
ErrorLevel is set to 1 if there was a problem or 0 otherwise.
Remarks~
The text retrieved is generally the same as what Window Spy shows for
that window. However, if DetectHiddenText has been turned off,
hidden text is omitted from OutputVar.
Each text element ends with a carriage return and linefeed (CR+LF),
which can be represented in the script as `r`n. To extract individual
lines or substrings, use commands such as |StringGetPos| and |StringMid|.
A parsing loop can also be used to examine each line or word one by
one.
If the retrieved text appears to be truncated (incomplete), try using
|VarSetCapacity|( OutputVar, 55 ) prior to WinGetText [replace 55
with a size that is considerably longer than the truncated text]. This
is necessary because some applications do not respond properly to the
WM_GETTEXTLENGTH message, which causes AutoHotkey to make the output
variable too small to fit all the text.
The amount of text retrieved is limited to a variable's maximum
capacity (which can be changed via the #MaxMem directive). As a
result, this command might use a large amount of RAM if the target
window (e.g. an editor with a large document open) contains a large
quantity of text. To avoid this, it might be possible to retrieve only
portions of the window's text by using |ControlGetText| instead. In any
case, a variable's memory can be freed later by assigning it to
nothing, i.e. >
OutputVar =
<
Windows 95/98/ME may be limited to 64 KB for some text elements of
certain windows.
To retrieve a list of all controls in a window, follow this example:
WinGet, OutputVar, ControlList, WinTitle
Window titles and text are case sensitive. Hidden windows are not
detected unless DetectHiddenWindows has been turned on.
Related~
|ControlGetText|, |WinGetActiveStats|, |WinGetActiveTitle|,
|WinGetTitle|, |WinGetPos|, #MaxMem
Example~
>
Run, Calc.exe
WinWait, Calculator
WinGetText, text ; The window found above will be used.
MsgBox, The text is:`n%text%
<
==============================================================================
*WinGet*
+--------+~
| 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.
|WinGet|, OutputVar [, Cmd, WinTitle, WinText, ExcludeTitle,
ExcludeText ]
Parameters~
OutputVar
---------
The name of the variable in which to store the result of Cmd.
Cmd
-----
See list below.
WinTitle
--------
A window title or other criteria identifying the target window. See
|WinTitle|.
WinText
-------
If present, this parameter must be a substring from a single text
element of the target window (as revealed by the included Window Spy
utility). Hidden text elements are detected if DetectHiddenText is
ON.
ExcludeTitle
------------
Windows whose titles include this value will not be considered.
ExcludeText
-----------
Windows whose text include this value will not be considered.
Cmd ~
is the operation to perform, which if blank defaults to ID. It can be
one of the following words:
ID
-----
Retrieves the unique ID number (HWND/handle) of a window. If there is
no matching window, OutputVar is made blank. The functions
|WinExist|() and |WinActive|() can also be used to retrieve the ID of
a window; for example,
>
WinExist("A")
<
is a fast way to get the ID of the active window. To discover the HWND
of a control (for use with Post/SendMessage or DllCall), use
|ControlGet| Hwnd or |MouseGetPos|.
IDLast
------
Same as above except it retrieves the ID of the last/bottommost window
if there is more than one match. If there is only one match, it
performs identically to ID. This concept is similar to that used by
|WinActivateBottom|.
PID
-----
Retrieves the Process ID (PID) of a window.
ProcessName
-----------
Retrieves the name of the process (e.g. notepad.exe) that owns a
window. If there are no matching windows, OutputVar is made blank.
ProcessPath [v1.1.01+]
-----------------------
Similar to ProcessName, but retrieves the full path and name of the
process instead of just the name.
Count
-----
Retrieves the number of existing windows that match the specified
|WinTitle|, |WinText|, ExcludeTitle, and ExcludeText (0 if none). To count
all windows on the system, omit all four title/text parameters. Hidden
windows are included only if DetectHiddenWindows has been turned on.
List
-----
Retrieves the unique ID numbers of all existing windows that match the
specified |WinTitle|, |WinText|, ExcludeTitle, and ExcludeText (to
retrieve all windows on the entire system, omit all four title/text
parameters). Each ID number is stored in an array element whose name
begins with OutputVar 's own name, while OutputVar itself is set to the
number of retrieved items (0 if none). For example, if OutputVar is
MyArray and two matching windows are discovered, MyArray1 will be set
to the ID of the first window, MyArray2 will be set to the ID of the
second window, and MyArray itself will be set to the number 2. Windows
are retrieved in order from topmost to bottommost (according to how
they are stacked on the desktop). Hidden windows are included only if
DetectHiddenWindows has been turned on. Within a function, to create
an array that is global instead of local, declare MyArray as a global
variable prior to using this command (the converse is true for
assume-global functions).
MinMax
------
Retrieves the minimized/maximized state for a window. OuputVar is made
blank if no matching window exists; otherwise, it is set to one of the
following numbers:
-1
-----
The window is minimized (|WinRestore| can unminimize it).
1
-----
The window is maximized (|WinRestore| can unmaximize it).
0
-----
The window is neither minimized nor maximized.
ControlList
-----------
Retrieves the control names for all controls in a window. If no
matching window exists or there are no controls in the window,
OutputVar is made blank. Otherwise, each control name consists of its
class name followed immediately by its sequence number (ClassNN), as
shown by Window Spy.
Each item except the last is terminated by a linefeed (`n). To examine
the individual control names one by one, use a parsing loop as
shown in the examples section below.
Controls are sorted according to their Z-order, which is usually the
same order as TAB key navigation if the window supports tabbing.
The control currently under the mouse cursor can be retrieved via
|MouseGetPos|.
ControlListHwnd [v1.0.43.06+]
-----------------------------
Same as above except it retrieves the window handle (HWND) of each
control rather than its ClassNN.
Transparent
-----------
Retrieves the degree of transparency of a window (see WinSet for how
to set transparency). OutputVar is made blank if: 1) the OS is older
than Windows XP; 2) there are no matching windows; 3) the window has
no transparency level; or 4) other conditions (caused by OS behavior)
such as the window having been minimized, restored, and/or resized
since it was made transparent. Otherwise, a number between 0 and 255
is stored, where 0 indicates an invisible window and 255 indicates an
opaque window. For example:
>
MouseGetPos,,, MouseWin
WinGet, Transparent, Transparent, ahk_id %MouseWin%
; Transparency of window under the mouse cursor
<
TransColor
----------
Retrieves the color that is marked transparent in a window (see WinSet
for how to set the TransColor). OutputVar is made blank if: 1) the OS
is older than Windows XP; 2) there are no matching windows; 3) the
window has no transparent color; or 4) other conditions (caused by OS
behavior) such as the window having been minimized, restored, and/or
resized since it was made transparent. Otherwise, a six-digit
hexadecimal RGB color is stored, e.g. 0x00CC99. For example:
>
MouseGetPos,,, MouseWin
WinGet, TransColor, TransColor, ahk_id %MouseWin%
; TransColor of the window under the mouse cursor
<
Style or ExStyle
----------------
Retrieves an 8-digit hexadecimal number representing style or extended
style (respectively) of a window. If there are no matching windows,
OutputVar is made blank. The following example determines whether a
window has the WS_DISABLED style:
>
WinGet, Style, Style, My Window Title
if (Style & 0x8000000) ; 0x8000000 is WS_DISABLED.
;... the window is disabled, so perform appropriate action
<
The next example determines whether a window has the WS_EX_TOPMOST
style (always-on-top):
>
WinGet, ExStyle, ExStyle, My Window Title
if (ExStyle & 0x8) ; 0x8 is WS_EX_TOPMOST.
;... the window is always-on-top, so perform appropriate action
<
See the styles table for a partial listing of styles.
Remarks~
A window's ID number is valid only during its lifetime. In other
words, if an application restarts, all of its windows will get new ID
numbers.
ID numbers retrieved by this command are numeric (the prefix "ahk_id"
is not included) and are stored in hexadecimal format regardless of
the setting of |SetFormat|.
The ID of the window under the mouse cursor can be retrieved with
|MouseGetPos|.
Although ID numbers are currently 32-bit unsigned integers, they may
become 64-bit in future versions. Therefore, it is unsafe to perform
numerical operations such as addition on these values because such
operations require that their input strings be parsable as signed
rather than unsigned integers.
Window titles and text are case sensitive. Hidden windows are not
detected unless DetectHiddenWindows has been turned on.
Related~
|WinGetClass|, |Process|, |WinGetTitle|, |MouseGetPos|, |ControlGet|,
|ControlFocus|, |GroupAdd|
Examples~
>
; Example #1: Maximize the active window and report its unique ID:
WinGet, active_id, ID, A
WinMaximize, ahk_id %active_id%
MsgBox, The active window's ID is "%active_id%".
; Example #2: This will visit all windows on the entire system and display info about each of them:
WinGet, id, list,,, Program Manager
Loop, %id%
{
this_id := id%A_Index%
WinActivate, ahk_id %this_id%
WinGetClass, this_class, ahk_id %this_id%
WinGetTitle, this_title, ahk_id %this_id%
MsgBox, 4, , Visiting All Windows`n%a_index% of %id%`nahk_id %this_id%`nahk_class %this_class%`n%this_title%`n`nContinue?
IfMsgBox, NO, break
}
; Example #3: Extract the individual control names from a ControlList:
WinGet, ActiveControlList, ControlList, A
Loop, Parse, ActiveControlList, `n
{
MsgBox, 4,, Control #%a_index% is "%A_LoopField%". Continue?
IfMsgBox, No
break
}
; Example #4: Display in real time the active window's control list:
#Persistent
SetTimer, WatchActiveWindow, 200
return
WatchActiveWindow:
WinGet, ControlList, ControlList, A
ToolTip, %ControlList%
return
<
==============================================================================
*WinGetTitle*
+-------------+~
| WinGetTitle |~
+-------------+~
Retrieves the title of the specified window.
|WinGetTitle|, OutputVar [, WinTitle, WinText, ExcludeTitle,
ExcludeText ]
Parameters~
OutputVar
---------
The name of the variable in which to store the retrieved title.
WinTitle
--------
A window title or other criteria identifying the target window. See
WinTitle.
WinText
-------
If present, this parameter must be a substring from a single text
element of the target window (as revealed by the included Window Spy
utility). Hidden text elements are detected if DetectHiddenText is ON.
ExcludeTitle
------------
Windows whose titles include this value will not be considered.
ExcludeText
-----------
Windows whose text include this value will not be considered.
Remarks~
To discover the name of the window that the mouse is currently
hovering over, use MouseGetPos.
Window titles and text are case sensitive. Hidden windows are not
detected unless DetectHiddenWindows has been turned on.
Related~
|WinGetActiveStats|, |WinGetActiveTitle|, |WinGetClass|, |WinGet|,
|WinGetText|, |ControlGetText|, |WinGetPos|
Example~
>
WinGetTitle, Title, A
MsgBox, The active window is "%Title%".
==============================================================================
*StringMid*
+-----------+~
| StringMid |~
+-----------+~
Retrieves one or more characters from the specified position in a
string.
|StringMid|, OutputVar, InputVar, StartChar [, Count , L]
NewStr := |SubStr|(String, StartPos [, Length]) ; See the SubStr()
function for details.
Parameters~
OutputVar
---------
The name of the variable in which to store the substring extracted
from InputVar.
InputVar
--------
The name of the variable from whose contents the substring will be
extracted. Do not enclose the name in percent signs unless you want
the contents of the variable to be used as the name.
StartChar
---------
The position of the first character to be extracted, which can be an
expression. Unlike StringGetPos, 1 is the first character. If
StartChar is less than 1, it will be assumed to be 1. If StartChar is
beyond the end of the string, OutputVar is made empty (blank).
Count
-----
In v1.0.43.10+, this parameter may be omitted or left blank, which is
the same as specifying an integer large enough to retrieve all
characters from the string.
Otherwise, specify the number of characters to extract, which can be
an expression. If Count is less than or equal to zero, OutputVar will
be made empty (blank). If Count exceeds the length of InputVar
measured from StartChar, OutputVar will be set equal to the entirety
of InputVar starting at StartChar.
L
-----
The letter L can be used to extract characters that lie to the left of
StartChar rather than to the right. In the following example,
OutputVar will be set to Red:
>
InputVar = The Red Fox
StringMid, OutputVar, InputVar, 7, 3, L
<
If the L option is present and StartChar is less than 1, OutputVar
will be made blank. If StartChar is beyond the length of InputVar,
only those characters within reach of Count will be extracted. For
example, the below will set OutputVar to Fox:
>
InputVar = The Red Fox
StringMid, OutputVar, InputVar, 14, 6, L
<
Remarks~
For this and all other commands, OutputVar is allowed to be the same
variable as InputVar.
Related~
|SubStr|(), |StringLeft|, |StringRight|, |StringTrimLeft|,
|StringTrimRight|, |IfInString|, |StringGetPos|, |StringLen|,
|StringLower|, |StringUpper|, |StringReplace|
Example~
>
Source = Hello this is a test.
StringMid, the_word_this, Source, 7, 4
<
==============================================================================
*StringLeft* *StringRight*
+--------------------------+~
| StringLeft / StringRight |~
+--------------------------+~
Retrieves a number of characters from the left or right-hand side of a
string.
|StringLeft|, OutputVar, InputVar, Count
StringRight, OutputVar, InputVar, Count
NewStr := |SubStr|(String, StartPos [, Length])
; See the SubStr() function for details.
Parameters~
OutputVar
---------
The name of the variable in which to store the substring extracted
from InputVar.
InputVar
--------
The name of the variable whose contents will be extracted from. Do not
enclose the name in percent signs unless you want the contents of the
variable to be used as the name.
Count
-----
The number of characters to extract, which can be an expression. If
Count is less than or equal to zero, OutputVar will be made empty
(blank). If Count exceeds the length of InputVar, OutputVar will be
set equal to the entirety of InputVar.
Remarks~
For this and all other commands, OutputVar is allowed to be the same
variable as an InputVar.
Related~
|SubStr|(), |StringMid|, |StringTrimLeft|, |StringTrimRight|,
|IfInString|, |StringGetPos|, |StringLen|, |StringLower|,
|StringUpper|, |StringReplace|
Example~
>
String = This is a test.
StringLeft, OutputVar, String, 4
; Stores the string "This" in OutputVar.
StringRight, OutputVar, String, 5
; Stores the string "test." in OutputVar
<
==============================================================================
*StringTrimLeft* *StringTrimRight*
+----------------------------------+~
| StringTrimLeft / StringTrimRight |~
+----------------------------------+~
Removes a number of characters from the left or right-hand side of a
string.
|StringTrimLeft|, OutputVar, InputVar, Count
|StringTrimRight|, OutputVar, InputVar, Count
NewStr := |SubStr|(String, StartPos [, Length])
; See the SubStr() function for details.
Parameters~
OutputVar
---------
The name of the variable in which to store the shortened version of
InputVar.
InputVar
--------
The name of the variable whose contents will be read from. Do not
enclose the name in percent signs unless you want the contents of the
variable to be used as the name.
Count
-----
The number of characters to remove, which can be an expression. If
Count is less than or equal to zero, OutputVar will be set equal to
the entirety of InputVar. If Count exceeds the length of InputVar,
OutputVar will be made empty (blank).
Remarks~
For this and all other commands, OutputVar is allowed to be the same
variable as an InputVar.
Related~
|SubStr|(), |StringMid|, |StringLeft|, |StringRight|, |IfInString|,
|StringGetPos|, |StringLen|, |StringLower|, |StringUpper|,
|StringReplace|
Example~
>
String = This is a test.
StringTrimLeft, OutputVar, String, 5 ; Stores the string "is a test." in OutputVar.
StringTrimRight, OutputVar, String, 6 ; Stores the string "This is a" in OutputVar.
<
==============================================================================
*StringGetPos*
+--------------+~
| StringGetPos |~
+--------------+~
Retrieves the position of the specified substring within a string.
|StringGetPos|, OutputVar, InputVar, SearchText [, L#|R#, Offset]
Position := |InStr|(Haystack, Needle [, CaseSensitive?, StartingPos])
; See the InStr() function for details.
Parameters~
OutputVar
---------
The name of the variable in which to store the retrieved position
relative to the first character of InputVar. Position 0 is the first
character for StringGetPos and position 1 is the first character for
InStr().
InputVar
--------
The name of the input variable, whose contents will be searched. Do
not enclose the name in percent signs unless you want the contents of
the variable to be used as the name.
SearchText
----------
The string to search for. Matching is not case sensitive unless
StringCaseSense has been turned on.
L#|R#
-----
This affects which occurrence will be found if SearchText occurs more
than once within InputVar. If this parameter is omitted, InputVar will
be searched starting from the left for the first match. If this
parameter is 1 or the letter R, the search will start looking at the
right side of InputVar and will continue leftward until the first
match is found.
To find a match other than the first, specify the letter L or R
followed by the number of the occurrence. For example, to find the
fourth occurrence from the right, specify r4. Note: If the number is
less than or equal to zero, no match will be found.
Offset
------
The number of characters on the leftmost or rightmost side (depending
on the parameter above) to skip over. If omitted, the default is 0.
For example, the following would start searching at the tenth
character from the left: StringGetPos, OutputVar, InputVar, abc, , 9.
This parameter can be an expression.
ErrorLevel~
ErrorLevel is set to 1 if the specified occurrence of SearchText could
not be found within InputVar, or 0 otherwise.
Remarks~
Unlike StringMid and InStr(), 0 is defined as the position of the
first character for StringGetPos.
The retrieved position is always relative to the first character of
InputVar, regardless of whether L#|R# and/or Offset are specified. For
example, if the string "abc" is found in 123abc789, its reported
position will always be 3 regardless of the method by which it was
found.
If the specified occurrence of SearchText does not exist within
InputVar, OutputVar will be set to -1 and ErrorLevel will be set to 1.
Use SplitPath to more easily parse a file path into its directory,
filename, and extension.
The built-in variables %A_Space% and %A_Tab% contain a single space
and a single tab character, respectively. They are useful when
searching for spaces and tabs alone or at the beginning or end of
SearchText.
Related~
|InStr|(), |RegExMatch|(), |IfInString|, if var in/contains MatchList,
|StringCaseSense|, |StringReplace|, |SplitPath|, |StringLeft|,
|StringRight|, |StringMid|, |StringTrimLeft|, |StringTrimRight|,
|StringLen|, |StringLower|, |StringUpper|, if var is type
Examples~
>
Haystack = abcdefghijklmnopqrs
Needle = def
StringGetPos, pos, Haystack, %Needle%
if pos >= 0
MsgBox, The string was found at position %pos%.
; Example #2:
; Divides up the full path name of a file into components.
; Note that it would be much easier to use StringSplit or a
; parsing loop to do this, so the below is just for illustration.
FileSelectFile, file, , , Pick a filename in a deeply nested folder:
if file <>
{
StringLen, pos_prev, file
pos_prev += 1 ; Adjust to be the position after the last char.
Loop
{
; Search from the right for the Nth occurrence:
StringGetPos, pos, file, \, R%A_Index%
if ErrorLevel
break
length := pos_prev - pos - 1
pos_prev := pos
pos += 2 ; Adjust for use with StringMid.
StringMid, path_component, file, %pos%, %length%
MsgBox Path component #%a_index% (from the right) is:`n%path_component%
}
}
<
==============================================================================
*StrLen* *StringLen*
+--------------------+~
| StrLen / StringLen |~
+--------------------+~
Retrieves the count of how many characters are in a string.
|OutputVar| := StrLen(InputVar)
|StringLen,| OutputVar, InputVar
Parameters~
OutputVar
---------
The name of the variable in which to store the length.
InputVar
--------
The name of the variable whose contents will be measured. Do not
enclose the name in percent signs unless you want the contents of the
variable to be used as the name.
Remarks~
If InputVar is a variable to which ClipboardAll was previously
assigned, StringLen will report its total size.
Related~
|IfInString|, |StringGetPos|, |StringMid|, |StringTrimLeft|,
|StringTrimRight|, |StringLeft|, |StringRight|, |StringLower|,
|StringUpper|, |StringReplace|
Example~
>
InputVar := "The Quick Brown Fox Jumps Over the Lazy Dog"
MsgBox % "The length of InputVar is " . StrLen(InputVar) ; Result: 43
StringLen, length, InputVar
MsgBox, The length of InputVar is %length%.
<
==============================================================================
*StringReplace*
+---------------+~
| StringReplace |~
+---------------+~
Replaces the specified substring with a new string.
|StringReplace|, OutputVar, InputVar, SearchText [, ReplaceText,
ReplaceAll?]
Parameters~
OutputVar
---------
The name of the variable in which to store the result of the
replacement process.
InputVar
--------
The name of the variable whose contents will be read from. Do not
enclose the name in percent signs unless you want the contents of the
variable to be used as the name.
SearchText
----------
The string to search for. Matching is not case sensitive unless
StringCaseSense has been turned on.
ReplaceText
-----------
SearchText will be replaced with this text. If omitted or blank,
SearchText will be replaced with blank (empty). In other words, it
will be omitted from OutputVar.
ReplaceAll?
-----------
If omitted, only the first occurrence of SearchText will be replaced.
But if this parameter is 1, A, or All, all occurrences will be
replaced.
Specify the word UseErrorLevel to store in ErrorLevel the number of
occurrences replaced (0 if none). UseErrorLevel implies "All".
ErrorLevel~
When the last parameter is UseErrorLevel, ErrorLevel is given the
number occurrences replaced (0 if none). Otherwise, ErrorLevel is set
to 1 if SearchText is not found within InputVar, or 0 if it is found.
Remarks~
For this and all other commands, OutputVar is allowed to be the same
variable as an InputVar.
The built-in variables %A_Space% and %A_Tab% contain a single space
and a single tab character, respectively. They are useful when
searching for spaces and tabs alone or at the beginning or end of
SearchText.
In v1.0.45, the AllSlow option became obsolete due to improvements to
performance and memory utilization. Although it may still be
specified, it has no effect.
Related~
|RegExReplace|(), |IfInString|, |StringCaseSense|, |StringLeft|,
|StringRight|, |StringMid|, |StringTrimLeft|, |StringTrimRight|,
|StringLen|, |StringLower|, |StringUpper|, |StringGetPos|, if var is
type
Examples~
>
; Remove all CR+LF's from the clipboard contents:
StringReplace, clipboard, clipboard, `r`n, , All
; Replace all spaces with pluses:
StringReplace, NewStr, OldStr, %A_SPACE%, +, All
; Remove all blank lines from the text in a variable:
Loop
{
StringReplace, MyString, MyString, `r`n`r`n, `r`n, UseErrorLevel
if ErrorLevel = 0 ; No more replacements needed.
break
}
<
==============================================================================
*StrPut* *StrGet* [AHK_L 46+]
+---------------------------------+~
| StrPut() / StrGet() [AHK_L 46+] |~
+---------------------------------+~
Copies a string to or from a memory address, optionally converting to
or from a given code page.
|StrPut|(String [, Encoding = None ] )
|StrPut|(String, Address [, Length] [, Encoding = None ] )
|StrGet|(Address [, Length] [, Encoding = None ] )
Parameters~
String
------
Any string. Numbers are also acceptable.
Address
-------
The address at which the string will be written to/read from.
Length
------
The maximum number of characters to read/write, including the
null-terminator if required. See Return Value.
Encoding
--------
The source encoding for StrGet or target encoding for StrPut; for
example, "UTF-8", "UTF-16" or "CP936". If Address and Length are not
specified, numeric identifiers must be prefixed with "CP". Specify an
empty string or "CP0" to use the system default ANSI code page.
Return Value~
For either function, invalid parameters cause an empty string to be
returned.
StrPut returns the number of characters written, the required buffer
size in characters if no Address was given, or 0 if an error occurred.
If Length is less than the length of the source string, the function
fails and returns 0. If Length is exactly the length of the source
string, the string is not null-terminated; otherwise the returned
count includes the null-terminator.
StrGet returns the requested string after performing any necessary
conversion.
Remarks~
Note that the String parameter of StrPut and return value of StrGet
are always in the native encoding of the current executable, whereas
Encoding specifies the encoding of the string written to or read from
the given Address. If no Encoding is specified, the string is simply
measured or copied without any conversion taking place.
If conversion between code pages is necessary, the required buffer
size may differ from the size of the source String.
Scripts which are required to be compatible with AutoHotkey Basic can
still use StrPut and StrGet provided that the appropriate script files
are installed in a function library. These scripts can be found at the
AutoHotkey Community Forum.
Related~
Script Compatibility, |FileEncoding|, |VarSetCapacity|()
Examples~
Either Length or Encoding may be specified directly after Address, but
in those cases Encoding must be non-numeric:
>
strA := StrGet(addressA, "cp0") ; OK
strA := StrGet(addressA, length, 0) ; OK
strA := StrGet(addressA, 0) ; Error
<
StrPut may be called once to calculate the required buffer size for a
string in a particular encoding, then again to encode and write the
string into the buffer. If you frequently use variables with StrPut,
consider adding this function to your library:
>
StrPutVar(string, ByRef var, encoding)
{
; Ensure capacity.
VarSetCapacity( var, StrPut(string, encoding)
; StrPut returns char count, but VarSetCapacity needs bytes.
* ((encoding="utf-16"||encoding="cp1200") ? 2 : 1) )
; Copy or convert the string.
return StrPut(string, &var, encoding)
}
<
==============================================================================
*DllCall*
+---------+~
| DllCall |~
+---------+~
Calls a function inside a DLL, such as a standard Windows API
function.
>
Result := |DllCall|("[DllFile\]Function" [, Type1, Arg1, Type2, Arg2, "Cdecl ReturnType"])
<
Parameters~
Result
------
DllCall returns the actual value returned by the function. If the
function is of a type that does not return a value, the result is an
undefined integer. If the function cannot be called due to an error,
the return value is blank (an empty string).
[DllFile\]Function
------------------
The DLL or EXE file name followed by a backslash and the name of the
function. For example: "MyDLL\MyFunction" (the file extension ".dll"
is the default when omitted). If an absolute path isn't specified,
DllFile is assumed to be in the system's PATH or |A_WorkingDir|.
DllFile may be omitted when calling a function that resides in
User32.dll, Kernel32.dll, ComCtl32.dll, or Gdi32.dll. For example,
"User32\IsWindowVisible" produces the same result as
"IsWindowVisible".
If no function can be found by the given name, an A (ANSI) or W
(Unicode) suffix is automatically appended based on which version of
AutoHotkey is running the script. For example, "MessageBox" is the
same as "MessageBoxA" in ANSI versions and "MessageBoxW" in Unicode
versions.
Performance can be dramatically improved when making repeated calls to
a DLL by loading it beforehand.
In v1.0.46.08+, this parameter may also consist solely of an an
integer, which is interpreted as the address of the function to call.
Sources of such addresses include COM and |RegisterCallback|().
Type1, Arg1
-----------
Each of these pairs represents a single parameter to be passed to the
function. The number of pairs is unlimited. For Type, see the types
table below. For Arg, specify the value to be passed to the function.
Cdecl ReturnType
----------------
The word Cdecl is normally omitted because most functions use the
standard calling convention rather than the "C" calling convention
(functions such as wsprintf that accept a varying number of arguments
are one exception to this). If you omit Cdecl but the call yields
ErrorLevel An -- where n is the total size of the arguments you passed
-- Cdecl might be required. Note that most object-oriented C++
functions use the thiscall convention, which is not supported.
If present, the word Cdecl should be listed before the return type (if
any). Separate each word from the next with a space or tab. For
example: "Cdecl Str"
[AHK_L 53+]: Since a separate "C" calling convention does not exist in
64-bit code, Cdecl may be specified but has no effect on 64-bit builds
of AutoHotkey.
ReturnType: If the function returns a 32-bit signed integer (Int),
BOOL, or nothing at all, ReturnType may be omitted. Otherwise, specify
one of the argument types from the types table below. The asterisk
suffix is also supported.
*DllCall_Types*
Types of Arguments and Return Values~
Str
-----
A string such as "Blue" or MyVar. If the called function modifies the
string and the argument is a naked variable, its contents will be
updated. For example, the following call would convert the contents of
MyVar to uppercase: >
DllCall("CharUpper", "Str", MyVar)
<
However, if the function is designed to store a string larger than a
variable's current capacity, ensure that the variable is large enough
before calling the function. This can be achieved by calling >
VarSetCapacity(MyVar, 123)
<
where 123 is the length that MyVar must be able to hold.
A Str argument must not be an expression that evaluates to a number
(such as i+1). If it is, the function is not called and ErrorLevel is
set to -2.
The asterisk variable "Str*" is supported but rarely used. It can be
used with functions that expect something like "TCHAR **" or "LPTSTR
*".
Note: When passing a string to a function, be aware what type of
string the function expects.
AStr
WStr
-----
[AHK_L 42+]: An ANSI or Unicode (Wide character) string. See Script
Compatibility for equivalent Win32 types and other details.
Int64
-----
A 64-bit integer, whose range is -9223372036854775808
(-0x8000000000000000) to 9223372036854775807 (0x7FFFFFFFFFFFFFFF).
Int
-----
A 32-bit integer (the most common integer type), whose range is
-2147483648 (-0x80000000) to 2147483647 (0x7FFFFFFF). An Int is
sometimes called a "Long".
An Int should also be used for each BOOL argument expected by a
function (a BOOL value should be either 1 or 0).
An unsigned Int (UInt) is also used quite frequently, such as for
DWORD.
Short
-----
A 16-bit integer, whose range is -32768 (-0x8000) to 32767 (0x7FFF).
An unsigned Short (UShort) can be used with functions that expect a
WORD.
Char
-----
An 8-bit integer, whose range is -128 (-0x80) to 127 (0x7F). An
unsigned character (UChar) can be used with functions that expect a
BYTE.
Float
-----
A 32-bit floating point number, which provides 6 digits of precision.
Double
------
A 64-bit floating point number, which provides 15 digits of precision.
Ptr
-----
[AHK_L 42+]: A pointer-sized integer, equivalent to Int or Int64
depending on whether the exe running the script is 32-bit or 64-bit.
Ptr should be used for pointers to arrays or structures (such as RECT*
or LPPOINT) and almost all handles (such as HWND, HBRUSH or HBITMAP).
If the parameter is a pointer to a single numeric value such as
LPDWORD or int*, generally the * or P suffix should be used instead of
"Ptr".
Ptr can also be used with the * or P suffix; it should be used with
functions that output a pointer via LPVOID* or similar.
UPtr is also valid, but is only unsigned in 32-bit builds as
AutoHotkey does not support unsigned 64-bit integers.
If compatibility with older versions of AutoHotkey is required, use a
variable type as shown below:
>
Ptr := A_PtrSize ? "Ptr" : "UInt" ; If A_PtrSize is not defined, use UInt instead.
DllCall("DeleteFile", Ptr, &filename) ; Omit the quote marks around Ptr.
<
Note: To pass a NULL handle or pointer, pass the integer 0.
* or P (suffix)
---------------
Append an asterisk (with optional preceding space) to any of the above
types to cause the address of the argument to be passed rather than
the value itself (the called function must be designed to accept it).
Since the value of such an argument might be modified by the function,
whenever a naked variable is passed as the argument, that variable's
contents will be updated. For example, the following call would pass
the contents of MyVar to MyFunction by address, but would also update
MyVar to reflect any changes made to it by MyFunction: >
DllCall("MyDll\MyFunction", "Int*", MyVar).
<
In general, an asterisk is used whenever a function has an argument
type or return type that starts with "LP". The most common example is
LPDWORD, which is a pointer to a DWORD. Since a DWORD is an unsigned
32-bit integer, use "UInt*" or "UintP" to represent LPDWORD. An
asterisk should not be used for string types such as LPTSTR, pointers
to structures such as LPRECT, or arrays; for these, "Str" or "Ptr"
should be used, depending on whether you pass a variable or its
address.
Note: "Char*" is not the same as "Str" because "Char*" passes the
address of an 8-bit number, whereas "Str" passes the address of a
series of characters which may be either 8-bit (ANSI) or 16-bit
(Unicode), depending on the version of AutoHotkey. Similarly, "UInt*"
passes the address of a 32-bit number, so should not be used if the
function expects an array of values or a structure larger than 32
bits.
Since variables in AutoHotkey have no fixed type, the address passed
to the function points to temporary memory rather than the variable
itself. It is not necessary to call VarSetCapacity on the variable as
DllCall will update it correctly after the function returns.
U (prefix)
----------
Prepend the letter U to any of the integer types above to interpret it
as an unsigned integer (UInt64, UInt, UShort, and UChar). Strictly
speaking, this is necessary only for return values and asterisk
variables because it does not matter whether an argument passed by
value is unsigned or signed (except for Int64).
If a negative integer is specified for an unsigned argument, the
integer wraps around into the unsigned domain. For example, when -1 is
sent as a UInt, it would become 0xFFFFFFFF.
Unsigned 64-bit integers produced by a function are not supported.
Therefore, to work with numbers greater or equal to
0x8000000000000000, omit the U prefix and interpret any negative
values received from the function as large integers. For example, a
function that yields -1 as an Int64 is really yielding
0xFFFFFFFFFFFFFFFF if it is designed to yield a UInt64.
Note: When specifying an argument type or return type that does not
contain a space or asterisk, the quotes around it may be omitted. For
example, str can be used in place of "Str" and CDecl in place of
"CDecl". In addition, the letter P may be used in place of asterisk to
allow the quotes to be omitted there as well. For example: UIntP.
ErrorLevel~
[v1.1.04+] This function is able to throw an exception on failure. For
more information, see Runtime Errors.
ErrorLevel is set to one of the following values to indicate whether
the call succeeded or failed.
0
-----
Success.
-1 (negative 1)
---------------
The [DllFile\]Function parameter is a floating point number. A string
or positive integer is required.
-2
-----
The return type or one of the specified arg types is invalid. This
error can also be caused by passing an expression that evaluates to a
number to a string (str) argument.
-3
-----
The specified DllFile could not be accessed or loaded. If no explicit
path was specified for DllFile, the file must exist in the system's
PATH or A_WorkingDir. This error might also occur if the user lacks
permission to access the file, or if AutoHotkey is 32-bit and the DLL
is 64-bit or vice versa.
-4
-----
The specified function could not be found inside the DLL.
N (any positive number)
-----------------------
The function was called but it aborted with fatal exception number N
(for example, 0xC0000005 means "access violation"). In such cases, the
function returns a blank value (empty string), but any asterisk
variables are still updated. An example of a fatal exception is
dereferencing an invalid pointer such as NULL. Since a Cdecl function
never produces the "An" error in the next paragraph, it may generate
an exception when too few arguments are passed to it.
An (the letter A followed by an integer n)
------------------------------------------
The function was called but was passed too many or too few arguments.
"n" is the number of bytes by which the argument list was incorrect.
If n is positive, too many arguments (or arguments that were too
large) were passed, or the call requires CDecl. If n is negative, too
few arguments were passed. This situation should be corrected to
ensure reliable operation of the function. The presence of this error
may also indicate that an exception occurred, in which case the
function returns a blank value. Note that due to the x64 calling
convention, 64-bit builds never set ErrorLevel to An.
Exceptions and A_LastError~
In spite of the built-in exception handling, it is still possible to
crash a script with DllCall. This can happen when a function does not
directly generate an exception but yields something inappropriate,
such as a bad pointer or a string that is not terminated. This might
not be the function's fault if the script passed it an unsuitable
value such as a bad pointer or a "str" with insufficient capacity. A
script can also crash when it specifies an inappropriate argument type
or return type, such as claiming that an ordinary integer yielded by a
function is an asterisk variable or str.
The built-in variable A_LastError contains the result of the operating
system's GetLastError() function, which is called immediately after
the function is called (this has no measurable impact on performance).
A_LastError is a number between 0 and 4294967295 (always formatted as
decimal, not hexadecimal). Like ErrorLevel, A_LastError is a
per-thread setting; that is, interruptions by other threads cannot
change it. However, A_LastError is also set by Run/RunWait.
Performance~
When making repeated calls to a DLL, performance can be dramatically
improved by loading it explicitly (this is not necessary for a
standard DLL such as User32 because it is always resident). This
practice avoids the need for DllCall to internally call LoadLibrary
and FreeLibrary each time. For example:
>
hModule := DllCall("LoadLibrary", "Str", "MyFunctions.dll", "Ptr") ; Avoids the need for DllCall() in the loop to load the library.
Loop, C:\My Documents\*.*, , 1
result := DllCall("MyFunctions\BackupFile", "Str", A_LoopFileFullPath)
DllCall("FreeLibrary", "Ptr", hModule) ; To conserve memory, the DLL may be unloaded after using it
<
In v1.0.46.08+, even faster performance can be achieved by looking up
the function's address beforehand. For example:
>
; In the following example, if the DLL isn't yet loaded, use LoadLibrary in place of GetModuleHandle.
MulDivProc := DllCall("GetProcAddress", Ptr, DllCall("GetModuleHandle", Str, "kernel32", "Ptr"), AStr, "MulDiv", "Ptr")
Loop 500
DllCall(MulDivProc, Int, 3, Int, 4, Int, 3)
<
[AHK_L 31+]: If DllCall's first parameter is a literal string such as
"MulDiv" and the DLL containing the function is ordinarily loaded
before the script starts, the string is automatically resolved to a
function address. This built-in optimization is more effective than
the example shown above.
Also, adding the line #NoEnv anywhere in the script improves DllCall's
performance when unquoted parameter types are used (e.g. Int vs.
"Int").
Finally, when passing a string-variable to a function that will not
change the length of the string, performance is improved by passing
the variable by address (e.g. &MyVar) rather than as a "str"
(especially when the string is very long). The following example
converts a string to uppercase: >
DllCall("CharUpper", Ptr, &MyVar, Ptr).
<
Structures and Arrays~
A structure is a collection of members (fields) stored adjacently in
memory. Most members tend to be integers.
Functions that accept the address of a structure (or a memory-block
array) can be called by storing the structure's raw binary data in a
normal variable. The following steps are generally used:
1) Call >
VarSetCapacity(MyStruct, 123, 0)
<
to ensure that the target variable is large enough to hold the
structure's data. Replace 123 with a number that is at least as large
as the size of the structure. Specifying zero as the last parameter
is optional; it initializes all members to be binary zero, which is
typically used to avoid calling NumPut() as often in the next step.
2) If the target function uses the values initially in the structure,
call >
NumPut(123, MyStruct, 4, "UInt")
<
to initialize any members that should be non-zero. Replace 123 with
the integer to be put into the target member (or specify &Var to store
the address of a variable). Replace 4 with the offset of the target
member (see step #4 for description of "offset"). Replace "UInt" with
the appropriate type or omit it if the member is a pointer or handle.
3) Call the target function, passing the address of MyStruct as a UInt
(or Ptr in AHK_L 42+) argument. For example, >
DllCall("MyDll\MyFunc", Ptr, &MyStruct)
<
The function will examine and/or change some of the members.
4) Use >
MyInteger := NumGet(MyStruct, 4, "UInt")
<
to retrieve any desired integers from the structure. Replace 4 with
the offset of the target member in the structure. The first member is
always at offset 0. The second member is at offset 0 plus the size of
the first member (typically 4). Members beyond the second are at the
offset of the previous member plus the size of the previous member.
Most members -- such as DWORD, Int, and other types of 32-bit integers
-- are 4 bytes in size. Replace "UInt" with the appropriate type or
omit it if the member is a pointer or handle.
See Structure Examples for actual usages.
Known Limitations~
When a variable's address (e.g. &MyVar) is passed to a function and
that function alters the length of the variable's contents, subsequent
uses of the variable may behave incorrectly. To fix this, do one of
the following: 1) Pass MyVar as a "Str" argument rather than as a
Ptr/address; 2) In v1.0.44.03+, call >
VarSetCapacity(MyVar, -1)
<
to update the variable's internally-stored length after calling
DllCall.
Any binary zero stored in a variable by a function hides all data to
the right of the zero; that is, such data cannot be accessed or
changed by most commands and functions. However, such data can be
manipulated by the address operator and NumPut/NumGet, as well as
DllCall itself.
A function that returns the address of one of the strings that was
passed into it might return an identical string in a different memory
address than expected. For example calling >
CharLower(CharUpper(MyVar))
<
in a programming language would convert MyVar's contents to lowercase.
But when the same is done with DllCall(), MyVar would be uppercase
after the following call because CharLower would have operated on a
different/temporary string whose contents were identical to MyVar:
>
MyVar = ABC
result := DllCall("CharLower", str, DllCall("CharUpper", Str, MyVar, Str), Str)
<
To work around this, change the two underlined "Str" values above to
Ptr. This interprets CharUpper's return value as a pure address that
will get passed as an integer to CharLower.
Certain limitations may be encountered when dealing with strings. For
details, see Script Compatibility.
Component Object Model (COM)~
COM objects which are accessible to VBScript and similar languages are
typically also accessible to AutoHotkey via ComObjCreate, ComObjGet or
ComObjActive and the built-in object syntax.
COM objects which don't support IDispatch can be used with DllCall by
retrieving the address of a function from the virtual function table
of the object's interface. For more details, see the example further
below.
Much of the .NET Framework is also accessible via COM and DllCall. See
http://www.autohotkey.com/forum/topic26191.html.
Related~
Script Compatibility, |PostMessage|, |OnMessage|(), |RegisterCallback|(),
|Run|, |VarSetCapacity|, Functions, |SysGet|, MSDN Library
Examples~
>
; Example: Calls the Windows API function "MessageBox" and
; report which button the user presses.
WhichButton := DllCall("MessageBox", "Int", "0", "Str", "Press Yes or No", "Str", "Title of box", "Int", 4)
MsgBox You pressed button #%WhichButton%.
; Example: Changes the desktop wallpaper to the specified bitmap (.bmp) file.
DllCall("SystemParametersInfo", UInt, 0x14, UInt, 0, Str, A_WinDir . "\winnt.bmp", UInt, 2);
; Example: Calls the API function "IsWindowVisible" to find out if a Notepad window is visible.
DetectHiddenWindows On
if not DllCall("IsWindowVisible", "Ptr", WinExist("Untitled - Notepad"))
; WinExist() returns an HWND.
MsgBox The window is not visible.
; Example: Calls the API's wsprintf() to pad the number 432
; with leading zeros to make it 10 characters wide (0000000432).
VarSetCapacity(ZeroPaddedNumber, 20)
; Ensure the variable is large enough to accept the new string.
DllCall("wsprintf", "Str", ZeroPaddedNumber, "Str", "%010d", "Int", 432, "Cdecl")
; Requires the Cdecl calling convention.
MsgBox %ZeroPaddedNumber%
; Example: Demonstrates QueryPerformanceCounter(), which gives
; more precision than A_TickCount's 10ms.
DllCall("QueryPerformanceCounter", "Int64*", CounterBefore)
Sleep 1000
DllCall("QueryPerformanceCounter", "Int64*", CounterAfter)
MsgBox % "Elapsed QPC time is " . CounterAfter - CounterBefore
; Example: This is a hotkey that temporarily reduces the mouse
; cursor's speed, which facilitates precise positioning. ; Hold down
; the F1 key to slow down the cursor. Release it to return to
; original speed.
F1::
SPI_GETMOUSESPEED = 0x70
SPI_SETMOUSESPEED = 0x71
; Retrieve the current speed so that it can be restored later:
DllCall("SystemParametersInfo", UInt, SPI_GETMOUSESPEED, UInt, 0, UIntP, OrigMouseSpeed, UInt, 0)
; Now set the mouse to the slower speed specified in the
; next-to-last parameter (the range is 1-20, 10 is default):
DllCall("SystemParametersInfo", UInt, SPI_SETMOUSESPEED, UInt, 0, Ptr, 3, UInt, 0)
KeyWait F1
; This prevents keyboard auto-repeat from doing the DllCall repeatedly.
return
F1 up::DllCall("SystemParametersInfo", UInt, 0x71, UInt, 0, Ptr, OrigMouseSpeed, UInt, 0)
; Restore the original speed.
; Example: When passed a window's Unique ID and the text or
; ClassNN of one of its controls, ; the following function
; returns the HWND (unique ID) of that control. ;
; v1.0.43.06+: This function has been superseded by the
; following command, which is more accurate.
ControlGet, OutputVar, Hwnd,, ClassNN, WinTitle
; Example: Monitors the active window and display the position
; of its vertical scroll bar in its focused control (with
; real-time updates). This requires v1.0.43.06+ because it
; uses ControlGet Hwnd.
#Persistent
SetTimer, WatchScrollBar, 100
return
WatchScrollBar:
ActiveWindow := WinExist("A")
if not ActiveWindow ; No active window.
return
ControlGetFocus, FocusedControl, ahk_id %ActiveWindow%
if not FocusedControl ; No focused control.
return
; Display the vertical or horizontal scroll bar's position in a ToolTip:
ControlGet, ChildHWND, Hwnd,, %FocusedControl%, ahk_id %ActiveWindow%
ToolTip % DllCall("GetScrollPos", "Ptr", ChildHWND, "Int", 1)
; Last parameter is 1 for SB_VERT, 0 for SB_HORZ.
return
; Example: This is a working script that writes some text to a
; file then reads it back into memory (requires v1.0.34+). ;
; This method can be used to help performance in cases where
; multiple files are being read or written simultaneously.
; in AHK_L 42+, the same can be achieved using FileOpen.
FileSelectFile, FileName, S16,, Create a new file:
if FileName =
return
GENERIC_WRITE = 0x40000000
; Open the file for writing rather than reading.
CREATE_ALWAYS = 2
; Create new file (overwriting any existing file).
hFile := DllCall("CreateFile", Str, FileName, UInt, GENERIC_WRITE, UInt, 0, Ptr, 0, UInt, CREATE_ALWAYS, UInt, 0, Ptr, 0, Ptr)
if not hFile
{
MsgBox Can't open "%FileName%" for writing.
return
}
TestString = This is a test string.`r`n
; When writing a file this way, use `r`n rather than `n to start a new line.
DllCall("WriteFile", Ptr, hFile, Str, TestString, UInt, StrLen(TestString), UIntP, BytesActuallyWritten, Ptr, 0)
DllCall("CloseHandle", Ptr, hFile)
; Close the file.
; Now that the file was written, read its contents back into
; memory.
GENERIC_READ = 0x80000000
; Open the file for reading rather than writing.
OPEN_EXISTING = 3
; This mode indicates that the file to be opened must already
; exist.
FILE_SHARE_READ = 0x1
; This and the next are whether other processes can open the
; file while we have it open.
FILE_SHARE_WRITE = 0x2
hFile := DllCall("CreateFile", Str, FileName, UInt, GENERIC_READ, UInt, FILE_SHARE_READ|FILE_SHARE_WRITE, Ptr, 0, UInt, OPEN_EXISTING, UInt, 0, Ptr, 0)
if not hFile
{
MsgBox Can't open "%FileName%" for reading.
return
}
; Make the variable empty for testing purposes, but ensure it
; retains sufficient capacity:
BytesToRead := VarSetCapacity(TestString, StrLen(TestString))
DllCall("ReadFile", Ptr, hFile, Str, TestString, UInt, BytesToRead, UIntP, BytesActuallyRead, Ptr, 0)
DllCall("CloseHandle", Ptr, hFile)
; Close the file.
MsgBox The following string was read from the file: %TestString%
; Example: Hides the mouse cursor when you press Win+C. To
; later show the cursor, press Win+C again. This script is
; from www.autohotkey.com/forum/topic6107.html
OnExit, ShowCursor ; Ensure the cursor is made visible when the script exits.
return
ShowCursor:
SystemCursor("On")
ExitApp
#c::SystemCursor("Toggle")
; Win+C hotkey to toggle the cursor on and off.
SystemCursor(OnOff=1)
; INIT = "I","Init"; OFF = 0,"Off"; TOGGLE = -1,"T","Toggle"; ON = others
{
static AndMask, XorMask, $, h_cursor
,c0,c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13 ; system cursors
, b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13 ; blank cursors
, h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11,h12,h13 ; handles of default cursors
if (OnOff = "Init" or OnOff = "I" or $ = "") ; init when requested or at first call
{
$ = h ; active default cursors
VarSetCapacity( h_cursor,4444, 1 )
VarSetCapacity( AndMask, 32*4, 0xFF )
VarSetCapacity( XorMask, 32*4, 0 )
system_cursors = 32512,32513,32514,32515,32516,32642,32643,32644,32645,32646,32648,32649,32650
StringSplit c, system_cursors, `,
Loop %c0%
{
h_cursor := DllCall( "LoadCursor", "Ptr",0, "Ptr",c%A_Index% )
h%A_Index% := DllCall( "CopyImage", "Ptr",h_cursor, "UInt",2, "Int",0, "Int",0, "UInt",0 )
b%A_Index% := DllCall( "CreateCursor", "Ptr",0, "Int",0, "Int",0
, "Int",32, "Int",32, "Ptr",&AndMask, "Ptr",&XorMask )
}
}
if (OnOff = 0 or OnOff = "Off" or $ = "h" and (OnOff < 0 or OnOff = "Toggle" or OnOff = "T"))
$ = b ; use blank cursors
else
$ = h ; use the saved cursors
Loop %c0%
{
h_cursor := DllCall( "CopyImage", "Ptr",%$%%A_Index%, "UInt",2, "Int",0, "Int",0, "UInt",0 )
DllCall( "SetSystemCursor", "Ptr",h_cursor, "UInt",c%A_Index% )
}
}
; Structure Example: Pass the address of a RECT structure to
; GetWindowRect(), which sets the structure's ; members to the
; positions of the left, top, right, and bottom sides of a
; window (relative to the screen).
Run Notepad
WinWait Untitled - Notepad
; This also sets the "last found window" for use with
; WinExist() below.
VarSetCapacity(Rect, 16)
; A RECT is a struct consisting of four 32-bit integers (i.e. 4*4=16).
DllCall("GetWindowRect", Ptr, WinExist(), Ptr, &Rect)
; WinExist() returns an HWND.
MsgBox % "Left " . NumGet(Rect, 0, "Int") . " Top " . NumGet(Rect, 4, "Int")
. " Right " . NumGet(Rect, 8, "Int") . " Bottom " . NumGet(Rect, 12, "Int")
; Structure Example: Pass to FillRect() the address of a RECT
; structure that indicates a part of the screen to temporarily
; paint red.
VarSetCapacity(Rect, 16, 0)
; Set capacity to hold four 4-byte integers and initialize
; them all to zero.
NumPut(A_ScreenWidth//2, Rect, 8, "Int")
; The third integer in the structure is "rect.right".
NumPut(A_ScreenHeight//2, Rect, 12, "Int")
; The fourth integer in the structure is "rect.bottom".
hDC := DllCall("GetDC", "Ptr", 0, "Ptr")
; Pass zero to get the desktop's device context.
hBrush := DllCall("CreateSolidBrush", "UInt", 0x0000FF, "Ptr")
; Create a red brush (0x0000FF is in BGR format).
DllCall("FillRect", "Ptr", hDC, "Ptr", &Rect, "Ptr", hBrush)
; Fill the specified rectangle using the brush above.
DllCall("ReleaseDC", "Ptr", 0, "Ptr", hDC)
; Clean-up.
DllCall("DeleteObject", "Ptr", hBrush)
; Clean-up.
; Structure Example: Change the system's clock to the
; specified date and time. Use caution when
; changing to a date in the future as it may cause scheduled
; tasks to run prematurely!
SetSystemTime("20051008142211")
; Pass it a timestamp (local, not UTC).
SetSystemTime(YYYYMMDDHHMISS)
; Sets the system clock to the specified date and time. ;
; Caller must ensure that the incoming parameter is a valid
; date-time stamp (local time, not UTC). Returns non-zero upon
; success and zero otherwise.
{
; Convert the parameter from local time to UTC for use with SetSystemTime().
UTC_Delta -= A_NowUTC, Seconds ; Seconds is more accurate due to rounding issue.
UTC_Delta := Round(-UTC_Delta/60) ; Round to nearest minute to ensure accuracy.
YYYYMMDDHHMISS += UTC_Delta, Minutes ; Apply offset to convert to UTC.
VarSetCapacity(SystemTime, 16, 0) ; This struct consists of 8 UShorts (i.e. 8*2=16).
StringLeft, Int, YYYYMMDDHHMISS, 4 ; YYYY (year)
NumPut(Int, SystemTime, 0, "UShort")
StringMid, Int, YYYYMMDDHHMISS, 5, 2 ; MM (month of year, 1-12)
NumPut(Int, SystemTime, 2, "UShort")
StringMid, Int, YYYYMMDDHHMISS, 7, 2 ; DD (day of month)
NumPut(Int, SystemTime, 6, "UShort")
StringMid, Int, YYYYMMDDHHMISS, 9, 2 ; HH (hour in 24-hour time)
NumPut(Int, SystemTime, 8, "UShort")
StringMid, Int, YYYYMMDDHHMISS, 11, 2 ; MI (minute)
NumPut(Int, SystemTime, 10, "UShort")
StringMid, Int, YYYYMMDDHHMISS, 13, 2 ; SS (second)
NumPut(Int, SystemTime, 12, "UShort")
return DllCall("SetSystemTime", Ptr, &SystemTime)
}
/* More Structure Examples:
1) See the WinLIRC client script for a demonstration of how to use DllCall() to make a network connection
to a TCP/IP server and receive data from it.
2) The operating system offers standard dialog boxes that prompt the user to pick a font and/or color, or an icon.
These dialogs use structures and are demonstrated at www.autohotkey.com/forum/topic17230.html.
*/
/*
Example: Temporarily remove the active window from the taskbar by using COM.
Methods in ITaskbarList's VTable:
IUnknown:
0 QueryInterface -- use ComObjQuery instead
1 AddRef -- use ObjAddRef instead
2 Release -- use ObjRelease instead
ITaskbarList:
3 HrInit
4 AddTab
5 DeleteTab
6 ActivateTab
7 SetActiveAlt
*/
IID_ITaskbarList := "{56FDF342-FD6D-11d0-958A-006097C9A090}"
CLSID_TaskbarList := "{56FDF344-FD6D-11d0-958A-006097C9A090}"
; Create the TaskbarList object and store its address in tbl.
tbl := ComObjCreate(CLSID_TaskbarList, IID_ITaskbarList)
activeHwnd := WinExist("A")
DllCall(vtable(tbl,3), "ptr", tbl) ; tbl.HrInit()
DllCall(vtable(tbl,5), "ptr", tbl, "ptr", activeHwnd) ; tbl.DeleteTab(activeHwnd)
Sleep 3000
DllCall(vtable(tbl,4), "ptr", tbl, "ptr", activeHwnd) ; tbl.AddTab(activeHwnd)
; Non-dispatch objects must always be manually freed.
ObjRelease(tbl)
vtable(ptr, n) {
; NumGet(ptr+0) returns the address of the object's virtual function
; table (vtable for short). The remainder of the expression retrieves
; the address of the nth function's address from the vtable.
return NumGet(NumGet(ptr+0), n*A_PtrSize)
}
==============================================================================
*StringLower* *StringUpper*
+---------------------------+~
| StringLower - StringUpper |~
+---------------------------+~
Converts a string to lowercase or uppercase.
>
StringLower, OutputVar, InputVar [, T]
StringUpper, OutputVar, InputVar [, T]
<
Parameters~
OutputVar
---------
The name of the variable in which to store newly converted string.
InputVar
--------
The name of the variable whose contents will be read from. Do not
enclose the name in percent signs unless you want the contents of the
variable to be used as the name.
T
-----
If this parameter is the letter T, the string will be converted to
title case. For example, "GONE with the WIND" would become "Gone With
The Wind".
Remarks~
To detect whether a character or string is entirely uppercase or
lowercase, use "if var is [not] upper/lower".
For this and all other commands, OutputVar is allowed to be the same
variable as an InputVar.
Related~
|IfInString|, |StringGetPos|, |StringMid|, |StringTrimLeft|,
|StringTrimRight|, |StringLeft|, |StringRight|, |StringLen|,
|StringReplace|
Example~
>
StringUpper, String1, String1 ; i.e. output can be the same as input.
StringLower, String2, String2
<
==============================================================================
*Suspend*
+---------+~
| Suspend |~
+---------+~
Disables or enables all or selected hotkeys and hotstrings.
>
Suspend [, Mode]
<
Parameters~
Mode
-----
On: Suspends all hotkeys and hotstrings except those explained the
Remarks section.
Off: Re-enables the hotkeys and hotstrings that were disable above.
Toggle (default): Changes to the opposite of its previous state (On or
Off).
Permit: Does nothing except mark the current subroutine as being
exempt from suspension.
Remarks~
Any hotkey/hotstring subroutine whose very first line is Suspend
(except Suspend On) will be exempt from suspension. In other words,
the hotkey will remain enabled even while suspension is ON. This
allows suspension to be turned off via such a hotkey.
To disable selected hotkeys or hotstrings automatically based on the
type of window that is present, use #IfWinActive/Exist.
Suspending a script's hotkeys does not stop the script's
already-running threads (if any); use Pause to do that.
When a script's hotkeys are suspended, its tray icon changes to the
letter S. This can be avoided by freezing the icon, which is done by
specifying 1 for the last parameter of the Menu command. For example:
>
Menu, Tray, Icon, C:\My Icon.ico, , 1
<
The built-in variable A_IsSuspended contains 1 if the script is
suspended and 0 otherwise.
Related~
|#IfWinActive|/ |#IfWinExist|, |Pause|, |Menu|, |ExitApp|
Example~
>
^!s::Suspend ; Assign the toggle-suspend function to a hotkey.
; Send a Suspend command to another script.
DetectHiddenWindows, On
WM_COMMAND := 0x111
ID_FILE_SUSPEND := 65404
PostMessage, WM_COMMAND, ID_FILE_SUSPEND,,, C:\YourScript.ahk ahk_class AutoHotkey
<
==============================================================================
*Continue*
*continue*
+----------+~
| Continue |~
+----------+~
Skips the rest of the current loop iteration and begins a new one.
Valid inside any kind of loop.
>
Continue [, LoopLabel]
<
[AHK_L 59+]~
-----------
If specified, LoopLabel identifies which loop this statement should
apply to; either by label name or numeric nesting level. If omitted or
1, this statement applies to the innermost loop in which it is
enclosed. LoopLabel must be a constant value - variables and
expressions are not supported. If a label is specified, it must point
directly at a loop command.
Continue behaves the same as reaching the loop's closing brace:
1. It increases A_Index by 1.
2. It skips the rest of the loop's body.
3. The loop's condition (if it has one) is checked to see if it is
satisified. If so, a new iteration begins; otherwise the loop ends.
The use of Break and Continue are encouraged over goto since they
usually make scripts more readable and maintainable.
Related~
|Break|, |Loop|, |Until|, While-loop, For-loop, Blocks, Labels
Example~
>
; This example displays 5 MsgBoxes, one for each number
; between 6 and 10. Note that in the first 5 iterations of
; the Loop, the "continue" command causes the loop to start
; over before it reaches the MsgBox line.
Loop, 10
{
if A_Index <= 5
continue
MsgBox %A_Index%
}; Continue the outer loop from within a nested loop.
outer:
Loop 3
{
x := A_Index
Loop 3
{
if (x*A_Index = 4)
continue outer ; Equivalent to continue 2 or
; goto continue_outer. MsgBox
; %x%,%A_Index% }
continue_outer: ; For goto.
ErrorLevel:=ErrorLevel ; Prior to revision 57, labels
; could not point to the end
; of a block.
}
<
==============================================================================
*Menu*
*Tray*
+------+~
| 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.
>
Menu, MenuName, Cmd [, P3, P4, P5]
<
Parameters~
MenuName
--------
It can be TRAY or the name of any custom menu. A custom menu is
automatically created the first time its name is used with the Add
command. For example: Menu, MyMenu, Add, Item1.
Once created, a custom menu can be displayed with the Show command. It
can also be attached as a submenu to one or more other menus via the
Add command.
Cmd, P3, P4, P5
---------------
These 4 parameters are dependent on each other. See list below for the
allowed combinations
Add or Change Items in a Menu~
=============================
Add [, MenuItemName, Label-or-Submenu, Pn]: ~
This is a multipurpose command that adds a menu item, updates one with
a new submenu or label, or converts one from a normal item into a
submenu (or vice versa). If MenuItemName does not yet exist, it will
be added to the menu. Otherwise, MenuItemName is updated with the
newly specified Label-or-Submenu.
To add a menu separator line, omit all three parameters.
The label subroutine is run as a new thread when the user selects the
menu item (similar to Gosub and hotkey subroutines). If
Label-or-Submenu is omitted, MenuItemName will be used as both the
label and the menu item's name.
[v1.1.20+]: If it is not the name of an existing label,
Label-or-Submenu can be the name of a function, or a single variable
reference containing a function object. For example, %funcobj% or %
funcobj. Other expressions which return objects are currently
unsupported. The function can optionally define parameters as shown
below:
>
FunctionName(ItemName, ItemPos, MenuName)
<
To have MenuItemName become a submenu -- which is a menu item that
opens a new menu when selected -- specify for Label-or-Submenu a colon
followed by the MenuName of an existing custom menu. For example:
>
Menu, MySubmenu, add, Item1
Menu, tray, add, This Menu Item Is A Submenu, :MySubmenu
<
Delete [, MenuItemName]:~
Deletes MenuItemName from the menu. Standard menu items such as Exit
(see below) cannot be individually deleted. If the default menu item
is deleted, the effect will be similar to having used the NoDefault
option. If MenuItemName is omitted, the entire MenuName menu will be
deleted as will any menu items in other menus that use MenuName as a
submenu.
DeleteAll:~
Deletes all custom menu items from the menu, leaving the menu empty
unless it contains the standard items (see below). Unlike a menu
entirely deleted by the Delete command (see above), an empty menu
still exists and thus any other menus that use it as a submenu will
retain those submenus.
Rename, MenuItemName [, NewName]:~
Changes MenuItemName to NewName (if NewName is blank, MenuItemName
will be converted into a separator line). NewName must not be the same
as any existing custom menu item. The menu item's current target label
or submenu is unchanged.
Check, MenuItemName:~
Adds a visible checkmark in the menu next to MenuItemName (if there
isn't one already).
Uncheck, MenuItemName:~
Removes the checkmark (if there is one) from MenuItemName.
ToggleCheck, MenuItemName:~
Adds a checkmark if there wasn't one; otherwise, removes it.
Enable, MenuItemName:~
Allows the user to once again select MenuItemName if was previously
disabled (grayed).
Disable, MenuItemName:~
Changes MenuItemName to a gray color to indicate that the user cannot
select it.
ToggleEnable, MenuItemName:~
Disables MenuItemName if it was previously enabled; otherwise, enables it.
Default [, MenuItemName]:~
Changes the menu's default item to be MenuItemName and makes that
item's font bold (setting a default item in menus other than TRAY is
currently purely cosmetic). When the user double-clicks the tray icon,
its default menu item is launched. If there is no default,
double-clicking has no effect. If MenuItemName is omitted, the effect
is the same as having used NoDefault below.
NoDefault:~
For the tray menu: Changes the menu back to having its standard
default menu item, which is OPEN for non-compiled scripts and none for
compiled scripts (except when the MainWindow option is in effect). If
the OPEN menu item does not exist due to a previous use of the
NoStandard command below, there will be no default and thus
double-clicking the tray icon will have no effect. For menus other
than TRAY: Any existing default item is returned to a non-bold font.
Standard:~
Inserts the standard menu items at the bottom of the menu (if they are
not already present). This command can be used with the tray menu or
any other menu.
NoStandard:~
Removes all standard (non-custom) menu items from the tray menu (if
they are present).
Set or Remove a Menu Item's Icon [v1.0.90+]~
===========================================
Icon, MenuItemName, FileName [, IconNumber, IconWidth]:~
Sets MenuItemName's icon. FileName can either be an icon file or any
image in a format supported by AutoHotkey. To use an icon group other
than the first one in the file, specify its number for IconNumber (if
omitted, it defaults to 1). If IconNumber is negative, its absolute
value is assumed to be the resource ID of an icon within an executable
file. Specify the desired width of the icon in IconWidth. If the icon
group indicated by IconNumber contains multiple icon sizes, the
closest match is used and the icon is scaled to the specified size.
See the Examples section for usage examples.
Currently it is necessary to specify "actual size" when setting the
icon to preserve transparency on Windows Vista and later. For example:
>
Menu, MenuName, Icon, MenuItemName, Filename.png,, 0
<
Known limitation: Icons on Gui menu bars are positioned incorrectly on
Windows XP and older.
NoIcon, MenuItemName:~
Removes MenuItemName's icon, if any.
*Change_icon_system_tray*
*How_to_have_your_own_icon_System_Tray*
Change the Tray Icon or ToolTip (MenuName must be TRAY)~
=======================================================
Icon [, FileName, IconNumber, 1]:~
Changes the script's icon to one of the ones from FileName. The
following types of files are supported: ICO, CUR, ANI, EXE, DLL, CPL,
SCR, and other types that contain icon resources. To use an icon group
other than the first one in the file, specify its number for
IconNumber (if omitted, it defaults to 1). For example, 2 would load
the default icon from the second icon group. If IconNumber is
negative, its absolute value is assumed to be the resource ID of an
icon within an executable file. Specify an asterisk (*) for FileName
to restore the script to its default icon.
The last parameter: Specify 1 for the last parameter to freeze the
icon, or 0 to unfreeze it (or leave it blank to keep the
frozen/unfrozen state unchanged). When the icon has been frozen, Pause
and Suspend will not change it. Note: To freeze or unfreeze the
current icon, use 1 or 0 as in the following example: Menu, Tray,
Icon,,, 1.
Changing the tray icon also changes the icon displayed by InputBox,
Progress, and subsequently-created GUI windows. Compiled scripts are
also affected even if a custom icon was specified at the time of
compiling. Note: Changing the icon will not unhide the tray icon if it
was previously hidden by means such as #NoTrayIcon; to do that, use
Menu, Tray, Icon (with no parameters).
Slight distortion may occur when loading tray icons from file types
other than .ICO. This is especially true for 16x16 icons. To prevent
this, store the desired tray icon inside a .ICO file.
There are some icons built into the operating system's DLLs and CPLs
that might be useful. For example: Menu, Tray, Icon, Shell32.dll, 174.
The built-in variables A_IconNumber and A_IconFile contain the number
and name (with full path) of the current icon (both are blank if the
icon is the default).
Icon (with no parameters):~
Creates the tray icon if it isn't already present. This will override
#NoTrayIcon if that directive is also present in the script.
NoIcon:~
Removes the tray icon if it exists. If this command is used at the
very top of the script, the tray icon might be briefly visible when
the script is launched. To prevent that, use #NoTrayIcon instead. The
built-in variable A_IconHidden contains 1 if the tray icon is
currently hidden or 0 otherwise.
Tip [, Text]:~
Changes the tray icon's tooltip -- which is displayed when the mouse
hovers over it. To create a multi-line tooltip, use the linefeed
character (`n) in between each line, e.g. Line1`nLine2. Only the first
127 characters of Text are displayed, and Text is truncated at the
first tab character, if present. If Text is omitted, the tooltip is
restored to its default text. The built-in variable A_IconTip contains
the current text of the tooltip (blank if the text is at its default).
Miscellaneous Commands~
======================
Show [, X, Y]:~
Displays MenuName, allowing the user to select an item with arrow
keys, menu shortcuts (underlined letters), or the mouse. Any menu can
be shown, including the tray menu but with the exception of GUI menu
bars. If both X and Y are omitted, the menu is displayed at the
current position of the mouse cursor. If only one of them is omitted,
the mouse cursor's position will be used for it. X and Y are relative
to the active window. Specify "CoordMode, Menu" beforehand to make
them relative to the entire screen.
Color, ColorValue [, Single]:~
Changes the background color of the menu to ColorValue, which is one
of the 16 primary HTML color names or a 6-digit RGB color value (see
color chart). Leave ColorValue blank (or specify the word Default) to
restore the menu to its default color. If the word Single is not
present as the next parameter, any submenus attached to this menu will
also be changed in color.
Click, ClickCount:~
Specify 1 for ClickCount to allow a single-click to activate the tray
menu's default menu item. Specify 2 for ClickCount to return to the
default behavior (double-click). For example: Menu, Tray, Click, 1.
MainWindow:~
This command affects compiled scripts only. It allows the script's
main window to be opened via the tray icon, which is otherwise
impossible. It also enables the items in the main window's View menu
such as "Lines most recently executed", which allows viewing of the
script's source code and other info. MenuName must be TRAY.
NoMainWindow (default):~
This command affects compiled scripts only. It restores the script to
its default behavior, that is, it prevents the main window from being
opened. Even while this option is in effect, the following commands
are still able to show the main window when they are encountered in
the script at runtime: ListLines, ListVars, ListHotkeys, and
KeyHistory. MenuName must be TRAY.
UseErrorLevel [, off]:~
If this option is never used in the script, it defaults to OFF. The
OFF setting displays a dialog and terminates the current thread
whenever the Menu command generates an error. Specify Menu, Tray,
UseErrorLevel to prevent the dialog and thread termination; instead,
ErrorLevel will be set to 1 if there was a problem or 0 otherwise. To
turn this option back off, specify OFF for the next parameter. This
setting is global, meaning it affects all menus, not just MenuName.
Remarks~
=======
To underline one of the letters in a menu item's name, precede that
letter with an ampersand (&). When the menu is displayed, such an item
can be selected by pressing the corresponding key on the keyboard. To
display a literal ampersand, specify two consecutive ampersands as in
this example: "Save && Exit"
The names of menus and menu items can be up to 260 characters long.
When referring to an existing menu or menu item, the name is not case
sensitive but any ampersands must be included. For example: &Open
Separator lines can be added to the menu by using Menu, Tray, Add
(i.e. omit all other parameters). However, separator lines currently
cannot be individually deleted. To work around this, use Menu, Tray,
DeleteAll and then re-add your custom menu items.
New menu items are always added at the bottom of the menu. For the
tray menu: To put your menu items on top of the standard menu items
(after adding your own menu items) run Menu, Tray, NoStandard followed
by Menu, Tray, Standard.
The standard menu items such as "Pause Script" and "Suspend Hotkeys"
cannot be individually operated upon by any menu sub-command.
If a menu ever becomes completely empty -- such as by using Menu,
MyMenu, DeleteAll -- it cannot be shown. If the tray menu becomes
empty, right-clicking and double-clicking the tray icon will have no
effect (in such cases it is usually better to use #NoTrayIcon).
If a menu item's subroutine is already running and the user selects
the same menu item again, a new thread will be created to run that
same subroutine, interrupting the previous thread. To instead buffer
such events until later, use Critical as the subroutine's first line
(however, this will also buffer/defer other threads such as the press
of a hotkey).
Whenever a subroutine is launched via a menu item, it starts off fresh
with the default values for settings such as SendMode. These defaults
can be changed in the auto-execute section.
The built-in variables A_ThisMenuItem and A_ThisMenuItemPos contain
the name and position of the custom menu item most recently selected
by the user (blank if none). Similarly, A_ThisMenu is the name of the
menu from which A_ThisMenuItem was selected. These variables are
useful when building a menu whose contents are not always the same. In
such a case, it is usually best to point all such menu items to the
same label and have that label refer to the above variables to
determine what action to take.
To keep a non-hotkey, non-GUI script running -- such as one that
contains only custom menus or menu items -- use #Persistent.
Related~
=======
|GUI|, |Threads|, |Thread|, |Critical|, |#NoTrayIcon|, |Gosub|,
|Return|, |SetTimer|, |#Persistent|
Examples~
========
>
; EXAMPLE #1: This is a working script that adds a new menu item to the bottom of the tray icon menu.
#Persistent ; Keep the script running until the user exits it.
Menu, tray, add ; Creates a separator line.
Menu, tray, add, Item1, MenuHandler ; Creates a new menu item.
return
MenuHandler:
MsgBox You selected %A_ThisMenuItem% from menu %A_ThisMenu%.
return
<
>
; EXAMPLE #2: This is a working script that creates a popup menu that is displayed when the user presses the Win-Z hotkey.
; Create the popup menu by adding some items to it.
Menu, MyMenu, Add, Item1, MenuHandler
Menu, MyMenu, Add, Item2, MenuHandler
Menu, MyMenu, Add ; Add a separator line.
; Create another menu destined to become a submenu of the above menu.
Menu, Submenu1, Add, Item1, MenuHandler
Menu, Submenu1, Add, Item2, MenuHandler
; Create a submenu in the first menu (a right-arrow indicator). When the user selects it, the second menu is displayed.
Menu, MyMenu, Add, My Submenu, :Submenu1
Menu, MyMenu, Add ; Add a separator line below the submenu.
Menu, MyMenu, Add, Item3, MenuHandler ; Add another menu item beneath the submenu.
return ; End of script's auto-execute section.
MenuHandler:
MsgBox You selected %A_ThisMenuItem% from the menu %A_ThisMenu%.
return
#z::Menu, MyMenu, Show ; i.e. press the Win-Z hotkey to show the menu.
<
>
; EXAMPLE #3: This is a working script that demonstrates some of the various menu commands.
#Persistent
#SingleInstance
menu, tray, add ; separator
menu, tray, add, TestToggle&Check
menu, tray, add, TestToggleEnable
menu, tray, add, TestDefault
menu, tray, add, TestStandard
menu, tray, add, TestDelete
menu, tray, add, TestDeleteAll
menu, tray, add, TestRename
menu, tray, add, Test
return
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
TestToggle&Check:
menu, tray, ToggleCheck, TestToggle&Check
menu, tray, Enable, TestToggleEnable ; Also enables the next test since it can't undo the disabling of itself.
menu, tray, add, TestDelete ; Similar to above.
return
TestToggleEnable:
menu, tray, ToggleEnable, TestToggleEnable
return
TestDefault:
if default = TestDefault
{
menu, tray, NoDefault
default =
}
else
{
menu, tray, Default, TestDefault
default = TestDefault
}
return
TestStandard:
if standard <> n
{
menu, tray, NoStandard
standard = n
}
else
{
menu, tray, Standard
standard = y
}
return
TestDelete:
menu, tray, delete, TestDelete
return
TestDeleteAll:
menu, tray, DeleteAll
return
TestRename:
if NewName <> renamed
{
OldName = TestRename
NewName = renamed
}
else
{
OldName = renamed
NewName = TestRename
}
menu, tray, rename, %OldName%, %NewName%
return
Test:
MsgBox, You selected "%A_ThisMenuItem%" in menu "%A_ThisMenu%".
return
<
>
; EXAMPLE #4: This is a working script that adds icons to its menu items.
Menu, FileMenu, Add, Script Icon, MenuHandler
Menu, FileMenu, Add, Suspend Icon, MenuHandler
Menu, FileMenu, Add, Pause Icon, MenuHandler
Menu, FileMenu, Icon, Script Icon, %A_AhkPath%, 2 ;Use the 2nd icon group from the file
Menu, FileMenu, Icon, Suspend Icon, %A_AhkPath%, -206 ;Use icon with resource identifier 206
Menu, FileMenu, Icon, Pause Icon, %A_AhkPath%, -207 ;Use icon with resource identifier 207
Menu, MyMenuBar, Add, &File, :FileMenu
Gui, Menu, MyMenuBar
Gui, Add, Button, gExit, Exit This Example
Gui, Show
MenuHandler:
Return
Exit:
ExitApp
<
==============================================================================
*Exit*
+------+~
| Exit |~
+------+~
Exits the current thread or (if the script is not persistent and
contains no hotkeys) the entire script.
>
Exit [, ExitCode]
<
Parameters~
ExitCode
--------
An integer between -2147483648 and 2147483647 (can be an expression)
that is returned to its caller when the script exits. This code is
accessible to any program that spawned the script, such as another
script (via RunWait) or a batch (.bat) file. If omitted, ExitCode
defaults to zero. Zero is traditionally used to indicate success.
Remarks~
If the script has no hotkeys, isn't persistent, and hasn't requested
the Num/Scroll/CapsLock key(s) to be kept AlwaysOn or AlwaysOff, it
will terminate immediately when Exit is encountered (except if it has
an OnExit subroutine).
Otherwise, the Exit command terminates the current thread. In other
words, the stack of subroutines called directly or indirectly by a
menu, timer, or hotkey subroutine will all be returned from as though
a Return were immediately encountered in each. If used directly inside
such a subroutine -- rather than in one of the subroutines called
indirectly by it -- Exit is equivalent to Return.
Use ExitApp to completely terminate a script that is persistent or
contains hotkeys.
Related~
|ExitApp|, |OnExit|, |Functions|, |Gosub|, |Return|, |Threads|,
|#Persistent|
Example~
>
#z::
Gosub, Sub2
MsgBox, This msgbox will never happen because of the EXIT.
return
Sub2:
Exit ; Terminate this subroutine as well as the calling subroutine.
<
==============================================================================
*ExitApp*
+---------+~
| ExitApp |~
+---------+~
Terminates the script unconditionally.
>
ExitApp [, ExitCode]
<
Parameters~
ExitCode
--------
An integer between -2147483648 and 2147483647 (can be an expression in
v1.0.48.01+) that is returned to its caller when the script exits.
This code is accessible to any program that spawned the script, such
as another script (via RunWait) or a batch (.bat) file. If omitted,
ExitCode defaults to zero. Zero is traditionally used to indicate
success.
Remarks~
The script is immediately terminated unless it has an OnExit
subroutine. This is equivalent to choosing "Exit" from the script's
tray menu or main menu.
Exit and ExitApp behave identically when the script contains no
hotkeys, is not persistent, and does not ask for the
Num/Scroll/Capslock key(s) to be kept AlwaysOn or AlwaysOff.
If the script has an OnExit subroutine, it will be run in response to
ExitApp.
Related~
|Exit|, |OnExit|, |#Persistent|
Example~
>
#x::ExitApp ; Assign a hotkey to terminate this script.
==============================================================================
*VarSetCapacity*
+----------------+~
| VarSetCapacity |~
+----------------+~
Enlarges a variable's holding capacity or frees its memory. Normally,
this is necessary only for unusual circumstances such as DllCall.
>
GrantedCapacity := VarSetCapacity(UnquotedVarName [, RequestedCapacity, FillByte])
<
Parameters~
GrantedCapacity
---------------
The number of bytes that Var can now hold, which will be greater than
or equal to RequestedCapacity. If VarName is not a valid variable name
(such as a literal string or number), 0 is returned. If the system has
insufficient memory to make the change (very rare), an error dialog is
displayed and the current capacity is returned - this behaviour may
change in a future version.
UnquotedVarName
---------------
The name of the variable (not in quotes). For example:
VarSetCapacity(MyVar, 1000). This can also be a dynamic variable such
as Array%i% or a function's ByRef parameter.
RequestedCapacity
-----------------
If omitted, the variable's current capacity will be returned and its
contents will not be altered. Otherwise, anything currently in the
variable is lost (the variable becomes blank).
Specify for RequestedCapacity the number of bytes that the variable
should be able to hold after the adjustment. For Unicode strings, this
should be the length times two. RequestedCapacity does not include the
internal zero terminator. For example, specifying 1 would allow the
variable to hold up to one byte in addition to its internal
terminator. Note: the variable will auto-expand if the script assigns
it a larger value later.
Since this function is often called simply to ensure the variable has
a certain minimum capacity, for performance reasons, it shrinks the
variable only when RequestedCapacity is 0. In other words, if the
variable's capacity is already greater than RequestedCapacity, it will
not be reduced (but the variable will still made blank for
consistency).
Therefore, to explicitly shrink a variable, first free its memory with
VarSetCapacity(Var, 0) and then use VarSetCapacity(Var, NewCapacity)
-- or simply let it auto-expand from zero as needed.
For performance reasons, freeing a variable whose previous capacity
was less than 64 characters (128 bytes in Unicode builds) might have
no effect because its memory is of a permanent type. In this case, the
current capacity will be returned rather than 0.
For performance reasons, the memory of a variable whose capacity is
less than 4096 bytes is not freed by storing an empty string in it
(e.g. Var := ""). However, VarSetCapacity(Var, 0) does free it.
In v1.0.44.03+, specify -1 for RequestedCapacity to update the
variable's internally-stored string length to the length of its
current contents. This is useful in cases where the variable has been
altered indirectly, such as by passing its address via DllCall(). In
this mode, VarSetCapacity() returns the length in bytes rather than
the capacity.
FillByte
--------
This parameter is normally omitted, in which case the memory of the
target variable is not initialized (instead, the variable is simply
made blank as described above). Otherwise, specify a number between 0
and 255. Each byte in the target variable's memory area (its current
capacity, which might be greater than RequestedCapacity) is set to
that number. Zero is by far the most common value, which is useful in
cases where the variable will hold raw binary data such as a DllCall
structure.
Remarks~
In addition to its uses described at DllCall, this function can also
be used to enhance performance when building a string by means of
gradual concatenation. This is because multiple automatic resizings
can be avoided when you have some idea of what the string's final
length will be. In such a case, RequestedCapacity need not be
accurate: if the capacity is too small, performance is still improved
and the variable will begin auto-expanding when the capacity has been
exhausted. If the capacity is too large, some of the memory is wasted,
but only temporarily because all the memory can be freed after the
operation by means of VarSetCapacity(Var, 0) or Var := "".
#MaxMem restricts only the automatic expansion that a variable does on
its own. It does not affect VarSetCapacity.
Related~
|DllCall|, |#MaxMem|, |NumPut|, |NumGet|
Example~
>
; Optimize by ensuring MyVar has plenty of space to work with.
VarSetCapacity(MyVar, 10240000) ; ~10 MB
Loop
{
...
MyVar = %MyVar%%StringToConcatenate%
...
}
; Calculate required buffer space for a string.
bytes_per_char := A_IsUnicode ? 2 : 1
max_chars := 500
max_bytes := max_chars * bytes_per_char
Loop 2
{
; Allocate space for use with DllCall.
VarSetCapacity(buf, max_bytes)
if A_Index = 1
; Alter the variable indirectly via DllCall.
DllCall("wsprintf", "ptr", &buf, "str", "0x%08x", "uint", 4919)
else
; Use "str" to update the length automatically:
DllCall("wsprintf", "str", buf, "str", "0x%08x", "uint", 4919)
; Concatenate a string to demonstrate why the length needs to be updated:
wrong_str := buf . ""
wrong_len := StrLen(buf)
; Update the variable's length.
VarSetCapacity(buf, -1)
right_str := buf . ""
right_len := StrLen(buf)
MsgBox,
(
Before updating
String: %wrong_str%
Length: %wrong_len%
After updating
String: %right_str%
Length: %right_len%
)
}
==============================================================================
*#MaxMem*
+---------+~
| #MaxMem |~
+---------+~
Sets the maximum capacity of each variable to the specified number of
megabytes.
>
#MaxMem Megabytes
<
Parameters~
Megabytes
---------
The number of megabytes to allow for each variable. A value larger
than 4095 is considered to be 4095. A value less than 1 is considered
to be 1.
Remarks~
If this directive is unspecified in the script, it will behave as
though set to 64.
The purpose of limiting each variable's capacity is to prevent a buggy
script from consuming all available system memory. Raising or lowering
the limit does not affect the performance of a script, nor does it
change how much memory the script actually uses (except in the case of
WinGetText and ControlGetText, which will be capable of retrieving
more text if #MaxMem is increased).
This setting is global, meaning that it needs to be specified only
once (anywhere in the script) to affect the behavior of the entire
script.
This setting restricts only the automatic expansion that a variable
does on its own. It does not affect VarSetCapacity.
Related~
|VarSetCapacity|, |Variables|, Sort, |WinGetText|, ControlGetText,
#MaxThreads
Example~
>
#MaxMem 256 ; Allow 256 MB per variable.
<
==============================================================================
*NumPut*
+--------+~
| NumPut |~
+--------+~
Stores a number in binary format at the specified address+offset.
>
NumPut(Number, VarOrAddress [, Offset = 0][, Type = "UPtr"])
<
Parameters~
Number
------
The number to store.
VarOrAddress
------------
A memory address or variable. If VarOrAddress is a variable such as
MyVar, the address of the variable's string buffer is used. This is
usually equivalent to passing &MyVar, but omitting the "&" performs
better and ensures that the target address + offset is valid.
Do not pass a variable reference if the variable contains the target
address; in that case, pass an expression such as MyVar+0.
Offset
------
An offset - in bytes - which is added to VarOrAddress to determine the
target address.
Type
-----
One of the following strings (defaults to UPtr if omitted): UInt, Int,
Int64, Short, UShort, Char, UChar, Double, Float, Ptr or UPtr
Unlike DllCall, these must be enclosed in quotes when used as literal
strings.
For details see |DllCall_Types|.
Return Value~
If the target address is invalid, an empty string is returned.
However, some invalid addresses cannot be detected as such and may
cause unpredictable behaviour.
Otherwise, the address to the right of the item just written is
returned. This is often used when writing a sequence of numbers of
different types, such as in a structure for use with DllCall.
General Remarks~
If an integer is too large to fit in the specified Type, its most
significant bytes are ignored; e.g. NumPut(257, var, 0, "Char") would
store the number 1.
If only three parameters are present, the third parameter can be
either Offset or Type. For example, NumPut(x, var, "int") is valid.
Related~
|NumGet|, |DllCall|, |VarSetCapacity|
==============================================================================
*NumGet*
+--------+~
| NumGet |~
+--------+~
Returns the binary number stored at the specified address+offset.
>
Number := NumGet(VarOrAddress [, Offset = 0][, Type = "UPtr"])
<
Parameters~
VarOrAddress
------------
A memory address or variable. If VarOrAddress is a variable such as
MyVar, the address of the variable's string buffer is used. This is
usually equivalent to passing &MyVar, but omitting the "&" performs
better and ensures that the target address + offset is valid.
Do not pass a variable reference if the variable contains the target
address; in that case, pass an expression such as MyVar+0.
Offset
------
An offset - in bytes - which is added to VarOrAddress to determine the
target address.
Type
-----
One of the following strings (defaults to UPtr if omitted): UInt, Int,
Int64, Short, UShort, Char, UChar, Double, Float, Ptr or UPtr
Unlike |DllCall|, these must be enclosed in quotes when used as
literal strings.
For details see |DllCall_Types|.
Return Value~
If the target address is invalid, an empty string is returned.
However, some invalid addresses cannot be detected as such and may
cause unpredictable behaviour.
Otherwise, the number at the specified address+offset is returned.
General Remarks~
If only two parameters are present, the second parameter can be either
Offset or Type. For example, NumGet(var, "int") is valid.
Related~
|NumPut|, |DllCall|, |VarSetCapacity|
==============================================================================
*Send* *SendRaw* *SendInput* *SendPlay* *SendEvent*
+---------------------------------------------------------------------+~
| Send SendRaw / SendInput / SendPlay / SendEvent: Send Keys & Clicks |~
+---------------------------------------------------------------------+~
Sends simulated keystrokes and mouse clicks to the active window.
>
Send Keys
SendRaw Keys
SendInput Keys
SendPlay Keys
SendEvent Keys
<
Parameters~
Keys
-----
The sequence of keys to send. As with other commands, the comma in
front of the first parameter is optional.
Raw mode: The SendRaw command interprets all characters literally
rather than translating {Enter} to an ENTER keystroke, ^c to
Control-C, etc. However, the normal rules for escape sequences,
variable references and expressions still apply since these are
processed before the command executes. To use raw mode with SendInput,
SendPlay, or SendEvent, write {Raw} as the first item in the string;
for example: SendInput {Raw}abc.
Normal mode:~
When not in raw mode, the following characters are treated as
modifiers (these modifiers affect only the very next key):
!: Sends an ALT keystroke. For example, Send This is text!a would send
the keys "This is text" and then press ALT+a. Note: !A produces a
different effect in some programs than !a. This is because !A presses
ALT+SHIFT+A and !a presses ALT+a. If in doubt, use lowercase.
+: Sends a SHIFT keystroke. For example, Send +abC would send the text
"AbC", and Send !+a would press ALT+SHIFT+a.
^: Sends a CONTROL keystroke. For example, Send ^!a would press
CTRL+ALT+a, and Send ^{Home} would send CONTROL+HOME. Note: ^A
produces a different effect in some programs than ^a. This is because
^A presses CONTROL+SHIFT+A and ^a presses CONTROL+a. If in doubt, use
lowercase.
#: Sends a WIN keystroke, therefore Send #e would hold down the
Windows key and then press the letter "e".
SendInput and SendPlay [v1.0.43+]: SendInput and SendPlay use the same
syntax as Send but are generally faster and more reliable. In
addition, they buffer any physical keyboard or mouse activity during
the send, which prevents the user's keystrokes from being interspersed
with those being sent. SendMode can be used to make Send synonymous
with SendInput or SendPlay. For more details about each mode, see
SendInput and SendPlay below.
SendEvent [v1.0.43+]: SendEvent sends keystrokes using the same method
as the pre-1.0.43 Send command. The rate at which keystrokes are sent
is determined by SetKeyDelay. By default, Send is synonymous
SendEvent; but it can be made a synonym for SendInput or SendPlay via
SendMode.
Key Names: The following table lists the special keys that can be sent
(each key name must be enclosed in braces):
Key Name Resulting Keystroke ~
{F1} - {F24} Function keys. For example: {F12} is the F12 key.
{!} !
{#} #
{+} +
{^} ^
{{} {
{}} }
{Enter} ENTER key on the main keyboard
{Escape} or {Esc} ESCAPE
{Space} SPACE (this is only needed for spaces that
appear either at the beginning or the end of
the string to be sent -- ones in the middle
can be literal spaces)
{Tab} TAB
{Backspace} or {BS} Backspace
{Delete} or {Del} Delete
{Insert} or {Ins} Insert
{Up} Up-arrow key on main keyboard
{Down} Down-arrow down key on main keyboard
{Left} Left-arrow key on main keyboard
{Right} Right-arrow key on main keyboard
{Home} Home key on main keyboard
{End} End key on main keyboard
{PgUp} Page-up key on main keyboard
{PgDn} Page-down key on main keyboard
{CapsLock} CapsLock (using SetCapsLockState is more
reliable on Win 2k/XP). Sending {CapsLock}
might require SetStoreCapslockMode Off
beforehand.
{ScrollLock} ScrollLock (see also: SetScrollLockState)
{NumLock} NumLock (see also: SetNumLockState)
{Control} or {Ctrl} CONTROL (technical info: sends the neutral
virtual key but the left scan code)
{LControl} or {LCtrl} Left CONTROL key (technical info: sends the
left virtual key rather than the neutral one)
{RControl} or {RCtrl} Right CONTROL key
{Control Down} or {Ctrl Down}
Holds the CONTROL key down until {Ctrl Up} is
sent. To hold down the left or right key
instead, use {RCtrl Down} and {RCtrl Up}.
{Alt} ALT (technical info: sends the neutral virtual
key but the left scan code)
{LAlt} Left ALT key (technical info: sends the left
virtual key rather than the neutral one)
{RAlt} Right ALT key (or AltGr, depending on keyboard layout)
{Alt Down} Holds the ALT key down until {Alt Up} is sent.
To hold down the left or right key instead,
use {RAlt Down} and {RAlt Up}.
{Shift} SHIFT (technical info: sends the neutral
virtual key but the left scan code) {LShift}
Left SHIFT key (technical info: sends the left
virtual key rather than the neutral one)
{RShift} Right SHIFT key
{Shift Down} Holds the SHIFT key down until {Shift Up} is
sent. To hold down the left or right key
instead, use {RShift Down} and {RShift Up}.
{LWin} Left Windows key
{RWin} Right Windows key
{LWin Down} Holds the left Windows key down until {LWin
Up} is sent
{RWin Down} Holds the right Windows key down until {RWin
Up} is sent
{AppsKey} Windows App key (invokes the right-click or
context menu)
{Sleep} Computer SLEEP key.
{ASC nnnnn} Sends an ALT+nnnnn keypad combination, which
can be used to generate special characters
that don't exist on the keyboard. To generate
ASCII characters, specify a number between 1
and 255. To generate ANSI characters (standard
in most languages), specify a number between
128 and 255, but precede it with a leading
zero, e.g. {Asc 0133}.
Unicode characters may be generated by specifying a number between 256
and 65535 (without a leading zero). However, this is not supported by
all applications. For alternatives, see the section below.
{U+nnnn} [v1.0.90+]: Sends a Unicode character where nnnn is the
hexadecimal value of the character excluding the 0x prefix. This
typically isn't needed in Unicode versions of AutoHotkey, where Send
and ControlSend automatically support Unicode text.
If the character doesn't map to a virtual keycode, SendInput() or
WM_CHAR is used to send the character and the current Send mode has no
effect.
{vkXX}
{scYYY}
{vkXXscYYY}
Sends a keystroke that has virtual key XX and scan code YYY. For
example: Send {vkFFsc159}. If the sc or vk portion is omitted, the
most appropriate value is sent in its place.
The values for XX and YYY are hexadecimal and can usually be
determined from the main window's View->Key history menu item. See
also: Special Keys
{Numpad0} - {Numpad9} Numpad digit keys (as seen when Numlock is ON).
For example: {Numpad5} is the digit 5. {NumpadDot} Numpad Period (as
seen when Numlock is ON).
{NumpadEnter} Enter key on keypad
{NumpadMult} Numpad Multiply
{NumpadDiv} Numpad Divide
{NumpadAdd} Numpad Add
{NumpadSub} Numpad Subtract
{NumpadDel} Delete key on keypad (this key and the following Numpad
keys are used when Numlock is OFF) {NumpadIns} Insert key on keypad
{NumpadClear} Clear key on keypad (usually the '5' key when Numlock is OFF).
{NumpadUp} Up-arrow key on keypad
{NumpadDown} Down-arrow key on keypad
{NumpadLeft} Left-arrow key on keypad
{NumpadRight} Right-arrow key on keypad
{NumpadHome} Home key on keypad
{NumpadEnd} End key on keypad
{NumpadPgUp} Page-up key on keypad
{NumpadPgDn} Page-down key on keypad
{Browser_Back} Select the browser "back" button
{Browser_Forward} Select the browser "forward" button
{Browser_Refresh} Select the browser "refresh" button
{Browser_Stop} Select the browser "stop" button
{Browser_Search} Select the browser "search" button
{Browser_Favorites} Select the browser "favorites" button
{Browser_Home} Launch the browser and go to the home page
{Volume_Mute} Mute/unmute the master volume. Usually equivalent to SoundSet, +1, , mute.
{Volume_Down} Reduce the master volume. Usually equivalent to SoundSet -5.
{Volume_Up} Increase the master volume. Usually equivalent to SoundSet +5.
{Media_Next} Select next track in media player
{Media_Prev} Select previous track in media player
{Media_Stop} Stop media player
{Media_Play_Pause} Play/pause media player
{Launch_Mail} Launch the email application
{Launch_Media} Launch media player
{Launch_App1} Launch user app1
{Launch_App2} Launch user app2
{PrintScreen} Print Screen
{CtrlBreak} Ctrl+break
{Pause} Pause
{Click [Options]}
[v1.0.43+] Sends a mouse click using the same options available in the
Click command. For example, {Click} would click the left mouse button
once at the mouse cursor's current position, and {Click 100, 200}
would click at coordinates 100, 200 (based on CoordMode). To move the
mouse without clicking, specify 0 after the coordinates; for example:
{Click 100, 200, 0}. The delay between mouse clicks is determined by
SetMouseDelay (not SetKeyDelay). {WheelDown}, {WheelUp}, {WheelLeft},
{WheelRight}, {LButton}, {RButton}, {MButton}, {XButton1}, {XButton2}
Sends a mouse button event at the cursor's current position (to have
control over position and other options, use {Click} above). The delay
between mouse clicks is determined by SetMouseDelay. WheelLeft/Right
require v1.0.48+, but have no effect on operating systems older than
Windows Vista.
{Blind} When {Blind} is the first item in the string, the program
avoids releasing Alt/Control/Shift/Win if they started out in the down
position. For example, the hotkey +s::Send {Blind}abc would send ABC
rather than abc because the user is holding down the Shift key.
{Blind} also causes SetStoreCapslockMode to be ignored; that is, the
state of Capslock is not changed. Finally, {Blind} omits the extra
Control keystrokes that would otherwise be sent; such keystrokes
prevent: 1) Start Menu appearance during LWin/RWin keystrokes; 2) menu
bar activation during Alt keystrokes.
Blind-mode is used internally when remapping a key. For example, the
remapping a::b would produce: 1) "b" when you type "a"; 2) uppercase B
when you type uppercase A; and 3) Control-B when you type Control-A.
{Blind} is not supported by SendRaw and ControlSendRaw. Furthermore,
it is not completely supported by SendPlay, especially when dealing
with the modifier keys (Control, Alt, Shift, and Win).
{Raw}
[v1.0.43+] Sends the keystrokes exactly as they appear rather than
translating {Enter} to an ENTER keystroke, ^c to Control-C, etc.
Although the string {Raw} need not occur at the beginning of the
string, once specified, it stays in effect for the remainder of the
string.
Repeating or Holding Down a Key To repeat a keystroke: Enclose in
braces the name of the key followed by the number of times to repeat
it. For example:
>
Send {DEL 4} ; Presses the Delete key 4 times.
Send {S 30} ; Sends 30 uppercase S characters.
Send +{TAB 4} ; Presses Shift-Tab 4 times. | To hold down or release a key: Enclose in braces the name of the key followed by the word Down or Up. For example:
Send {b down}{b up}
Send {TAB down}{TAB up}
Send {Up down} ; Press down the up-arrow key.
Sleep 1000 ; Keep it down for one second.
Send {Up up} ; Release the up-arrow key. | When a key is held down via the method above, it does not begin auto-repeating like it would if you were physically holding it down (this is because auto-repeat is a driver/hardware feature). However, a Loop can be used to simulate auto-repeat. The following example sends 20 tab keystrokes:
Loop 20
{
Send {Tab down} ; Auto-repeat consists of consecutive down-events (with no up-events).
Sleep 30 ; The number of milliseconds between keystrokes (or use SetKeyDelay).
}
Send {Tab up} ; Release the key
<
The word DownTemp may also be used. Its effect is the same as Down
except for the modifer keys (Control/Shift/Alt/Win). In those cases,
DownTemp tells subsequent sends that the key is not permanently down,
and may be released whenever a keystroke calls for it. For example,
Send {Control DownTemp} followed later by Send a would produce a
normal "a" keystroke, not a control-A keystroke.
General Remarks~
There are no specific limitations on which characters the Send command
supports. If a character does not exist in the current keyboard
layout, it is simulated by sending a Unicode character packet or
Alt+nnnnn combination, depending on the version of AutoHotkey. Unicode
characters are supported directly as text in Unicode versions of
AutoHotkey, or using {U+nnnn} notation in any version.
BlockInput Compared to SendInput/SendPlay: Although the BlockInput
command can be used to prevent any keystrokes physically typed by the
user from disrupting the flow of simulated keystrokes, it is often
better to use SendInput or SendPlay so that keystrokes and mouse
clicks become uninterruptible. This is because unlike BlockInput,
SendInput/Play does not discard what the user types during the send;
instead, such keystrokes are buffered and sent afterward.
When sending a large number of keystrokes, a continuation section can
be used to improve readability and maintainability.
Since the operating system does not allow simulation of the
CTRL-ALT-DELETE combination, doing something like Send ^!{Delete} will
have no effect.
Send may have no effect on Windows Vista or later if the active window
is running with administrative privileges and the script is not. This
is due to a security mechanism called User Interface Privilege
Isolation.
SendInput [v1.0.43+] SendInput is generally the preferred method to
send keystrokes and mouse clicks because of its superior speed and
reliability. Under most conditions, SendInput is nearly instantaneous,
even when sending long strings. Since SendInput is so fast, it is also
more reliable because there is less opportunity for some other window
to pop up unexpectedly and intercept the keystrokes. Reliability is
further improved by the fact that anything the user types during a
SendInput is postponed until afterward.
Unlike the other sending modes, the operating system limits SendInput
to about 5000 characters (this may vary depending on the operating
system's version and performance settings). Characters and events
beyond this limit are not sent.
Note: SendInput ignores SetKeyDelay because the operating system does
not support a delay in this mode. However, when SendInput reverts to
SendEvent under the conditions described below, it uses SetKeyDelay
-1, 0 (unless SendEvent's KeyDelay is -1,-1, in which case -1,-1 is
used). When SendInput reverts to SendPlay, it uses SendPlay's
KeyDelay.
If a script other than the one executing SendInput has a low-level
keyboard hook installed, SendInput automatically reverts to SendEvent
(or SendPlay if SendMode InputThenPlay is in effect). This is done
because the presence of an external hook disables all of SendInput's
advantages, making it inferior to both SendPlay and SendEvent.
However, since SendInput is unable to detect a low-level hook in
programs other than AutoHotkey v1.0.43+, it will not revert in these
cases, making it less reliable than SendPlay/Event.
When SendInput sends mouse clicks by means such as {Click}, and
CoordMode Mouse, Relative is in effect (the default), every click will
be relative to the window that was active at the start of the send.
Therefore, if SendInput intentionally activates another window (by
means such as alt-tab), the coordinates of subsequent clicks within
the same command will be wrong because they will still be relative to
the old window rather than the new one.
SendPlay [v1.0.43+] Note: SendPlay may have no effect at all if UAC is
enabled, even if the script is running as an administrator. For more
information, refer to the FAQ.
SendPlay's biggest advantage is its ability to "play back" keystrokes
and mouse clicks in a broader variety of games than the other modes.
For example, a particular game may accept hotstrings only when they
have the SendPlay option.
Of the three sending modes, SendPlay is the most unusual because it
does not simulate keystrokes and mouse clicks per se. Instead, it
creates a series of events (messages) that flow directly to the active
window (similar to ControlSend, but at a lower level). Consequently,
SendPlay does not trigger hotkeys or hotstrings.
Like SendInput, SendPlay's keystrokes do not get interspersed with
keystrokes typed by the user. Thus, if the user happens to type
something during a SendPlay, those keystrokes are postponed until
afterward.
Although SendPlay is considerably slower than SendInput, it is usually
faster than the traditional SendEvent mode (even when KeyDelay is -1).
The Windows keys (LWin and RWin) are automatically blocked during a
SendPlay if the keyboard hook is installed. This prevents the Start
Menu from appearing if the user accidentally presses a Windows key
during the send. By contrast, keys other than LWin and RWin do not
need to be blocked because the operating system automatically
postpones them until after the SendPlay (via buffering).
SendPlay does not use the standard settings of SetKeyDelay and
SetMouseDelay. Instead, it defaults to no delay at all, which can be
changed as shown in the following examples:
SetKeyDelay, 0, 10, Play ; Note that both 0 and -1 are the same in
SendPlay mode. SetMouseDelay, 10, Play | SendPlay is unable to turn
on or off the Capslock, Numlock, or Scroll-lock keys. Similarly, it is
unable to change a key's state as seen by GetKeyState unless the
keystrokes are sent to one of the script's own windows. Even then, any
changes to the left/right modifier keys (e.g. RControl) can be
detected only via their neutral counterparts (e.g. Control). Also,
SendPlay has other limitations described on the SendMode page.
Unlike SendInput and SendEvent, the user may interrupt a SendPlay by
pressing Control-Alt-Del or Control-Escape. When this happens, the
remaining keystrokes are not sent but the script continues executing
as though the SendPlay had completed normally.
Although SendPlay can send LWin and RWin events, they are sent
directly to the active window rather than performing their native
operating system function. To work around this, use SendEvent. For
example, SendEvent #r would show the Start Menu's Run dialog.
Related~
SendMode, SetKeyDelay, SetStoreCapslockMode, Escape sequences (e.g.
`%), ControlSend, BlockInput, Hotstrings, |WinActivate|
Examples~
>
Send Sincerely,{enter}John Smith ; Types a two-line signature.
Send !fs ; Select the File->Save menu (Alt+F followed by S).
Send {End}+{Left 4} ; Jump to the end of the text then send four shift+left-arrow keystrokes.
SendInput {Raw}A long series of raw characters sent via the fastest method (SendInput).
<
==============================================================================
*MouseGetPos*
+-------------+~
| MouseGetPos |~
+-------------+~
Retrieves the current position of the mouse cursor, and optionally
which window and control it is hovering over.
>
MouseGetPos, [OutputVarX, OutputVarY, OutputVarWin, OutputVarControl, 1|2|3]
<
Parameters~
OutputVarX/Y
------------
The names of the variables in which to store the X and Y coordinates.
The retrieved coordinates are relative to the active window unless
CoordMode was used to change to screen coordinates.
OutputVarWin
------------
This optional parameter is the name of the variable in which to store
the unique ID number of the window under the mouse cursor. If the
window cannot be determined, this variable will be made blank.
The window does not have to be active to be detected. Hidden windows
cannot be detected.
OutputVarControl
----------------
This optional parameter is the name of the variable in which to store
the name (ClassNN) of the control under the mouse cursor. If the
control cannot be determined, this variable will be made blank.
The names of controls should always match those shown by the version
of Window Spy distributed with v1.0.14+ (but not necessarily older
versions of Window Spy). However, unlike Window Spy, the window under
the mouse cursor does not have to be active for a control to be
detected.
1|2|3
-----
If omitted, it defaults to 0. Otherwise, specify one of the following
digits:
1: Uses a simpler method to determine OutputVarControl. This method
correctly retrieves the active/topmost child window of an Multiple
Document Interface (MDI) application such as SysEdit or TextPad.
However, it is less accurate for other purposes such as detecting
controls inside a GroupBox control.
2 [v1.0.43.06+]: Stores the control's HWND in OutputVarControl rather
than the control's ClassNN.
3 [v1.0.43.06+]: A combination of 1 and 2 above.
Remarks~
Any of the output variables may be omitted if the corresponding
information is not needed.
Related~
|CoordMode|, |WinGet|, |SetDefaultMouseSpeed|, |Click|
Example~
>
MouseGetPos, xpos, ypos
Msgbox, The cursor is at X%xpos% Y%ypos%.
; This example allows you to move the mouse around to see
; the title of the window currently under the cursor:
#Persistent
SetTimer, WatchCursor, 100
return
WatchCursor:
MouseGetPos, , , id, control
WinGetTitle, title, ahk_id %id%
WinGetClass, class, ahk_id %id%
ToolTip, ahk_id %id%`nahk_class %class%`n%title%`nControl: %control%
return
<
==============================================================================
*MouseClick*
+------------+~
| 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.
>
MouseClick [, WhichButton , X, Y, ClickCount, Speed, D|U, R]
<
Parameters~
WhichButton~
The button to click: Left (default), Right, Middle (or just the first
letter of each of these); or the fourth or fifth mouse button (X1 or
X2). For example: MouseClick, X1. This parameter may be omitted, in
which case it defaults to Left.
Rotate the mouse wheel: Specify WheelUp or WU to turn the wheel upward
(away from you); specify WheelDown or WD to turn the wheel downward
(toward you). In v1.0.48+, specify WheelLeft (or WL) or WheelRight (or
WR) to push the wheel left or right, respectively (but these have no
effect on operating systems older than Windows Vista). ClickCount is
the number of notches to turn the wheel.
To compensate automatically for cases where the user has swapped the
left and right mouse buttons via the system's control panel, use the
Click command instead.
X, Y~
The x/y coordinates to which the mouse cursor is moved prior to
clicking, which can be expressions. Coordinates are relative to the
active window unless CoordMode was used to change that. If omitted,
the cursor's current position is used.
ClickCount
----------
The number of times to click the mouse, which can be an expression. If omitted, the button is clicked once.
Speed
-----
The speed to move the mouse in the range 0 (fastest) to 100 (slowest),
which can be an expression. Note: a speed of 0 will move the mouse
instantly. If omitted, the default speed (as set by
SetDefaultMouseSpeed or 2 otherwise) will be used.
Speed is ignored for SendInput/Play modes; they move the mouse
instantaneously (though SetMouseDelay has a mode that applies to
SendPlay). To visually move the mouse more slowly -- such as a script
that performs a demonstration for an audience -- use SendEvent {Click
100, 200} or SendMode Event (optionally in conjuction with
BlockInput).
D|U
-----
If this parameter is omitted, each click will consist of a "down"
event followed by an "up" event. Alternatively:
D = Press the mouse button down but do not release it (i.e. generate a
down-event).
U = Release the mouse button (i.e. generate an up-event).
R
If this parameter is the letter R, the X and Y coordinates will be
treated as offsets from the current mouse position. In other words,
the cursor will be moved from its current position by X pixels to the
right (left if negative) and Y pixels down (up if negative).
Remarks~
This command uses the sending method set by SendMode.
The Click command is recommended over MouseClick because:
1.It automatically compensates when the left and right mouse buttons
are swapped via the control panel.
2.It is generally easier to use. To perform a shift-click or
control-click, use the Send command before and after the operation as
shown in these examples:
>
; Example #1:
Send, {Control down}
MouseClick, left, 55, 233
Send, {Control up} | ; Example #2:
Send, {Shift down}
MouseClick, left, 55, 233
Send, {Shift up} | The SendPlay mode is able to successfully generate mouse events in a broader variety of games than the other modes. In addition, some applications and games may have trouble tracking the mouse if it moves too quickly. The speed parameter or SetDefaultMouseSpeed can be used to reduce the speed (in the default SendEvent mode only).
Some applications do not obey a ClickCount higher than 1 for the mouse wheel. For them, use a Loop such as the following:
Loop, 5
MouseClick, WheelUp | The BlockInput command can be used to prevent any physical mouse activity by the user from disrupting the simulated mouse events produced by the mouse commands. However, this is generally not needed for the SendInput/Play modes because they automatically postpone the user's physical mouse activity until afterward.
There is an automatic delay after every click-down and click-up of the mouse (except for SendInput mode and for turning the mouse wheel). Use SetMouseDelay to change the length of the delay.
<
Related~
CoordMode, SendMode, SetDefaultMouseSpeed, SetMouseDelay, Click,
MouseClickDrag, MouseGetPos, MouseMove, ControlClick, BlockInput
Examples~
>
; Double click at the current mouse pos:
MouseClick, left
MouseClick, left
; Same as above:
MouseClick, left, , , 2
; Move to specified coordinates then right-click once:
MouseClick, right, 200, 300
; Here are two hotkeys that simulate the turning of the mouse wheel:
#up::MouseClick, WheelUp, , , 2 ; Turn it by two notches.
#down::MouseClick, WheelDown, , , 2
<
==============================================================================
*BlockInput*
+------------+~
| BlockInput |~
+------------+~
Disables or enables the user's ability to interact with the computer
via keyboard and mouse.
>
BlockInput, Mode
<
Parameters~
Mode
-----
Mode 1: One of the following words:
On: The user is prevented from interacting with the computer (mouse
and keyboard input has no effect).
Off: Input is re-enabled.
Mode 2: This mode operates independently of the other two. For
example, BlockInput On will continue to block input until BlockInput
Off is used, even if one of the below is also in effect.
Send: The user's keyboard and mouse input is ignored while a Send or
SendRaw is in progress (the traditional SendEvent mode only). This
prevents the user's keystrokes from disrupting the flow of simulated
keystrokes. When the Send finishes, input is re-enabled (unless still
blocked by a previous use of BlockInput On).
Mouse: The user's keyboard and mouse input is ignored while a Click,
MouseMove, MouseClick, or MouseClickDrag is in progress (the
traditional SendEvent mode only). This prevents the user's mouse
movements and clicks from disrupting the simulated mouse events. When
the mouse command finishes, input is re-enabled (unless still blocked
by a previous use of BlockInput On).
SendAndMouse: A combination of the above two modes.
Default~
Turns off both the Send and the Mouse modes, but does not change the
current state of input blocking. For example, if BlockInput On is
currently in effect, using BlockInput Default will not turn it off.
Mode 3 (requires v1.0.43.11+): This mode operates independently of the
other two. For example, if BlockInput On and BlockInput MouseMove are
both in effect, mouse movement will be blocked until both are turned
off.
MouseMove~
The mouse cursor will not move in response to the user's physical movement of the mouse (DirectInput applications are a possible exception). When a script first uses this command, the mouse hook is installed (if it is not already). In addition, the script becomes persistent, meaning that ExitApp should be used to terminate it. The mouse hook will stay installed until the next use of the Suspend or Hotkey command, at which time it is removed if not required by any hotkeys or hotstrings (see #Hotstring NoMouse).
MouseMoveOff: Allows the user to move the mouse cursor.
Remarks~
Note: BlockInput On might have no effect if UAC is enabled and the
script has not been run as administrator. For more information, refer
to the FAQ.
In preference to BlockInput, it is often better to use SendMode Input
or SendMode Play so that keystrokes and mouse clicks become
uninterruptible. This is because unlike BlockInput, those modes do not
discard what the user types during the send; instead, those keystrokes
are buffered and sent afterward. Avoiding BlockInput also avoids the
need to work around sticking keys as described in the next paragraph.
If BlockInput becomes active while the user is holding down keys, it
might cause those keys to become "stuck down". This can be avoided by
waiting for the keys to be released prior to turning BlockInput on, as
in this example:
>
^!p::
KeyWait Control ; Wait for the key to be released. Use one KeyWait for each of the hotkey's modifiers.
KeyWait Alt
BlockInput On
; ... send keystrokes and mouse clicks ...
BlockInput Off
return | Input blocking is automatically and momentarily disabled whenever an ALT event is sent (then re-enabled afterward).
<
When BlockInput is in effect, user input is blocked but AutoHotkey can
simulate keystrokes and mouse clicks. However, pressing Ctrl+Alt+Del
will re-enable input due to a Windows API feature.
Certain types of hook hotkeys can still be triggered when BlockInput
is on. Examples include MButton (mouse hook) and LWin & Space
(keyboard hook with explicit prefix rather than modifiers $#).
Input is automatically re-enabled when the script closes.
Related~
|SendMode|, |Send|, |Click|, |MouseMove|, |MouseClick|, |MouseClickDrag|
Example~
>
BlockInput, on
Run, notepad
WinWaitActive, Untitled - Notepad
Send, {F5} ; pastes time and date
BlockInput, off
==============================================================================
*MouseClickDrag*
+----------------+~
| MouseClickDrag |~
+----------------+~
Clicks and holds the specified mouse button, moves the mouse to the
destination coordinates, then releases the button.
>
MouseClickDrag, WhichButton, X1, Y1, X2, Y2 [, Speed, R]
<
Parameters~
WhichButton
-----------
The button to click: Left, Right, Middle (or just the first letter of
each of these). Specify X1 for the fourth button and X2 for the fifth.
For example: MouseClickDrag, X1, ....
To compensate automatically for cases where the user has swapped the
left and right mouse buttons via the system's control panel, use the
Click command instead.
X1, Y1
------
The x/y coordinates of the drag's starting position, which can be expressions (the mouse will be moved to these coordinates right before the drag is started). Coordinates are relative to the active window unless CoordMode was used to change that. If omitted, the mouse's current position is used.
X2, Y2
------
The x/y coordinates to drag the mouse to (that is, while the button is held down), which can be expressions. Coordinates are relative to the active window unless CoordMode was used to change that.
Speed
-----
The speed to move the mouse in the range 0 (fastest) to 100 (slowest),
which can be an expression. Note: a speed of 0 will move the mouse
instantly. If omitted, the default speed (as set by
SetDefaultMouseSpeed or 2 otherwise) will be used.
Speed is ignored for SendInput/Play modes; they move the mouse
instantaneously (though SetMouseDelay has a mode that applies to
SendPlay). To visually move the mouse more slowly -- such as a script
that performs a demonstration for an audience -- use SendEvent {Click
100, 200} or SendMode Event (optionally in conjuction with
BlockInput).
R
If this parameter is the letter R, the X1 and Y1 coordinates will be
treated as offsets from the current mouse position. In other words,
the cursor will be moved from its current position by X1 pixels to the
right (left if negative) and Y1 pixels down (up if negative).
Similarly, the X2 and Y2 coordinates will be treated as offsets from
the X1 and Y1 coordinates. For example, the following would first move
the cursor down and to the right by 5 pixels from its starting
position, and then drag it from that position down and to the right by
10 pixels: MouseClickDrag, Left, 5, 5, 10, 10, , R.
Remarks~
This command uses the sending method set by SendMode.
Dragging can also be done via the various Send commands, which is more
flexible because the mode can be specified via the command name. For
example:
SendEvent {Click 6, 52, down}{click 45, 52, up} | Another advantage of
the method above is that unlike MouseClickDrag, it automatically
compensates when the user has swapped the left and right mouse buttons
via the system's control panel.
The SendPlay mode is able to successfully generate mouse events in a
broader variety of games than the other modes. However, dragging via
SendPlay might not work in RichEdit controls (and possibly others)
such as those of WordPad and Metapad.
Some applications and games may have trouble tracking the mouse if it
moves too quickly. The speed parameter or SetDefaultMouseSpeed can be
used to reduce the speed (in the default SendEvent mode only).
The BlockInput command can be used to prevent any physical mouse
activity by the user from disrupting the simulated mouse events
produced by the mouse commands. However, this is generally not needed
for the SendInput/Play modes because they automatically postpone the
user's physical mouse activity until afterward.
There is an automatic delay after every click-down and click-up of the
mouse (except for SendInput mode). This delay also occurs after the
movement of the mouse during the drag operation. Use SetMouseDelay to
change the length of the delay.
Related~
|CoordMode|, |SendMode|, |SetDefaultMouseSpeed|, |SetMouseDelay|,
|Click|, |MouseClick|, |MouseGetPos|, |MouseMove|, |BlockInput|
Example~
>
MouseClickDrag, left, 0, 200, 600, 400
; The following example opens MS Paint and draws a little house:
Run, mspaint.exe
WinWaitActive, ahk_class MSPaintApp,, 2
if ErrorLevel
return
MouseClickDrag, L, 150, 250, 150, 150
MouseClickDrag, L, 150, 150, 200, 100
MouseClickDrag, L, 200, 100, 250, 150
MouseClickDrag, L, 250, 150, 150, 150
MouseClickDrag, L, 150, 150, 250, 250
MouseClickDrag, L, 250, 250, 250, 150
MouseClickDrag, L, 250, 150, 150, 250
MouseClickDrag, L, 150, 250, 250, 250
<
==============================================================================
*SetMouseDelay*
+---------------+~
| SetMouseDelay |~
+---------------+~
Sets the delay that will occur after each mouse movement or click.
>
SetMouseDelay, Delay [, Play]
<
Parameters~
Delay
-----
Time in milliseconds, which can be an expression. Use -1 for no delay
at all and 0 for the smallest possible delay (however, if the Play
parameter is present, both 0 and -1 produce no delay). If unset, the
default delay is 10 for the traditional SendEvent mode and -1 for
SendPlay mode.
Play
-----
[v1.0.43+]
The word Play applies the delay to the SendPlay mode rather than the
traditional Send/SendEvent mode. If a script never uses this
parameter, the delay is always -1 for SendPlay.
Remarks~
A short delay (sleep) is done automatically after every mouse movement
or click generated by Click and MouseMove/Click/Drag (except for
SendInput mode). This is done to improve the reliability of scripts
because a window sometimes can't keep up with a rapid flood of mouse
events.
Due to the granularity of the OS's time-keeping system, delays might
be rounded up to the nearest multiple of 10 or 15. For example, a
delay between 1 and 10 (inclusive) is equivalent to 10 or 15 on most
Windows XP systems (and probably 2k).
A delay of 0 internally executes a Sleep(0), which yields the
remainder of the script's timeslice to any other process that may need
it. If there is none, Sleep(0) will not sleep at all. By contrast, a
delay of -1 will never sleep.
The built-in variable A_MouseDelay contains the current setting for
Send/SendEvent mode. [v1.1.23+]: A_MouseDelayPlay contains the current
setting for SendPlay mode.
Every newly launched thread (such as a hotkey, custom menu item, or
timed subroutine) starts off fresh with the default setting for this
command. That default may be changed by using this command in the
auto-execute section (top part of the script).
Related~
|SetDefaultMouseSpeed|, |Click|, |MouseMove|, |MouseClick|,
|MouseClickDrag|, |SendMode|, |SetKeyDelay|, |SetControlDelay|,
|SetWinDelay|, |SetBatchLines|
Example~
>
SetMouseDelay, 0
<
==============================================================================
*SetDefaultMouseSpeed*
+----------------------+~
| SetDefaultMouseSpeed |~
+----------------------+~
Sets the mouse speed that will be used if unspecified in Click and
MouseMove/Click/Drag.
>
SetDefaultMouseSpeed, Speed
<
Parameters~
Speed
-----
The speed to move the mouse in the range 0 (fastest) to 100 (slowest).
Note: a speed of 0 will move the mouse instantly. This parameter can
be an expression.
Remarks~
SetDefaultMouseSpeed is ignored for SendInput/Play modes; they move
the mouse instantaneously (however, SetMouseDelay has a mode that
applies to SendPlay). To visually move the mouse more slowly -- such
as a script that performs a demonstration for an audience -- use
SendEvent {Click 100, 200} or SendMode Event (optionally in conjuction
with BlockInput).
If this command is not used, the default mouse speed is 2. The
built-in variable A_DefaultMouseSpeed contains the current setting.
The commands MouseClick, MouseMove, and MouseClickDrag all have a
parameter to override the default mouse speed.
Whenever Speed is greater than zero, SetMouseDelay also influences the
speed by producing a delay after each incremental move the mouse makes
toward its destination.
Every newly launched thread (such as a hotkey, custom menu item, or
timed subroutine) starts off fresh with the default setting for this
command. That default may be changed by using this command in the
auto-execute section (top part of the script).
Related~
|SetMouseDelay|, |SendMode|, |Click|, |MouseClick|, |MouseMove|,
|MouseClickDrag|, |SetWinDelay|, |SetControlDelay|, |SetKeyDelay|,
|SetKeyDelay|
Example~
>
SetDefaultMouseSpeed, 0 ; Move the mouse instantly.
<
==============================================================================
*SendMode*
+----------+~
| SendMode |~
+----------+~
Makes Send synonymous with SendInput or SendPlay rather than the
default (SendEvent). Also makes Click and MouseMove/Click/Drag use the
specified method.
>
SendMode Input|Play|Event|InputThenPlay
<
The first parameter is one of the following words:
Event
-----
This is the starting default used by all scripts. It uses the
SendEvent method for Send, SendRaw, Click, and MouseMove/Click/Drag.
Input
-----
Switches to the SendInput method for Send, SendRaw, Click, and
MouseMove/Click/Drag. Known limitations:
•Windows Explorer ignores SendInput's simulation of certain
navigational hotkeys such as Alt+LeftArrow. To work around this, use
either SendEvent !{Left} or SendInput {Backspace}.
InputThenPlay [v1.0.43.02+]: Same as above except that rather than
falling back to Event mode when SendInput is unavailable, it reverts
to Play mode (below). This also causes the SendInput command itself to
revert to Play mode when SendInput is unavailable.
Play
-----
Switches to the SendPlay method for Send, SendRaw, Click, and MouseMove/Click/Drag.
Known limitations:
•Characters that do not exist in the current keyboard layout (such as
Ô in English) cannot be sent. To work around this, use SendEvent.
•Simulated mouse dragging might have no effect in RichEdit controls
(and possibly others) such as those of WordPad and Metapad. To use an
alternate mode for a particular drag, follow this example: SendEvent
{Click 6, 52, down}{Click 45, 52, up}.
•Simulated mouse wheel rotation produces movement in only one
direction (usually downward, but upward in some applications). Also,
wheel rotation might have no effect in applications such as MS Word
and Notepad. To use an alternate mode for a particular rotation,
follow this example: SendEvent {WheelDown 5}.
•When using SendMode Play in the auto-execute section (top part of the
script), all remapped keys are affected and might lose some of their
functionality. See SendPlay remapping limitations for details.
•SendPlay does not trigger AutoHotkey's hotkeys or hotstrings, or
global hotkeys registered by other programs or the OS.
Remarks~
Since SendMode also changes the mode of Click and
MouseMove/Click/Drag, there may be times when you wish to use a
different mode for a particular mouse event. The easiest way to do
this is via {Click}. For example:
SendEvent {Click 100, 200} ; SendEvent uses the older, traditional
method of clicking. | If SendMode is used in the auto-execute section
(top part of the script), it also affects keyboard and mouse
remapping. In particular, if you use SendMode Play with remapping, see
SendPlay remapping limitations.
[v1.1.23+]: The built-in variable A_SendMode contains the current setting.
Every newly launched thread (such as a hotkey, custom menu item, or
timed subroutine) starts off fresh with the default setting for this
command. That default may be changed by using this command in the
auto-execute section (top part of the script).
Related~
|Send|, |SetKeyDelay|, |SetMouseDelay|, |Click|, |MouseClick|,
|MouseClickDrag|, |MouseMove|
Examples~
>
SendMode Input
SendMode InputThenPlay
==============================================================================
*Include* *IncludeAgain*
+------------------------+~
| Include / IncludeAgain |~
+------------------------+~
Causes the script to behave as though the specified file's contents
are present at this exact position.
>
#Include FileOrDirName
#Include
#IncludeAgain FileOrDirName
<
Parameters~
FileOrDirName
-------------
The path of a file or directory as explained below. This must not
contain double quotes, wildcards, or variable references except
%A_ScriptDir%, %A_AppData%, %A_AppDataCommon% and (in v1.1.11+)
%A_LineFile%. Escape sequences other than semicolon (`;) must not be
used, nor are they needed because characters such as percent signs are
treated literally.
File: The name of the file to be included, which is assumed to be in
the startup/working directory if an absolute path is not specified
(except for ahk2exe, which assumes the file is in the script's own
directory). Note: SetWorkingDir has no effect on #Include because
#Include is processed before the script begins executing.
Directory: Specify a directory instead of a file to change the working
directory used by all subsequent occurrences of #Include and
FileInstall. Note: Changing the working directory in this way does not
affect the script's initial working directory when it starts running
(A_WorkingDir). To change that, use SetWorkingDir at the top of the
script.
LibName
-------
[v1.0.90+]: A library file or function name. For example, #include
and #include would both include lib.ahk from one of
the function library folders.
Remarks~
A script behaves as though the included file's contents are physically
present at the exact position of the #Include directive (as though a
copy-and-paste were done from the included file). Consequently, it
generally cannot merge two isolated scripts together into one
functioning script (to achieve that, see
www.autohotkey.com/forum/topic18545.html).
#Include ensures that FileName is included only once, even if multiple
inclusions are encountered for it. By contrast, #IncludeAgain allows
multiple inclusions of the same file, while being the same as #Include
in all other respects.
The FileName parameter may optionally be preceded by *i and a single
space, which causes the program to ignore any failure to read the
included file. For example: #Include *i SpecialOptions.ahk. This
option should be used only when the included file's contents are not
essential to the main script's operation.
Lines displayed in the main window via ListLines or the menu
View->Lines are always numbered according to their physical order
within their own files. In other words, including a new file will
change the line numbering of the main script file by only one line,
namely that of the #Include line itself (except for compiled scripts,
which merge their included files into one big script at the time of
compilation).
#Include is often used to load functions defined in an external file.
Unlike subroutine labels, functions can be included at the very top of
the script without affecting the auto-execute section.
Like other # directives, #Include cannot be executed conditionally. In
other words, this example would not work:
>
if x = 1
#Include SomeFile.ahk ; This line takes effect regardless of the value of x.
y = 2 ; And this line would belong to the IF above, since # directives cannot belong to IFs.
<
Files can be automatically included (i.e. without having to use
#Include) by calling a library function by name.
[v1.1.11+]: Use %A_LineFile%\.. to refer to the directory which
contains the current file, even if it is not the main script file. For
example, #Include %A_LineFile%\..\other.ahk.
Related~
|libraries_of_functions|,
|introductions_to_functions_and_simple_examples|, |FileInstall|
Example~
>
#Include C:\My Documents\Scripts\Utility Subroutines.ahk
#Include %A_ScriptDir% ; Changes the working directory for subsequent #Includes and FileInstalls.
#Include C:\My Scripts ; Same as above but for an explicitly named directory.
==============================================================================
*FileInstall*
+-------------+~
| FileInstall |~
+-------------+~
Includes the specified file inside the compiled version of the script.
>
FileInstall, Source, Dest [, Flag]
<
Parameters~
Source
------
The name of the file to be added to the compiled EXE. The file is
assumed to be in (or relative to) the script's own directory if an
absolute path isn't specified.
The file name must not contain double quotes, variable references
(e.g. %A_ProgramFiles%), or wildcards. In addition, any special
characters such as literal percent signs and commas must be escaped
(just like in the parameters of all other commands). Finally, this
parameter must be listed to the right of the FileInstall command (that
is, not on a continuation line beneath it).
Dest
-----
When Source is extracted from the EXE, this is the name of the file to
be created. It is assumed to be in %A_WorkingDir% if an absolute path
isn't specified. The destination directory must already exist. Unlike
Source, variable references may be used.
Flag
-----
(optional) this flag determines whether to overwrite files if they
already exist:
0 = (default) do not overwrite existing files
1 = overwrite existing files
This parameter can be an expression, even one that evalutes to true or
false (since true and false are stored internally as 1 and 0).
ErrorLevel~
[v1.1.04+] This command is able to throw an exception on failure. For
more information, see Runtime Errors.
ErrorLevel is set to 1 if there was a problem or 0 otherwise.
Remarks~
This command is a directive for the Ahk2Exe compiler that allows you
to add extra files to the resulting compiled script. Later, when the
compiled script is run, the files are extracted back out onto the
disk.
The file is added during script compilation. When the compiled script
is executed and the same "FileInstall" command is reached, the file is
then extracted to Dest.
Files added to a script are compressed and also encrypted.
If this command is used in an normal (uncompiled) script, a simple
file copy will be performed instead -- this helps the testing of
scripts that will eventually be compiled.
Related~
|FileCopy|, |#Include|
Example~
>
FileInstall, C:\My Documents\My File.txt, %A_ProgramFiles%\My Application\Readme.txt, 1
<
==============================================================================
*FileCopy*
+----------+~
| FileCopy |~
+----------+~
Copies one or more files.
>
FileCopy, SourcePattern, DestPattern [, Flag]
<
Parameters~
SourcePattern
-------------
The name of a single file or folder, or a wildcard pattern such as
C:\Temp\*.tmp. SourcePattern is assumed to be in %A_WorkingDir% if an
absolute path isn't specified.
DestPatternThe name or pattern of the destination, which is assumed to
be in %A_WorkingDir% if an absolute path isn't specified. To perform a
simple copy -- retaining the existing file name(s) -- specify only the
folder name as shown in these functionally identical examples:
FileCopy, C:\*.txt, C:\My Folder
>
FileCopy, C:\*.txt, C:\My Folder\*.*
<
Flag
-----
(optional) this flag determines whether to overwrite files if they
already exist:
0 = (default) do not overwrite existing files
1 = overwrite existing files
This parameter can be an expression, even one that evalutes to true or
false (since true and false are stored internally as 1 and 0).
ErrorLevel
----------
[v1.1.04+] This command is able to throw an exception on failure. For
more information, see Runtime Errors.
ErrorLevel is set to the number of files that could not be copied due
to an error, or 0 otherwise.
In either case, if the source file is a single file (no wildcards) and
it does not exist, ErrorLevel is set to 0. To detect this condition,
use IfExist or FileExist() on the source file prior to copying it.
Unlike FileMove, copying a file onto itself is always counted as an
error, even if the overwrite mode is in effect.
If files were found, A_LastError is set to 0 (zero) or the result of
the operating system's GetLastError() function immediately after the
last failure. Otherwise A_LastError contains an error code that might
indicate why no files were found.
Remarks~
FileCopy copies files only. To instead copy the contents of a folder
(all its files and subfolders), see the examples section below. To
copy a single folder (including its subfolders), use FileCopyDir.
The operation will continue even if error(s) are encountered.
Related~
|FileMove|, |FileCopyDir|, |FileMoveDir|, |FileDelete|
Examples~
>
FileCopy, C:\My Documents\List1.txt, D:\Main Backup\ ; Make a copy but keep the orig. file name.
FileCopy, C:\My File.txt, C:\My File New.txt ; Copy a file into the same folder by providing a new name.
FileCopy, C:\Folder1\*.txt, D:\New Folder\*.bkp ; Copy to new location and give new extension.
; The following example copies all files and folders inside a folder to a different folder:
ErrorCount := CopyFilesAndFolders("C:\My Folder\*.*", "D:\Folder to receive all files & folders")
if ErrorCount <> 0
MsgBox %ErrorCount% files/folders could not be copied.
CopyFilesAndFolders(SourcePattern, DestinationFolder, DoOverwrite = false)
; Copies all files and folders matching SourcePattern into the folder named DestinationFolder and
; returns the number of files/folders that could not be copied.
{
; First copy all the files (but not the folders):
FileCopy, %SourcePattern%, %DestinationFolder%, %DoOverwrite%
ErrorCount := ErrorLevel
; Now copy all the folders:
Loop, %SourcePattern%, 2 ; 2 means "retrieve folders only".
{
FileCopyDir, %A_LoopFileFullPath%, %DestinationFolder%\%A_LoopFileName%, %DoOverwrite%
ErrorCount += ErrorLevel
if ErrorLevel ; Report each problem folder by name.
MsgBox Could not copy %A_LoopFileFullPath% into %DestinationFolder%.
}
return ErrorCount
}
==============================================================================
*FileMove*
+----------+~
| FileMove |~
+----------+~
Moves or renames one or more files.
>
FileMove, SourcePattern, DestPattern [, Flag]
<
Parameters~
SourcePattern
-------------
The name of a single file or a wildcard pattern such as C:\Temp\*.tmp.
SourcePattern is assumed to be in %A_WorkingDir% if an absolute path
isn't specified.
DestPattern
-----------
The name or pattern of the destination, which is assumed to be in
%A_WorkingDir% if an absolute path isn't specified. To perform a
simple move -- retaining the existing file name(s) -- specify only the
folder name as shown in these functionally identical examples:
>
FileMove, C:\*.txt, C:\My Folder
FileMove, C:\*.txt, C:\My Folder\*.*
<
Flag
-----
(optional) this flag determines whether to overwrite files if they
already exist:
0 = (default) do not overwrite existing files
1 = overwrite existing files
This parameter can be an expression, even one that evalutes to true or
false (since true and false are stored internally as 1 and 0).
ErrorLevel
----------
[v1.1.04+] This command is able to throw an exception on failure. For
more information, see Runtime Errors.
ErrorLevel is set to the number of files that could not be moved due
to an error, or 0 otherwise. However, if the source file is a single
file (no wildcards) and it does not exist, ErrorLevel is set to 0. To
detect this condition, use IfExist or FileExist() on the source file
prior to moving it.
Unlike FileCopy, moving a file onto itself is always considered
successful, even if the overwrite mode is not in effect.
If files were found, A_LastError is set to 0 (zero) or the result of
the operating system's GetLastError() function immediately after the
last failure. Otherwise A_LastError contains an error code that might
indicate why no files were found.
Remarks~
FileMove moves files only. To instead move the contents of a folder
(all its files and subfolders), see the examples section below. To
move or rename a single folder, use FileMoveDir.
The operation will continue even if error(s) are encountered.
Although this command is capable of moving files to a different
volume, the operation will take longer than a same-volume move. This
is because a same-volume move is similar to a rename, and therefore
much faster.
Related~
|FileCopy|, |FileCopyDir|, |FileMoveDir|, |FileDelete|
Examples~
>
FileMove, C:\My Documents\List1.txt, D:\Main Backup\ ; Move the file without renaming it.
FileMove, C:\File Before.txt, C:\File After.txt ; Rename a single file.
FileMove, C:\Folder1\*.txt, D:\New Folder\*.bkp ; Move and rename files to a new extension.
; The following example moves all files and folders inside a folder to a different folder:
ErrorCount := MoveFilesAndFolders("C:\My Folder\*.*", "D:\Folder to receive all files & folders")
if ErrorCount <> 0
MsgBox %ErrorCount% files/folders could not be moved.
MoveFilesAndFolders(SourcePattern, DestinationFolder, DoOverwrite = false)
; Moves all files and folders matching SourcePattern into the folder named DestinationFolder and
; returns the number of files/folders that could not be moved. This function requires v1.0.38+
; because it uses FileMoveDir's mode 2.
{
if DoOverwrite = 1
DoOverwrite = 2 ; See FileMoveDir for description of mode 2 vs. 1.
; First move all the files (but not the folders):
FileMove, %SourcePattern%, %DestinationFolder%, %DoOverwrite%
ErrorCount := ErrorLevel
; Now move all the folders:
Loop, %SourcePattern%, 2 ; 2 means "retrieve folders only".
{
FileMoveDir, %A_LoopFileFullPath%, %DestinationFolder%\%A_LoopFileName%, %DoOverwrite%
ErrorCount += ErrorLevel
if ErrorLevel ; Report each problem folder by name.
MsgBox Could not move %A_LoopFileFullPath% into %DestinationFolder%.
}
return ErrorCount
}
<
==============================================================================
*FileCopyDir*
+-------------+~
| FileCopyDir |~
+-------------+~
Copies a folder along with all its sub-folders and files (similar to
xcopy).
>
FileCopyDir, Source, Dest [, Flag]
<
Parameters~
Source
------
Name of the source directory (with no trailing backslash), which is
assumed to be in %A_WorkingDir% if an absolute path isn't specified.
For example: C:\My Folder
Dest
-----
Name of the destination directory (with no trailing baskslash), which
is assumed to be in %A_WorkingDir% if an absolute path isn't
specified. For example: C:\Copy of My Folder
Flag
-----
(optional) this flag determines whether to overwrite files if they
already exist:
0 (default): Do not overwrite existing files. The operation will fail
and have no effect if Dest already exists as a file or directory.
1: Overwrite existing files. However, any files or subfolders inside
Dest that do not have a counterpart in Source will not be deleted.
This parameter can be an expression, even one that evalutes to true or
false (since true and false are stored internally as 1 and 0).
ErrorLevel
----------
[v1.1.04+] This command is able to throw an exception on failure. For
more information, see Runtime Errors.
ErrorLevel is set to 1 if there was a problem or 0 otherwise. However,
if the source directory contains any saved webpages consisting of a
PageName.htm file and a corresponding directory named PageName_files,
an error may be indicated even when the copy is successful.
Remarks~
If the destination directory structure doesn't exist it will be
created if possible.
Since the operation will recursively copy a folder along with all its
subfolders and files, the result of copying a folder to a destination
somewhere inside itself is undefined. To work around this, first copy
it to a destination outside itself, then use FileMoveDir to move that
copy to the desired location.
FileCopyDir copies a single folder. To instead copy the contents of a
folder (all its files and subfolders), see the examples section of
FileCopy.
Related~
|FileMoveDir|, |FileCopy|, |FileMove|, |FileDelete|, |file-loops|,
|FileSelectFolder|, |SplitPath|
Examples~
>
FileCopyDir, C:\My Folder, C:\Copy of My Folder
; Example #2: A working script that prompts you to copy a folder.
FileSelectFolder, SourceFolder, , 3, Select the folder to copy
if SourceFolder =
return
; Otherwise, continue.
FileSelectFolder, TargetFolder, , 3, Select the folder IN WHICH to create the duplicate folder.
if TargetFolder =
return
; Otherwise, continue.
MsgBox, 4, , A copy of the folder "%SourceFolder%" will be put into "%TargetFolder%". Continue?
IfMsgBox, No
return
SplitPath, SourceFolder, SourceFolderName ; Extract only the folder name from its full path.
FileCopyDir, %SourceFolder%, %TargetFolder%\%SourceFolderName%
if ErrorLevel
MsgBox The folder could not be copied, perhaps because a folder of that name already exists in "%TargetFolder%".
return
<
==============================================================================
*FileMoveDir*
+-------------+~
| FileMoveDir |~
+-------------+~
Moves a folder along with all its sub-folders and files. It can also
rename a folder.
>
FileMoveDir, Source, Dest [, Flag]
<
Parameters~
Source
------
Name of the source directory (with no trailing backslash), which is
assumed to be in %A_WorkingDir% if an absolute path isn't specified.
For example: C:\My Folder
Dest
-----
The new path and name of the directory (with no trailing baskslash),
which is assumed to be in %A_WorkingDir% if an absolute path isn't
specified. For example: D:\My Folder. Note: Dest is the actual path
and name that the directory will have after it is moved; it is not the
directory into which Source is moved (except for the known limitation
mentioned below).
Flag
-----
(options) Specify one of the following single characters:
0 (default): Do not overwrite existing files. The operation will fail
if Dest already exists as a file or directory.
1: Overwrite existing files. However, any files or subfolders inside
Dest that do not have a counterpart in Source will not be deleted.
Known limitation: If Dest already exists as a folder and it is on the
same volume as Source, Source will be moved into it rather than
overwriting it. To avoid this, see the next option.
2: The same as mode 1 above except that the limitation is absent.
R: Rename the directory rather than moving it. Although renaming
normally has the same effect as moving, it is helpful in cases where
you want "all or none" behavior; that is, when you don't want the
operation to be only partially successful when Source or one of its
files is locked (in use). Although this method cannot move Source onto
a different volume, it can move it to any other directory on its own
volume. The operation will fail if Dest already exists as a file or
directory.
ErrorLevel
----------
[v1.1.04+] This command is able to throw an exception on failure. For
more information, see Runtime Errors.
ErrorLevel is set to 1 if there was a problem or 0 otherwise.
Remarks~
FileMoveDir moves a single folder to a new location. To instead move
the contents of a folder (all its files and subfolders), see the
examples section of FileMove.
If the source and destination are on different volumes or UNC paths, a
copy/delete operation will be performed rather than a move.
Related~
|FileCopyDir|, |FileCopy|, |FileMove|, |FileDelete|, |File-loops|,
|FileSelectFolder|, |SplitPath|
Example~
>
FileMoveDir, C:\My Folder, D:\My Folder ; Move to a new drive.
FileMoveDir, C:\My Folder, C:\My Folder (renamed), R ; Simple rename.
FileMoveDir, C:\My Folder, C:\New Location\My Folder, R ; Folders can be "renamed into" another location as long as it's on the same volume.
<
==============================================================================
*FileDelete*
+------------+~
| FileDelete |~
+------------+~
Deletes one or more files.
>
FileDelete, FilePattern
<
Parameters~
FilePattern
-----------
The name of a single file or a wildcard pattern such as C:\Temp\*.tmp.
FilePattern is assumed to be in %A_WorkingDir% if an absolute path
isn't specified.
To remove an entire folder, along with all its sub-folders and files,
use FileRemoveDir.
ErrorLevel
----------
[v1.1.04+] This command is able to throw an exception on failure. For
more information, see Runtime Errors.
ErrorLevel is set to the number of files that failed to be deleted (if
any) or 0 otherwise. Deleting a wildcard pattern such as *.tmp is
considered a success even if it does not match any files; thus
ErrorLevel is set to 0.
If files were found, A_LastError is set to 0 (zero) or the result of
the operating system's GetLastError() function immediately after the
last failure. Otherwise A_LastError contains an error code that might
indicate why no files were found.
Remarks~
To delete a read-only file, first remove the read-only attribute. For
example: FileSetAttrib, -R, C:\My File.txt.
Related~
|FileRecycle|, |FileRemoveDir|, |FileCopy|, |FileMove|
Example~
>
FileDelete, C:\temp files\*.tmp
==============================================================================
*FileRecycle*
+-------------+~
| FileRecycle |~
+-------------+~
Sends a file or directory to the recycle bin, if possible.
>
FileRecycle, FilePattern
<
Parameters~
FilePattern
-----------
The name of a single file or a wildcard pattern such as C:\Temp\*.tmp.
FilePattern is assumed to be in %A_WorkingDir% if an absolute path
isn't specified.
To recycle an entire directory, provide its name without a trailing
backslash.
ErrorLevel
----------
[v1.1.04+] This command is able to throw an exception on failure. For
more information, see Runtime Errors.
ErrorLevel is set to 1 if there was a problem or 0 otherwise.
Remarks
-------
SHFileOperation is used to do the actual work. This function may
permanently delete the file if it is too large to be recycled; as of
v1.0.96, a warning should be shown before this occurs.
Related~
|FileRecycleEmpty|, |FileDelete|, |FileCopy|, |FileMove|
Example~
>
FileRecycle, C:\temp files\*.tmp
<
==============================================================================
*FileRecycleEmpty*
+------------------+~
| FileRecycleEmpty |~
+------------------+~
Sends a file or directory to the recycle bin, if possible.
>
FileRecycle, FilePattern
<
Parameters~
FilePattern
-----------
The name of a single file or a wildcard pattern such as C:\Temp\*.tmp.
FilePattern is assumed to be in %A_WorkingDir% if an absolute path
isn't specified.
To recycle an entire directory, provide its name without a trailing
backslash.
ErrorLevel
----------
[v1.1.04+] This command is able to throw an exception on failure. For
more information, see Runtime Errors.
ErrorLevel is set to 1 if there was a problem or 0 otherwise.
Remarks~
SHFileOperation is used to do the actual work. This function may
permanently delete the file if it is too large to be recycled; as of
v1.0.96, a warning should be shown before this occurs.
Related~
|FileRecycleEmpty|, |FileDelete|, |FileCopy|, |FileMove|
Example~
>
FileRecycle, C:\temp files\*.tmp
<
==============================================================================
*FileSelectFolder*
+------------------+~
| FileSelectFolder |~
+------------------+~
Displays a standard dialog that allows the user to select a folder.
>
FileSelectFolder, OutputVar [, StartingFolder, Options, Prompt]
<
Parameters~
OutputVar
---------
The name of the variable in which to store the user's selected folder.
This will be made blank if the user cancels the dialog (i.e. does not
wish to select a folder). If the user selects a root directory (such
as C:\), OutputVar will contain a trailing backslash. If this is
undesirable, remove it as follows:
>
FileSelectFolder, Folder
Folder := RegExReplace(Folder, "\\$") ; Removes the trailing backslash, if present.
<
StartingFolder
--------------
If blank or omitted, the dialog's initial selection will be the user's
My Documents folder (or possibly My Computer). A CLSID folder such as
::{20d04fe0-3aea-1069-a2d8-08002b30309d} (i.e. My Computer) may be
specified start navigation at a specific special folder.
Otherwise, the most common usage of this parameter is an asterisk
followed immediately by the absolute path of the drive or folder to be
initially selected. For example, *C:\ would initially select the C
drive. Similarly, *C:\My Folder would initially select that particular
folder.
The asterisk indicates that the user is permitted to navigate upward
(closer to the root) from the starting folder. Without the asterisk,
the user would be forced to select a folder inside StartingFolder (or
StartingFolder itself). One benefit of omitting the asterisk is that
StartingFolder is initially shown in a tree-expanded state, which may
save the user from having to click the first plus sign.
If the asterisk is present, upward navigation may optionally be
restricted to a folder other than Desktop. This is done by preceding
the asterisk with the absolute path of the uppermost folder followed
by exactly one space or tab. In the following example, the user would
not be allowed to navigate any higher than C:\My Folder (but the
initial selection would be C:\My Folder\Projects):
>
C:\My Folder *C:\My Folder\Projects
<
Options~
One of the following numbers:
0: The options below are all disabled (except on Windows 2000, where
the "make new folder" button might appear anyway).
1 (default): A button is provided that allows the user to create new
folders.
Add 2 to the above number to provide an edit field that allows the
user to type the name of a folder. For example, a value of 3 for this
parameter provides both an edit field and a "make new folder" button.
Add 4 to the above number to omit the BIF_NEWDIALOGSTYLE property.
Adding 4 ensures that FileSelectFolder will work properly even in a
Preinstallation Environment like WinPE or BartPE. However, this
prevents the appearance of a "make new folder" button, at least on
Windows XP. ["4" requires v1.0.48+]
If the user types an invalid folder name in the edit field, OutputVar
will be set to the folder selected in the navigation tree rather than
what the user entered, at least on Windows XP.
This parameter can be an expression.
Prompt
------
Text displayed in the window to instruct the user what to do. If
omitted or blank, it will default to "Select Folder - %A_SCRIPTNAME%"
(i.e. the name of the current script).
ErrorLevel
----------
[v1.1.04+] This command is able to throw an exception on failure. For
more information, see Runtime Errors.
ErrorLevel is set to 1 if the user dismissed the dialog without
selecting a folder (such as by pressing the Cancel button). It is also
set to 1 if the system refused to show the dialog (rare). Otherwise,
it is set to 0.
Remarks~
A GUI window may display a modal folder-selection dialog by means of
Gui +OwnDialogs. A modal dialog prevents the user from interacting
with the GUI window until the dialog is dismissed.
Known limitation: A timer that launches during the display of a
FileSelectFolder dialog will postpone the effect of the user's clicks
inside the dialog until after the timer finishes. To work around this,
avoid using timers whose subroutines take a long time to finish, or
disable all timers during the dialog:
>
Thread, NoTimers
FileSelectFolder, OutputVar,, 3
Thread, NoTimers, false
<
Related~
|FileSelectFile|, |MsgBox|, |InputBox|, |ToolTip|, |GUI|,
|CLSID_List|, |FileCopyDir|, |FileMoveDir|, |SplitPath|
Also, 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.
Example~
>
FileSelectFolder, OutputVar, , 3
if OutputVar =
MsgBox, You didn't select a folder.
else
MsgBox, You selected folder "%OutputVar%".
; CLSID Example:
FileSelectFolder, OutputVar, ::{20d04fe0-3aea-1069-a2d8-08002b30309d} ; My Computer.
<
==============================================================================
*FileSelectFile*
+----------------+~
| FileSelectFile |~
+----------------+~
Displays a standard dialog that allows the user to open or save
file(s).
>
FileSelectFile, OutputVar [, Options, RootDir\Filename, Prompt, Filter]
<
Parameters~
OutputVar
---------
The name of the variable in which to store the filename(s) selected by
the user. This will be made blank if the user cancels the dialog (i.e.
does not wish to select a file).
Options
-------
If omitted, it will default to zero, which is the same as having none
of the options below.
M: Multi-select. Specify the letter M to allow the user to select more
than one file via shift-click, control-click, or other means. M may
optionally be followed by a number as described below (for example,
both M and M1 are valid). To extract the individual files, see the
example at the bottom of this page.
S: Save button. Specify the letter S to cause the dialog to always
contain a Save button instead of an Open button. S may optionally be
followed by a number (or sum of numbers) as described below (for
example, both S and S24 are valid).
Even if M and S are absent, the following numbers can be used. To put
more than one of them into effect, add them up. For example, to use 8
and 16, specify the number 24.
1: File Must Exist
2: Path Must Exist
8: Prompt to Create New File
16: Prompt to OverWrite File
32 [v1.0.43.09+]: Shortcuts (.lnk files) are selected as-is rather
than being resolved to their targets. This option also prevents
navigation into a folder via a folder shortcut.
If the "Prompt to Overwrite" option is present without the "Prompt to
Create" option, the dialog will contain a Save button rather than an
Open button. This behavior is due to a quirk in Windows.
RootDir\Filename
----------------
If present, this parameter contains one or both of the following:
RootDir: The root (starting) directory, which is assumed to be a
subfolder in %A_WorkingDir% if an absolute path is not specified. If
omitted or blank, the starting directory will be a default that might
depend on the OS version (it will likely be the directory most
recently selected by the user during a prior use of FileSelectFile).
In v1.0.43.10+ on Windows XP/2003 and earlier, a CLSID such as
::{20d04fe0-3aea-1069-a2d8-08002b30309d} (i.e. My Computer) may also
be specified, in which case any subdirectory present after the CLSID
should end in a backslash (otherwise, the string after the last
backslash will be interpreted as the default filename, below).
Filename: The default filename to initially show in the dialog's edit
field. Only the naked filename (with no path) will be shown. To ensure
that the dialog is properly shown, ensure that no illegal characters
are present (such as /<|:").
Examples~
>
C:\My Pictures\Default Image Name.gif ; Both RootDir and Filename are present.
C:\My Pictures ; Only RootDir is present.
My Pictures ; Only RootDir is present, and it's relative to the current working directory.
My File ; Only Filename is present (but if "My File" exists as a folder, it is assumed to be RootDir).
<
Prompt
------
Text displayed in the window to instruct the user what to do. If
omitted or blank, it will default to "Select File - %A_SCRIPTNAME%"
(i.e. the name of the current script).
Filter
------
Indicates which types of files are shown by the dialog.
Example: Documents (*.txt)
Example: Audio (*.wav; *.mp2; *.mp3)
If omitted, the filter defaults to All Files (*.*). An option for Text Documents (*.txt) will also be available in the dialog's "files of type" menu.
Otherwise, the filter uses the indicated string but also provides an option for All Files (*.*) in the dialog's "files of type" drop-down list. To include more than one file extension in the filter, separate them with semicolons as illustrated in the example above.
ErrorLevel
----------
[v1.1.04+] This command is able to throw an exception on failure. For
more information, see Runtime Errors.
ErrorLevel is set to 1 if the user dismissed the dialog without
selecting a file (such as by pressing the Cancel button). It is also
set to 1 if the system refused to show the dialog (rare). Otherwise,
it is set to 0.
Remarks~
If the user didn't select anything (e.g. pressed CANCEL), OutputVar is
made blank.
If multi-select is not in effect, OutputVar is set to the full path
and name of the single file chosen by the user.
If the M option (multi-select) is in effect, OutputVar is set to a
list of items, each of which except the last is followed by a linefeed
(`n) character. The first item in the list is the path that contains
all the selected files (this path will end in a backslash only if it
is a root folder such as C:\). The other items are the selected
filenames (without path). For example:
C:\My Documents\New Folder [this is the path in which all the files
below reside]
test1.txt [these are the naked filenames: no path info]
test2.txt
... etc.
(The example at the bottom of this page demonstrates how to extract
the files one by one.)
When multi-select is in effect, the sum of the lengths of the selected
filenames is limited to 64 KB. Although this is typically enough to
hold several thousand files, OutputVar will be made blank if the limit
is exceeded.
A GUI window may display a modal file-selection dialog by means of Gui
+OwnDialogs. A modal dialog prevents the user from interacting with
the GUI window until the dialog is dismissed.
Known limitation: A timer that launches during the display of a
FileSelectFile dialog will postpone the effect of the user's clicks
inside the dialog until after the timer finishes. To work around this,
avoid using timers whose subroutines take a long time to finish, or
disable all timers during the dialog:
>
Thread, NoTimers
FileSelectFile, OutputVar
Thread, NoTimers, false
<
Obsolete option: In v1.0.25.06+, the multi-select option "4" is
obsolete. However, for compatibility with older scripts, it still
functions as it did before. Specifically, if the user selects only one
file, OutputVar will contain its full path and name followed by a
linefeed (`n) character. If the user selects more than one file, the
format is the same as that of the M option described above, except
that the last item also ends in a linefeed (`n).
Related~
|FileSelectFolder|, |MsgBox|, |InputBox|, |ToolTip|, |GUI|, |CLSID_List|, |parsing_loop|, |SplitPath|
Also, 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.
Examples~
>
FileSelectFile, SelectedFile, 3, , Open a file, Text Documents (*.txt; *.doc)
if SelectedFile =
MsgBox, The user didn't select anything.
else
MsgBox, The user selected the following:`n%SelectedFile%
; CLSID Example (requires XP/2003 or earlier):
FileSelectFile, OutputVar,, ::{645ff040-5081-101b-9f08-00aa002f954e} ; Recycle Bin.
; Multi-Select Example:
FileSelectFile, files, M3 ; M3 = Multiselect existing files.
if files =
{
MsgBox, The user pressed cancel.
return
}
Loop, parse, files, `n
{
if a_index = 1
MsgBox, The selected files are all contained in %A_LoopField%.
else
{
MsgBox, 4, , The next file is %A_LoopField%. Continue?
IfMsgBox, No, break
}
}
return
<
==============================================================================
*file-loops*
+------------+~
| File Loops |~
+------------+~
Retrieves the specified files or folders, one at a time.
>
Loop, Files, FilePattern [, Mode] ; v1.1.21+ (recommended)
Loop, FilePattern [, IncludeFolders?, Recurse?]
<
Parameters~
Files [v1.1.21+]
The literal word Files (case-insensitive). This cannot be a variable
or expression.
FilePattern
-----------
The name of a single file or folder, or a wildcard pattern such as
C:\Temp\*.tmp. FilePattern is assumed to be in %A_WorkingDir% if an
absolute path isn't specified.
Both asterisks and question marks are supported as wildcards. A match
occurs when the pattern appears in either the file's long/normal name
or its 8.3 short name.
If this parameter is a single file or folder (i.e. no wildcards) and
Recurse is set to 1 or Mode includes R, more than one match will be
found if the specified file name appears in more than one of the
folders being searched.
Mode [v1.1.21+]
Zero or more of the following letters:
D: Include directories (folders).
F: Include files. If both F and D are omitted, files are included but
not folders.
R: Recurse into subdirectories (subfolders). If R is omitted, files
and folders in subfolders are not included.
IncludeFolders?
One of the following digits, or blank to use the default:
0 (default) Folders are not retrieved (only files).
1 All files and folders that match the wildcard pattern are retrieved.
2 Only folders are retrieved (no files).
Recurse?One of the following digits, or blank to use the default:
0 (default) Subfolders are not recursed into.
1 Subfolders are recursed into so that files and folders contained
therein are retrieved if they match FilePattern. All subfolders will
be recursed into, not just those whose names match FilePattern.
Special Variables Available Inside a File-Loop~
The following variables exist within any file-loop. If an inner
file-loop is enclosed by an outer file-loop, the innermost loop's file
will take precedence:
A_LoopFileName The name of the file or folder currently retrieved
(without the path).
A_LoopFileExt The file's extension (e.g. TXT, DOC, or EXE). The period
(.) is not included.
A_LoopFileFullPath The path and name of the file/folder currently
retrieved. If FilePattern contains a relative path rather than an
absolute path, the path here will also be relative. In addition, any
short (8.3) folder names in FilePattern will still be short (see next
item to get the long version).
A_LoopFileLongPath This is different than A_LoopFileFullPath in the
following ways: 1) It always contains the absolute/complete path of
the file even if FilePattern contains a relative path; 2) Any short
(8.3) folder names in FilePattern itself are converted to their long
names; 3) Characters in FilePattern are converted to uppercase or
lowercase to match the case stored in the file system. This is useful
for converting file names -- such as those passed into a script as
command line parameters -- to their exact path names as shown by
Explorer.
A_LoopFileShortPath
The 8.3 short path and name of the file/folder currently retrieved.
For example: C:\MYDOCU~1\ADDRES~1.txt. If FilePattern contains a
relative path rather than an absolute path, the path here will also be
relative.
To retrieve the complete 8.3 path and name for a single file or
folder, specify its name for FilePattern as in this example:
>
Loop, C:\My Documents\Address List.txt
ShortPathName = %A_LoopFileShortPath%
<
NOTE: This variable will be blank if the file does not have a short
name, which can happen on systems where NtfsDisable8dot3NameCreation
has been set in the registry. It will also be blank if FilePattern
contains a relative path and the body of the loop uses SetWorkingDir
to switch away from the working directory in effect for the loop
itself.
A_LoopFileShortName The 8.3 short name, or alternate name of the file.
If the file doesn't have one (due to the long name being shorter than
8.3 or perhaps because short-name generation is disabled on an NTFS
file system), A_LoopFileName will be retrieved instead.
A_LoopFileDir The path of the directory in which A_LoopFileName
resides. If FilePattern contains a relative path rather than an
absolute path, the path here will also be relative. A root directory
will not contain a trailing backslash. For example: C:
A_LoopFileTimeModified The time the file was last modified. Format
YYYYMMDDHH24MISS.
A_LoopFileTimeCreated The time the file was created. Format
YYYYMMDDHH24MISS.
A_LoopFileTimeAccessed The time the file was last accessed. Format
YYYYMMDDHH24MISS.
A_LoopFileAttrib The attributes of the file currently retrieved.
A_LoopFileSize The size in bytes of the file currently retrieved.
Files larger than 4 gigabytes are also supported.
A_LoopFileSizeKB The size in Kbytes of the file currently retrieved,
rounded down to the nearest integer.
A_LoopFileSizeMB The size in Mbytes of the file currently retrieved,
rounded down to the nearest integer.
Remarks~
A file-loop is useful when you want to operate on a collection of
files and/or folders, one at a time.
All matching files are retrieved, including hidden files. By contrast,
OS features such as the DIR command omit hidden files by default. To
avoid processing hidden, system, and/or read-only files, use something
like the following inside the loop:
if A_LoopFileAttrib contains H,R,S ; Skip any file that is either H
(Hidden), R (Read-only), or S (System). Note: No spaces in "H,R,S".
continue ; Skip this file and move on to the next one.
To retrieve files' relative paths instead of absolute paths during a
recursive search, use SetWorkingDir to change to the base folder prior
to the loop, and then omit the path from the Loop (e.g. Loop, *.*, 0,
1). That will cause A_LoopFileFullPath to contain the file's path
relative to the base folder.
A file-loop can disrupt itself if it creates or renames files or
folders within its own purview. For example, if it renames files via
FileMove or other means, each such file might be found twice: once as
its old name and again as its new name. To work around this, rename
the files only after creating a list of them. For example:
FileList =
Loop, Files, *.jpg
FileList = %FileList%%A_LoopFileName%`n
Loop, Parse, FileList, `n
FileMove, %A_LoopField%, renamed_%A_LoopField%
Files in an NTFS file system are probably always retrieved in
alphabetical order. Files in other file systems are retrieved in no
particular order. To ensure a particular ordering, use the Sort
command as shown in the Examples section below.
Files and folders with a complete path name longer than 259 characters
are skipped over as though they do not exist. Such files are rare
because normally, the operating system does not allow their creation.
See Loop for information about Blocks, Break, Continue, and the
A_Index variable (which exists in every type of loop).
Related~
|Loop|, |Break|, |Continue|, |Blocks|, |SplitPath|, |FileSetAttrib|, |FileSetTime|
Examples~
>
; Example #1:
Loop Files, %A_ProgramFiles%\*.txt, R ; Recurse into subfolders.
{
MsgBox, 4, , Filename = %A_LoopFileFullPath%`n`nContinue?
IfMsgBox, No
break
}
; Example #2: Calculate the size of a folder, including the files in all its subfolders:
SetBatchLines, -1 ; Make the operation run at maximum speed.
FolderSizeKB = 0
FileSelectFolder, WhichFolder ; Ask the user to pick a folder.
Loop, Files, %WhichFolder%\*.*, R
FolderSizeKB += %A_LoopFileSizeKB%
MsgBox Size of %WhichFolder% is %FolderSizeKB% KB.
; Example #3: Retrieve file names sorted by name (see next example to sort by date):
FileList = ; Initialize to be blank.
Loop, C:\*.*
FileList = %FileList%%A_LoopFileName%`n
Sort, FileList, R ; The R option sorts in reverse order. See Sort for other options.
Loop, parse, FileList, `n
{
if A_LoopField = ; Ignore the blank item at the end of the list.
continue
MsgBox, 4,, File number %A_Index% is %A_LoopField%. Continue?
IfMsgBox, No
break
}
; Example #4: Retrieve file names sorted by modification date:
FileList =
Loop, Files, %A_MyDocuments%\Photos\*.*, FD ; Include Files and Directories
FileList = %FileList%%A_LoopFileTimeModified%`t%A_LoopFileName%`n
Sort, FileList ; Sort by date.
Loop, Parse, FileList, `n
{
if A_LoopField = ; Omit the last linefeed (blank item) at the end of the list.
continue
StringSplit, FileItem, A_LoopField, %A_Tab% ; Split into two parts at the tab char.
MsgBox, 4,, The next file (modified at %FileItem1%) is:`n%FileItem2%`n`nContinue?
IfMsgBox, No
break
}
; Example #5: Copy only the source files that are newer than their counterparts
; in the destination:
CopyIfNewer:
; Caller has set the variables CopySourcePattern and CopyDest for us.
Loop, Files, %CopySourcePattern%
{
copy_it = n
IfNotExist, %CopyDest%\%A_LoopFileName% ; Always copy if target file doesn't yet exist.
copy_it = y
else
{
FileGetTime, time, %CopyDest%\%A_LoopFileName%
EnvSub, time, %A_LoopFileTimeModified%, seconds ; Subtract the source file's time from the destination's.
if time < 0 ; Source file is newer than destination file.
copy_it = y
}
if copy_it = y
{
FileCopy, %A_LoopFileFullPath%, %CopyDest%\%A_LoopFileName%, 1 ; Copy with overwrite=yes
if ErrorLevel
MsgBox, Could not copy "%A_LoopFileFullPath%" to "%CopyDest%\%A_LoopFileName%".
}
}
Return
; Example #6: Convert filenames passed in via command-line parameters to long names,
; complete path, and correct uppercase/lowercase characters as stored in the file system.
Loop %0% ; For each file dropped onto the script (or passed as a parameter).
{
GivenPath := %A_Index% ; Retrieve the next command line parameter.
Loop %GivenPath%, 1
LongPath = %A_LoopFileLongPath%
MsgBox The case-corrected long path name of file`n%GivenPath%`nis:`n%LongPath%
}
<
==============================================================================
*SplitPath*
+-----------+~
| SplitPath |~
+-----------+~
Separates a file name or URL into its name, directory, extension, and
drive.
>
SplitPath, InputVar [, OutFileName, OutDir, OutExtension, OutNameNoExt, OutDrive]
<
Parameters~
InputVar
--------
Name of the variable containing the file name to be analyzed.
[v1.1.21+]: This parameter can be an % expression, but the
percent-space prefix must be used.
OutFileName
-----------
Name of the variable in which to store the file name without its path.
The file's extension is included.
OutDir
------
Name of the variable in which to store the directory of the file,
including drive letter or share name (if present). The final backslash
is not included even if the file is located in a drive's root
directory.
OutExtension
------------
Name of the variable in which to store the file's extension (e.g. TXT,
DOC, or EXE). The dot is not included.
OutNameNoExt
------------
Name of the variable in which to store the file name without its path,
dot and extension.
OutDrive
--------
Name of the variable in which to store the drive letter or server name
of the file. If the file is on a local or mapped drive, the variable
will be set to the drive letter followed by a colon (no backslash). If
the file is on a network path (UNC), the variable will be set to the
share name, e.g. \\Workstation01
Remarks
-------
Any of the output variables may be omitted if the corresponding
information is not needed.
If InputVar contains a filename that lacks a drive letter (that is, it
has no path or merely a relative path), OutDrive will be made blank
but all the other output variables will be set correctly. Similarly,
if there is no path present, OutDir will be made blank; and if there
is a path but no file name present, OutFileName and OutNameNoExt will
be made blank.
Actual files and directories in the file system are not checked by
this command. It simply analyzes the string given in InputVar.
Wildcards (* and ?) and other characters illegal in filenames are
treated the same as legal characters, with the exception of colon,
backslash, and period (dot), which are processed according to their
nature in delimiting the drive letter, directory, and extension of the
file.
Support for URLs: If InputVar contains a colon-double-slash, such as
http://domain.com or ftp://domain.com, OutDir is set to the protocol
prefix + domain name + directory (e.g. http://domain.com/images) and
OutDrive is set to the protocol prefix + domain name (e.g.
http://domain.com). All other variables are set according to their
definitions above.
Related~
|A_LoopFileExt|, |StringSplit|, |StringGetPos|, |StringMid|,
|StringTrimLeft|, |StringLeft|, |FileSelectFile|, |FileSelectFolder|
Example~
>
FullFileName = C:\My Documents\Address List.txt
; To fetch only the bare filename from the above:
SplitPath, FullFileName, name
; To fetch only its directory:
SplitPath, FullFileName,, dir
; To fetch all info:
SplitPath, FullFileName, name, dir, ext, name_no_ext, drive
; The above will set the variables as follows:
; name = Address List.txt
; dir = C:\My Documents
; ext = txt
; name_no_ext = Address List
; drive = C:
<
==============================================================================
*FileSetAttrib*
+---------------+~
| FileSetAttrib |~
+---------------+~
Changes the attributes of one or more files or folders. Wildcards are
supported.
>
FileSetAttrib, Attributes [, FilePattern, OperateOnFolders?, Recurse?]
<
Parameters~
Attributes
----------
The attributes to change (see Remarks).
FilePatternThe name of a single file or folder, or a wildcard pattern
such as C:\Temp\*.tmp. FilePattern is assumed to be in %A_WorkingDir%
if an absolute path isn't specified.
If omitted, the current file of the innermost enclosing File-Loop will
be used instead.
OperateOnFolders?
0 (default) Folders are not operated upon (only files).
1 All files and folders that match the wildcard pattern are operated upon.
2 Only folders are operated upon (no files).
Note: If FilePattern is a single folder rather than a wildcard
pattern, it will always be operated upon regardless of this setting.
This parameter can be an expression.
Recurse?
--------
0 (default) Subfolders are not recursed into.
1 Subfolders are recursed into so that files and folders contained
therein are operated upon if they match FilePattern. All subfolders
will be recursed into, not just those whose names match FilePattern.
However, files and folders with a complete path name longer than 259
characters are skipped over as though they do not exist. Such files
are rare because normally, the operating system does not allow their
creation.
This parameter can be an expression.
ErrorLevel
----------
[v1.1.04+] This command is able to throw an exception on failure. For
more information, see Runtime Errors.
ErrorLevel is set to the number of files that failed to be changed or
0 otherwise.
If files were found, A_LastError is set to 0 (zero) or the result of
the operating system's GetLastError() function immediately after the
last failure. Otherwise A_LastError contains an error code that might
indicate why no files were found.
Remarks~
The Attributes parameter consists of a collection of operators and
attribute letters.
Operators:
----------
+ Turn on the attribute
- Turn off the attribute
^ Toggle the attribute (set it to the opposite value of what it is now)
Attribute letters:
------------------
R = READONLY
A = ARCHIVE
S = SYSTEM
H = HIDDEN
N = NORMAL (this is valid only when used without any other attributes)
O = OFFLINE
T = TEMPORARY
Note: Currently, the compression state of files cannot be changed with this command.
Related~
|FileGetAttrib|, |FileGetTime|, |FileSetTime|, |FileGetSize|, |FileGetVersion|, |file-loop|
Examples~
>
FileSetAttrib, +RH, C:\MyFiles\*.*, 1 ; +RH is identical to +R+H
FileSetAttrib, ^H, C:\MyFiles ; Toggle the folder's "hidden" attribute.
FileSetAttrib, -R+A, C:\New Text File.txt
FileSetAttrib, +A, C:\*.ini, , 1 ; Recurse through all .ini files on the C drive.
<
vim:noundofile:foldcolumn=1:filetype=help:textwidth=70:wrap:nomodifiable:readonly:scrolljump=6: