Mouse and keyboard macros and hotkeys.

Accueil | Téléchargement | Documentation | Historique | Support | Forum

GUI

(Traduction en cours...)

Crée et gère les fenêtres et les contrôles. De telles fenêtres peuvent être utilisées comme des formulaires d'entrée de données ou des interfaces utilisateurs personnalisées.

GUI, sous-commande [, Param2, Param3, Param4]

Table des Matières

Add, ControlType [, Options, Texte]

Ajoute un contrôle à une fenêtre parente (créer en premier la fenêtre parent elle-même, si nécessaire).

ControlType est un élément de la liste suivante:

Par exemple:

Gui, Add, Text,, S'il vous plaît, entrez votre nom:
Gui, Add, Edit, vName
Gui, Show

Show [, Options, Titre]

A moins que ce ne soit spécifié autrement dans Options, cette commande rend la fenêtre visible, la "déminimise" (si nécessaire), l'active, et défini sont titre. Si Titre est omis, le titre précédent est conservé (ou s'il n'y en a pas, le nom du script est utilisé).

Ommettez les options X, Y, W, et H ci-dessous pour que la fenêtre conserve sa taille et position précédente. S'il n'y a pas de position précédente, la fenêtre sera auto-centrée dans une ou dans les deux dimensions si les options X et/ou Y mentionnées ci-dessous sont absentes. S'il n'y a pas de taille précédente, la fenêtre sera auto-dimensionnée en accord avec la taille et les positions des contrôles qu'elle contient.

Zéro ou plusieurs des chaînes suivantes peuvent être présentes dans Options:

Wn: Spécifiez pour n la largeur de la zone client de la fenêtre, qui exclue la barre des titres, la barre de menu, et les bords de la fenêtre.

Hn: Spécifiez pour n la hauteur de la zone client de la fenêtre.

Note: En redimensionnant une fenêtre qui pourrait être en train d'être réduite ou agrandie, incluez Restore ou NoActivate dans les options pour s'assurer d'un comportement correct. Par exemple: Gui, Show, Restore w300 h200

Xn: Spécifiez pour n la position-X de la fenêtre sur l'écran.

Yn: Spécifiez pour n la position-Y de la fenêtre sur l'écran.

Center: Centre la fenêtre horizontalement et verticalement sur l'écran.

xCenter: Centre la fenêtre horizontalement sur l'écran. Par exemple: Gui, Show, xCenter y0

yCenter: Centre la fenêtre verticalement sur l'écran.

AutoSize: Redimensionne la fenête pour s'adapter uniquement à ses contrôles actuellement visibles. Ceci est utile pour redimensionner la fenêtre après l'ajout de nouveaux contrôles, ou lorsque des contrôles existants sont redimensionnés, cachés ou rendus visibles. Par exemple:
Gui, Show, AutoSize Center


Dans la version 1.0.25.13+, un des éléments suivants peut aussi être présent:

Minimize: Réduit la fenêtre et active celle qui se trouve au-dessous.

Maximize: Agrandit et active la fenêtre.

Restore: Dé-réduit ou dés-agrandit la fenêtre, si nécessaire. La fenêtre est aussi affichée et activée, si nécessaire.

NoActivate: Dé-réduit ou dés-agrandit la fenêtre, si nécessaire. La fenêtre est aussi affichée sans être activée.

NA: Affiche la fenêtre sans l'activer. Si la fenêtre est réduite, elle restera ainsi mais montera probablement plus haut dans l'ordre-z, ce qui peut être vu dans le sélecteur alt-tab. Si la fenêtre était cachée précédemment, cela provoquera probablement son affichage au dessus de la fenêtre activemême si la fenêtre active n'est pas désactivée.

Hide: Cache la fenêtre et active celle au-dessous d'elle. C'est identique à Gui Cancel excepté que cela permet à une fenêtre cachée d'être déplacée, redimensionnée, ou que le titre soit changé sans l'afficher. Par exemple: Gui, Show, Hide x55 y66 w300 h200, Nouveau Titre

Submit [, NoHide]

