# GUI

Creates and manages windows and controls. Such windows can be used as data entry forms or custom user interfaces.

Gui, sub-command [, Param2, Param3, Param4]

## Table of Contents

- Add: Creates a control such as text, button, or checkbox.
- Show: Displays the window. It can also minimize, maximize, or move the window.
- Submit: Saves the user's input and optionally hides the window.
- Cancel (or Hide): Hides the window.
- Destroy: Deletes the window.
- Font: Sets the typeface, size, style, and text color for subsequently created controls.
- Color: Sets the background color for the window and/or its controls.
- Margin: Sets the margin/spacing used whenever no explicit position has been specified for a control.
- Options and styles for a window: Sets various options for the appearance and behavior of the window.
- Menu: Adds or removes a menu bar.
- Minimize / Maximize / Restore: Performs the indicated operation on the window.
- Flash: Blinks the window and its taskbar button.
- Default: Changes the current thread's default GUI window number.
- Positioning and sizing of controls
- Storing and responding to user input: variables and g-labels
- Options and styles for controls
- Window Events: GuiClose | GuiEscape | GuiSize | GuiContextMenu | GuiDropFiles
- Creating Multiple GUI windows
- GUI Events, Threads, and Subroutines
- Miscellaneous: Keyboard Navigation | Window Appearance | General Remarks
- Examples: Contains working scripts that demonstrate GUI windows and controls.

## 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
- Hotkey, DateTime, MonthCal
- Slider, Progress
- GroupBox, Tab, StatusBar, Internet Explorer Control

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

yCenter: Centers the window vertically on the screen.

AutoSize: Resizes the window to accommodate only its currently visible controls. This is useful to resize the window after new controls are added, or existing controls are resized, hidden, or unhidden. For example:
Gui, Show, AutoSize Center

One of the following may also be present:

Minimize: Minimizes the window and activates the one beneath it.

Maximize: Maximizes and activates the window.

Restore: Unminimizes or unmaximizes the window, if necessary. The window is also shown and activated, if necessary.

NoActivate: Unminimizes or unmaximizes the window, if necessary. The window is also shown without activating it.

NA: Shows the window without activating it. If the window is minimized, it will stay that way but will probably rise higher in the z-order (which is the order seen in the alt-tab selector). If the window was previously hidden, this will probably cause it to appear on top of the active window even though the active window is not deactivated.

Hide: Hides the window and activates the one beneath it. This is identical in function to Gui Cancel except that it allows a hidden window to be moved, resized, or given a new title without showing it. For example: Gui, Show, Hide x55 y66 w300 h200, New Title

## Gui, 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]

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.

Omit the last two parameters to restore the font to the system's default GUI typeface, size, and color.

FontName may be the name of any font, such as one from the font table. If FontName is omitted or does not exist on the system, the previous font's typeface will be used (or if none, the system's default GUI typeface). This behavior is useful to make a GUI window have a similar font on multiple systems, even if some of those systems lack the preferred font. For example, by using the following commands in order, Verdana will be given preference over Arial, which in turn is given preference over MS sans serif:

    gui, font,, MS sans serif
    gui, font,, Arial
    gui, font,, Verdana  ; Preferred font.

If the Options parameter is blank, the previous font's attributes will be used. Otherwise, specify one or more of the following option letters as substitutes:

C: Color name (see color chart) or RGB value -- or specify the word Default to return to the system's default color (black on most systems). Example values: cRed, cFFFFAA, cDefault. Note: Buttons do not obey custom colors. Also, an individual control can be created with a font color other than the current one by including the C option. For example: Gui, Add, Text, cRed, My Text

S: Size (in points). For example: s12 (specify decimal, not hexadecimal)

W: Weight (boldness), which is a number between 1 and 1000 (400 is normal and 700 is bold). For example: w600 (specify decimal, not hexadecimal)

The following words are also supported: bold, italic, strike, underline, and norm. Norm returns the font to normal weight/boldness and turns off italic, strike, and underline (but it retains the existing color and size). It is possible to use norm to turn off all attributes and then selectively turn on others. For example, specifying norm italic would set the font to normal then to italic.

To specify more than one option, include a space between each. For example: cBlue s12 bold

If a script creates multiple GUI windows, each window remembers its own "current font" for the purpose of creating more controls.

On a related note, the operating system offers standard dialog boxes that prompt the user to pick a font, color, or icon. These dialogs can be displayed via DllCall() as demonstrated at www.autohotkey.com/forum/topic17230.html.