Sauvegarde les contenus de chaque contrôle dans sa variable associée (s'il y a) et cache la fenêtre à moins que le mot NoHide ne soit présent. Pour les contrôles qui produisent de multiples champs de sortie, tel qu'une ListBox multi sélection, la sotie utilise le délimiteur courant de la fenêtre. Si la fenêtre n'existe pas -- peut-être du faît qu'elle ait été détruite via Gui Destroy -- cette commande n'a aucun effet.

Cancel

Cache la fenêtre sans sauvegarder les contenus des contrôles dans leurs variables associées. Si la fenêtre n'existe pas -- peut-être du faît qu'elle ait été détruite via Gui Destroy  -- cette commande n'a aucun effet.

Destroy

Supprime la fenêtre (si elle existe) et tout ses contrôles, libérant la mémoire correspondante et les ressources système. Si cette commande n'est pas utilisée, toutes les fenêtres GUI sont automatiquement détruites lorsque le script s'arrête.

Font [, Options, FontName]

Fixe le type de police, la taille, le style et/ou la couleur pour les contrôles crées après ce point.

Omettez les deux paramètres pour restaurer la police GUI par défaut du système, sa taille et sa couleur.

FontName peut être le nom de n'importe quelle police, telle qu'une de la table des polices. Si FontName est omis ou n'existe pas dans le système, la police précédente sera utilisée, (ou s'il n'y en avait pas, la police GUI par défaut du système). Ce comportement est très utile pour faire qu'une fenêtre GUI ait une police similaire sur de multiples systèmes, même s'il manque la police préférée sur certains de ces systèmes. Par exemple, en utilisant les commandes suivantes dans l'ordre, Verdana sera préférée à Arial, qui à son tour sera préférée à MS sans serif:

gui, font,, MS sans serif
gui, font,, Arial
gui, font,, Verdana ; Police préférée.

Si le paramètre Options est vide, les attributs de la police précédente seront utilisés.Sinon, spécifiez une ou plus des lettres d'options comme substituts:

C: Nom de la couleur (voir color chart) ou valeur RGB -- ou spécifiez le mot Default pour revenir à la couleur par défaut du système (noir sur la plupart des systèmes). Exemple de valeurs: cRed, cFFFFAA, cDefault. Note: Les boutons n'obéïssent pas aux couleurs personalisées. De plus, un contrôle individuel peut être créé avec une couleur de police autre que la couleur courante en incluant l'option C. Par exemple: Gui, Add, Text, cRed, Mon Texte

S: Taille (en points). Par exemple: s10

W: Grammage (épaisseur), qui est un nombre entre 1 et 1000 (400 est normal  700 est gras). Par exemple: w600

Les mots suivants sont aussi supportés: bold (gras), italic (italique), strike (barré) , underline (souligné), et norm (normal). Norm revient au grammage/épaisseur normal et désactive l'italique, le barré et le souligné (mais conserve la couleur et la taille existante). Il est possible d'utiliser norm pour désactiver tout les attributs et ensuite en activer sélectivement d'autres. Par exemple, spécifier norm italic positionnerait la police sur normal puis sur italique.

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.

Color [, WindowColor, ControlColor]

Sets the background color of the window and/or its controls. WindowColor is used as the background for the parent window. ControlColor is applied to all present and future controls in the window (with the exception of a few types that do not support a custom color). Although ControlColor is initially obeyed by ListViews, subsequent changes to ControlColor do not affect them. Use GuiControl +BackgroundFF9977, MyListView to explicitly change a ListView's 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 and beyond, 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.
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.

Margin [, X, Y] [v1.0.33.01+]

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 (if 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.

+/-Option1 +/-Option2 ...

One or more options may be specified immediately after the GUI command. For performance reasons, it is better to do this 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 +owner ; Change the current/default GUI window.
Gui, 2:-resize +owner ; Change the second GUI window.

AlwaysOnTop [v1.0.25.13+]: 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: Provides a title bar and a thick window border/edge [Default]. When removing the caption from a window that will use WinSet TransColor, remove it only after setting the TransColor.

Delimiter [v1.0.36+]: 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 [v1.0.25.13+]: 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).

LastFound [v1.0.25.13+]: Sets the window to be the last found window, allowing commands such as WinSet to operate on it even if it is hidden (i.e. 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

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

MinimizeBox: Enables the minimize button in the title bar. [Default]

OwnDialogs [v1.0.35.01+]: 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 for itself 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 is created (i.e. 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 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 -MaximizeButton.

SysMenu: 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. This setting may be changed for an individual control by specifying +Theme or -Theme in its options.

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

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

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

Menu [, 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, MenuHandler
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

To remove a window's current menu bar, use "Gui Menu" (i.e. omit MenuName).

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 (note: 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 as a popup menu or submenu.

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 the UseErrorLevel setting is in effect). Use the following steps to make such changes: 1) detach the menu bar via "Gui Menu"; 2) make the changes; 3) reattach the menu bar via "Gui, Menu, MyMenuBar".

Hide / Minimize / Maximize / Restore [v1.0.25.14+]

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

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

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 http://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, 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 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 bottom or right 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, which uses the previous section for itself but establishes a new section for subsequent controls.

Options for Assigning Actions and Variables to Controls

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). For example: vMyEdit. This variable will be given the contents of its control 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 and GuiControlGet. Note: Gui Submit does not change the contents of variables associated with control types that are not input capable (such as Text and GroupBox).

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

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 it is used on a control that has this property.

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 activating or modifying it. Use "GuiControl Enable" to enable it later. Note: To make an Edit control read-only, specify the string ReadOnly instead. Also, in v1.0.26+, 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. In v1.0.26+, 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 (this can be used to make 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.

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

Theme [v1.0.32]: 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.

Remarks

The following labels will be automatically associated with a GUI window if they exist in the script:

GuiEscape: Launched when the user presses Escape. 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 also produce this effect.

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.

GuiSize: Launched when the window is resized, minimized, maximized, or restored. The 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, ErrorLevel will contain one of the following digits (in v1.0.36+, A_EventInfo may be used in place of ErrorLevel):
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.

GuiContextMenu [v1.0.36+]: 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 subroutine may check the following variables: 1) A_GuiControl, which contains the text or variable name of the control that received the event (blank if none); 2) A_EventInfo, which contains the number of the currently focused row (0 if none) in a ListBox or ListView if a control of that type is the target of this event; 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%); and 4) A_GuiEvent, which contains the word RightClick if the user right-clicked, and 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 this label.

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 subroutine may check the following variables: 1) A_GuiControl, which contains the text or variable name of the control upon which the files were dropped (blank if none); 2) ErrorLevel, which in v1.0.25+ contains the number of files dropped (in v1.0.36+, A_EventInfo may be used in place of ErrorLevel); 3) A_GuiX and A_GuiY, which in v1.0.36+ contain the X and Y coordinates of where the files were dropped; and 4) A_GuiControlEvent, 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:

Loop, parse, A_GuiControlEvent, `n
{
MsgBox, 4,, File number %A_Index% is:`n%A_LoopField%.`n`nContinue?
IfMsgBox, No, Break
}

; To extract only the first file, follow this example:
Loop, parse, A_GuiControlEvent, `n
{
FirstFile = %A_LoopField%
Break
}

; To process the files in alphabetical order, follow this example:
FileList = %A_GuiControlEvent%
Sort, FileList
Loop, parse, FileList, `n
... etc.

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.


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 labels for the second window.

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

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

 

GUI Events

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.

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. See their links for details.

All GUI threads start off fresh with the default values for settings such as SetKeyDelay. These defaults can be changed in the auto-execute section.

To have multiple events perform the same subroutine, specify their labels consecutively above the subroutine. For example:

GuiEscape:
GuiClose:
ButtonCancel:
Gui, Cancel ; All of the above labels will execute this subroutine.
return


Keyboard Navigation

A GUI window may be navigated via the TAB key, which moves keyboard focus to the next input-capable control (controls lacking the TabStop style 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 is displayed in the control's text as an underlined character. 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

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.

See also: 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, ListView, Control, ControlGet, SplashImage, MsgBox, FileSelectFile, FileSelectFolder

 

Examples



; Example: Achieve an effect similar to SplashTextOn. This script requires v1.0.25.13.
Gui, +AlwaysOnTop +Disabled -SysMenu
Gui, Add, Text,, Some text to display.
Gui, Show, NoActivate, My Window ; NoActivate avoids deactivating the currently active window.


; Example: Simple input-box:
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, Tab,, First Tab|Second Tab|Third Tab
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_GuiControlEvent <> 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: On-screen display (OSD). This script requires v1.0.25.13 or later.
CustomColor = EEAA99 ; Can be any RGB color (it will be made transparent below).
Gui, +AlwaysOnTop +LastFound +Owner ; +Owner prevents a taskbar button from appearing.
Gui, Color, %CustomColor%
Gui, Font, s24
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
Gui, -Caption ; Remove the title bar and window borders.
SetTimer, UpdateOSD, 200
Gosub, UpdateOSD ; Make the first update immediate rather than waiting for the timer.
Gui, Show, x0 y400
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. This script requires v1.0.25.0.
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. This script requires v1.0.25.0.
; 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:
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 <> 0
{
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:
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 <> 0
{ 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:
MsgBox A very simple text editor.
return
GuiDropFiles: ; Support drag & drop.
Loop, parse, A_GuiControlEvent, `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