## Gui, 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, 2:-Caption if it is the second window, etc.

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 2:+Resize -MaximizeBox  ; Change the settings of the second GUI window.

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

Label [v1.0.44.09+]: Sets custom names for this window's special labels. For example, Gui 2:+LabelMyGui would use the labels MyGuiClose and MyGuiSize (if they exist) instead of 2GuiClose and 2GuiSize. In other words, the string "2Gui" is replaced by "MyGui" 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 2:+LastFoundExist
    IfWinExist
        MsgBox GUI #2 already exists.

MaximizeBox: Enables the maximize button in the title bar. This is also included as part of Resize below.

MinimizeBox (present by default): Enables the minimize button in the title bar.

MinSize and MaxSize [v1.0.44.13+]: Determines the minimum and/or maximum size of the window, such as when the user drags its edges to resize it. Specify the word MinSize and/or MaxSize with no suffix to use the window's current size as the limit (if the window has no current size, it will use the size from the first use of Gui Show). Alternatively, append the width, followed by an X, followed by the height; for example: Gui +Resize +MinSize640x480. The dimensions are in pixels, and they specify the size of the window's client area (which excludes borders, title bar, and menu bar). Specify each number as decimal, not hexadecimal.

Either the width or the height may be omitted to leave it unchanged (e.g. +MinSize640x or +MinSizex480). Furthermore, Min/MaxSize can be specified more than once to use the window's current size for one dimension and an explicit size for the other. For example, +MinSize +MinSize640x would use the window's current size for the height and 640 for the width.

If MinSize and MaxSize are never used, the operating system's defaults are used (similarly, Gui -MinSize -MaxSize can be used to return to the defaults). Note: the window must have +Resize to allow resizing by the user.

OwnDialogs: Gui +OwnDialogs should be specified in each thread (such as a ButtonOK subroutine) for which subsequently displayed MsgBox, InputBox, FileSelectFile, and FileSelectFolder dialogs should be owned by the window. Such dialogs become modal, meaning that the user cannot interact with the GUI window until dismissing the dialog. By contrast, ToolTip, Progress, and SplashImage windows do not become modal even though they become owned; they will merely stay always on top of their owner. In either case, any owned dialog or window is automatically destroyed when its GUI window is destroyed.

There is typically no need to turn this setting back off because it does not affect other threads. However, if a thread needs to display both owned and unowned dialogs, it may turn off this setting via Gui -OwnDialogs.

If no window number prefix is specified -- such as using Gui +OwnDialogs rather than Gui 2:+OwnDialogs -- the thread's default window will own the dialogs.

Owner: Use +owner to make the window owned by another (but once the window is created, -owner has no effect). An owned window has no taskbar button by default, and when visible it is always on top of its owner. It is also automatically destroyed when its owner is destroyed. +Owner must be used after the window's owner is created but before the owned window is created (that is, before commands such as Gui Add). There are two ways to use +owner as shown in these examples:

    gui, 2:+owner1  ; Make #2 window owned by #1 window.
    gui, 2:+owner  ; Make #2 window owned by script's main window to prevent display of a taskbar button.

To prevent the user from interacting with the owner while one of its owned window is visible, disable the owner via Gui +Disabled. Later (when the time comes to cancel or destroy the owned window), re-enable the owner via Gui -Disabled. Do this prior to cancel/destroy so that the owner will be reactivated automatically.

Resize: Makes the window resizable and enables its maximize button in the title bar. To avoid enabling the maximize button, specify +Resize -MaximizeBox.

SysMenu (present by default): Specify -SysMenu (minus SysMenu) to omit the system menu and icon in the window's upper left corner. This will also omit the minimize, maximize, and close buttons in the title bar.

Theme: By specifying -Theme, all subsequently created controls in the window will have Classic Theme appearance on Windows XP and beyond. To later create additional controls that obey the current theme, turn it back on via +Theme. Note: This option has no effect on operating systems older than Windows XP, nor does it have any effect on XP itself if the Classic Theme is in effect. Finally, this setting may be changed for an individual control by specifying +Theme or -Theme in its options.

ToolWindow: Provides a narrower title bar but the window will have no taskbar button.

(Unnamed Style): Specify a plus or minus sign followed immediately by a decimal or hexadecimal style number.

(Unnamed ExStyle): Specify a plus or minus sign followed immediately by the letter E and a decimal or hexadecimal extended style number. For example, +E0x40000 would add the WS_EX_APPWINDOW style, which provides a taskbar button for a window that would otherwise lack one. Although the other extended styles are not documented here (since they are rarely used), they can be discovered by searching for WS_EX_APPWINDOW at www.microsoft.com.

## 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    Ctrl+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. To enable such a shortcut in the script, use a context-sensitive hotkey:

    #IfWinActive GUI Window's Title ahk_class AutoHotkeyGUI
    ^o::  ; The Ctrl+O hotkey.
    MenuFileOpen:
    Gui +OwnDialogs  ; Force the user to dismiss the FileSelectFile dialog before returning to the main window.
    FileSelectFile, SelectedFile
    MsgBox You selected the file %SelectedFile%.
    return

    ; The following part is needed only if the script will be run on Windows 95/98/Me:
    #IfWinActive
    $^o::Send ^o

To remove a window's current menu bar, use Gui Menu (that is, omit the last parameter).

Once a menu has been used as a menu bar, it should not be used as a popup menu or a submenu. This is because menu bars internally require a different format (however, this restriction applies only to the menu bar itself, not its submenus). If you need to work around this, create one menu to use as the menu bar and another identical menu to use for everything else.

The use of certain destructive menu sub-commands such as Delete and DeleteAll against a menu that is currently being used as a menu bar (and in some cases, its submenus) is not supported and will cause an error dialog to be displayed (unless UseErrorLevel is in effect). Use the following steps to make such changes: 1) detach the menu bar via Gui Menu (that is, omit MenuName); 2) make the changes; 3) reattach the menu bar via Gui, Menu, MyMenuBar

## Gui, 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, 2:Default

Changes the current thread's default GUI window number, which is used whenever a window number is not specified for GuiControl, GuiControlGet, and the Gui command itself. In the following example, the default window number is changed to two: Gui 2:Default. See thread's default window for more information about the default window.

## 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/

## 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 (except GroupBoxes, which multiply by 18 to provide room inside for margins).

H: Height, in pixels. If both the H and R options are absent, DropDownLists, ComboBoxes, ListBoxes, and empty 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.

## 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.

## 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.

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.

Center: Centers the control's text within its available width.

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, precede Wrap with a minus sign 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).

## 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.

Hwnd OutputVar [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). On a related note, a parent window's HWND can be retrieved via Gui 2:+LastFoundExist followed by WinExist().

Theme: This option can be used to override the window's current theme setting on a per-control basis. 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 the first, the window's number is used as a prefix for the special labels mentioned above; for example, 2GuiEscape and 2GuiClose would be the default labels for the second window. To use custom label names, see Gui +Label.

Each script may have up to 99 GUI windows simultaneously. To operate upon a window number other than the default, include a number followed by a colon in front of the sub-command as in these examples:

    Gui, 2:Add, Text,, Text for about-box.
    Gui, 2:Show

Gui 2:Default can be used to avoid the need for the "2:" prefix above. In addition, the prefix is not necessary inside a GUI thread that operates upon the same window number that launched the thread.

Performance might be slightly better for lower window numbers than higher ones.

## 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 number 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 number 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, 2:+owner1  ; Make the main window (Gui #1) the owner of the "about box" (Gui #2).
    Gui +Disabled  ; Disable main window.
    Gui, 2:Add, Text,, Text for about box.
    Gui, 2:Add, Button, Default, OK
    Gui, 2:Show
    return

    2ButtonOK:  ; This section is used by the "about box" above.
    2GuiClose:
    2GuiEscape:
    Gui, 1:-Disabled  ; Re-enable the main window (must be done prior to the next step).
    Gui Destroy  ; Destroy the about box.
    return

    GuiDropFiles:  ; Support drag & drop.
    Loop, parse, A_GuiEvent, `n
    {
        SelectedFileName = %A_LoopField%  ; Get the first file only (in case there's more than one).
        break
    }
    Gosub FileRead
    return

    GuiSize:
    if ErrorLevel = 1  ; The window has been minimized.  No action needed.
        return
    ; Otherwise, the window has been resized or maximized. Resize the Edit control to match.
    NewWidth := A_GuiWidth - 20
    NewHeight := A_GuiHeight - 20
    GuiControl, Move, MainEdit, W%NewWidth% H%NewHeight%
    return

    FileExit:     ; User chose "Exit" from the File menu.
    GuiClose:  ; User closed the window.
    ExitApp