GuiCreate

Creates a new Gui object, which is essential for creating and managing a GUI.

GuiObj := GuiCreate(Options, Title := A_ScriptName, EventObj)

Parameters

Options

For performance reasons, it is better to set all options in a single line.

Specify a plus sign to add the option and a minus sign to remove it. For example: Gui.Opt("+Resize -MaximizeBox").

The effect of this parameter is cumulative; that is, it alters only those settings that are explicitly specified, leaving all the others unchanged.

AlwaysOnTop: Makes the window stay on top of all other windows, which is the same effect as WinSetAlwaysOnTop.

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 WinSetTransColor, 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 or modified via GuiControl object. Specify a single character immediately after the word Delimiter. For example, Gui.Opt("+Delimiter`n") would use a linefeed character, which might be especially appropriate with continuation sections. Similarly, Gui.Opt("+Delimiter|") would revert to the default delimiter. To use space or tab, specify Gui.Opt("+DelimiterSpace") or Gui.Opt("+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).

DPIScale: Use Gui.Opt("-DPIScale") to disable DPI scaling, which is enabled by default. If DPI scaling is enabled on a system with a non-standard DPI setting, the Gui object and GuiControl object automatically scale coordinates and sizes to give controls roughly the same apparent size (but higher resolution). For example, with a DPI of 144 (150%), E := Gui.Add("Edit", "w100") would make the GUI control 150 pixels wide, but E.Pos.W would still return 100. A_ScreenDPI contains the system's current DPI.

DPI scaling only applies to the Gui object and GuiControl object, so coordinates coming directly from other sources such as ControlGetPos or WinGetPos will not work. There are a number of ways to deal with this:

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 functions such as WinGetStyle and WinSetTransparent 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.Opt("+LastFound")
WinSetTransColor(CustomColor " 150")
Gui.Show()

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: 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.Opt("+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.Opt("-MinSize -MaxSize") can be used to return to the defaults). Note: the window must have +Resize to allow resizing by the user.

OwnDialogs: Gui.Opt("+OwnDialogs") should be specified in each thread (such as a event handling function of a Button control) for which subsequently displayed MsgBox, InputBox, FileSelect, and DirSelect dialogs should be owned by the window. Such dialogs are modal, meaning that the user cannot interact with the GUI window until dismissing the dialog. By contrast, ToolTip 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.Opt("-OwnDialogs").

Owner: Use +Owner to make the window owned by another. An owned window has no taskbar button by default, and when visible it is always on top of its owner. It is also automatically destroyed when its owner is destroyed. +Owner can be used before or after the owned window is created. There are two ways to use +Owner, as shown below:

Gui.Opt("+OwnerMyOtherGui")  ; Make the GUI owned by MyOtherGui.
Gui.Opt("+Owner")  ; Make the GUI owned by script's main window to prevent display of a taskbar button.

+Owner can be immediately followed by the name or number of an existing GUI or the HWND of any top-level window.

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

Parent: Use +Parent immediately followed by the name or number of an existing GUI or the HWND of any window or control to use it as the parent of this window. To convert the GUI back into a top-level window, use -Parent. This option works even after the window is created.

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

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

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

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

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

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

Title

The window title. If omitted, it defaults to the current value of A_ScriptName.

EventObj

An "event sink", or object to bind events to. If EventObj is specified, OnEvent, OnNotify and OnCommand can be used to register methods of EventObj to be called when an event is raised. If omitted or empty, any string passed to OnEvent's Function parameter is interpreted as a function name.

Return Value

Returns a Gui object. This object provides methods and properties for creating and managing windows, and creating controls.

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 := GuiCreate("+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 the GuiControl object 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.

If the script is not persistent for any other reason, it will exit after the last visible GUI is closed; either when the last thread completes or immediately if no threads are running.

Related

Gui object, GuiControl object, GuiFromHwnd, GuiCtrlFromHwnd, Menu, Control Types, ListView, TreeView, Control functions, MsgBox, FileSelect, DirSelect

Examples

; Example: Display a text pop-up:

Gui := GuiCreate(, "Title of Window")
Gui.Opt("+AlwaysOnTop +Disabled -SysMenu +Owner")  ; +Owner avoids a taskbar button.
Gui.Add("Text",, "Some text to display.")
Gui.Show("NoActivate")  ; NoActivate avoids deactivating the currently active window.
; Example: A simple input-box that asks for first name and last name:

Gui := GuiCreate(, "Simple Input Example")
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").OnEvent("Click", "Gui_Close")
Gui.OnEvent("Close", "Gui_Close")
Gui.Show()

Gui_Close(Gui)
{
  Saved := Gui.Submit()  ; Save the contents of named controls into an object.
  MsgBox("You entered '%Saved.FirstName% %Saved.LastName%'.")
}
; Example: Tab control:

Gui := GuiCreate()
Tab := Gui.Add("Tab3",, "First Tab|Second Tab|Third Tab")
Gui.Add("Checkbox", "vMyCheckbox", "Sample checkbox") 
Tab.UseTab(2)
Gui.Add("Radio", "vMyRadio", "Sample radio1")
Gui.Add("Radio",, "Sample radio2")
Tab.UseTab(3)
Gui.Add("Edit", "vMyEdit r5")  ; r5 means 5 rows tall.
Tab.UseTab()  ; i.e. subsequently-added controls will not belong to the tab control.
Gui.Add("Button", "default xm", "OK").OnEvent("Click", "Gui_Close")  ; xm puts it at the bottom left corner.
Gui.OnEvent("Close", "Gui_Close")
Gui.OnEvent("Escape", "Gui_Close")
Gui.Show()

Gui_Close(Gui)
{
  Saved := Gui.Submit()  ; Save the contents of named controls into an object.
  MsgBox("You entered:`n" Saved.MyCheckbox "`n" Saved.MyRadio "`n" Saved.MyEdit)
}
; Example: ListBox containing files in a directory:

Gui := GuiCreate()
Gui.Add("Text",, "Pick a file to launch from the list below.")
fn := Func("LaunchFile").bind(Gui)
LB := Gui.Add("ListBox", "w640 r10 vFile"), LB.OnEvent("DoubleClick", fn)
LoopFiles("C:\*.*")  ; Change this folder and wildcard pattern to suit your preferences.
    LB.Add(A_LoopFilePath)
Gui.Add("Button", "Default", "OK").OnEvent("Click", fn)
Gui.Show()

LaunchFile(Gui)
{
  Saved := Gui.Submit()
  if MsgBox("Would you like to launch the file or document below?`n`n%Saved.File%",, 4) = "No"
    return
  try ; Otherwise, try to launch it:
    Run(Saved.File)
  catch Error
    MsgBox(Error.Extra)
}
; Example: Display context-senstive help (via ToolTip) whenever the user moves the mouse over a particular control:

Gui := GuiCreate()
Gui.Add("Edit", "vMyEdit")
MyEdit_TT := "This is a tooltip for the control whose name is MyEdit."
Gui.Add("DropDownList", "vMyDDL", "Red|Green|Blue")
MyDDL_TT := "Choose a color from the drop-down list."
Gui.Add("Checkbox", "vMyCheckBox", "This control has no tooltip.")
Gui.OnEvent("Close", "Gui_Close")
Gui.Show()
OnMessage(0x200, "WM_MOUSEMOVE")

WM_MOUSEMOVE(wParam, lParam, msg, Hwnd)
{
  global  
  static PrevHwnd
  if (Hwnd <gt; PrevHwnd)
  {
    Text := "", ToolTip() ; Turn off any previous tooltip.
    CurrControl := GuiCtrlFromHwnd(Hwnd)
    if CurrControl
    {
      Text := %CurrControl.Name%_TT
      SetTimer("DisplayToolTip", -1000)
    }
    PrevHwnd := Hwnd
  }
}

DisplayToolTip()
{
  global
  ToolTip(Text)
  SetTimer("ToolTip", -3000) ; Remove the tooltip.
}

Gui_Close()
{
  ExitApp()
}
; Example: On-screen display (OSD) via transparent window:

Gui := GuiCreate()
Gui.Opt("+LastFound +AlwaysOnTop -Caption +ToolWindow")  ; +ToolWindow avoids a taskbar button and an alt-tab menu item.
Gui.BackColor := "EEAA99"  ; Can be any RGB color (it will be made transparent below).
Gui.SetFont("s32")  ; Set a large font size (32-point).
CoordText := Gui.Add("Text", "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):
WinSetTransColor(Gui.BackColor " 150")
fn := Func("UpdateOSD").bind(CoordText), SetTimer(fn, 200)
UpdateOSD(CoordText)  ; Make the first update immediate rather than waiting for the timer.
Gui.Show("x0 y400 NoActivate")  ; NoActivate avoids deactivating the currently active window.

UpdateOSD(GuiCtrl)
{
  MouseGetPos(MouseX, MouseY)
  GuiCtrl.Value := "X%MouseX%, Y%MouseY%"
}
; Example: A moving progress bar overlayed on a background image.

Gui := GuiCreate()
Gui.BackColor := "White"
Gui.Add("Picture", "x0 y0 h350 w450", "%A_WinDir%\Web\Wallpaper\Windows\img0.jpg")
MyBtn := Gui.Add("Button", "Default xp+20 yp+250", "Start the Bar Moving")
MyProgress := Gui.Add("Progress", "w416")
MyText := Gui.Add("Text", "wp")  ; wp means "use width of previous".
MyBtn.OnEvent("Click", Func("MoveBar").bind(MyProgress, MyText))
Gui.Show()

MoveBar(ProgressCtrl, TextCtrl)
{
  LoopFiles("%A_WinDir%\*.*")
  {
    if A_Index > 100
      break
    ProgressCtrl.Value := A_Index
    TextCtrl.Value := A_LoopFileName
    Sleep 50
  }
  TextCtrl.Value := "Bar finished."
}
; Example: Simple image viewer:

Gui := GuiCreate("+Resize")
MyBtn := Gui.Add("Button", "default", "&Load New Image")
MyRadio := Gui.Add("Radio", "ym+5 x+10 checked", "Load &actual size")
Gui.Add("Radio", "ym+5 x+10", "Load to &fit screen")
MyPic := Gui.Add("Pic", "xm vPic")
MyBtn.OnEvent("Click", Func("LoadNewImage").bind(Gui, MyRadio, MyPic))
Gui.Show()

LoadNewImage(Gui, RadioCtrl, PicCtrl)
{
  File := FileSelect(,, "Select an image:", "Images (*.gif; *.jpg; *.bmp; *.png; *.tif; *.ico; *.cur; *.ani; *.exe; *.dll)")
  if File = ""
    return
  if RadioCtrl.Value = 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.
  }
  PicCtrl.Value := "*w%Width% *h%Height% %File%"  ; Load the image.
  Gui.Title := File
  Gui.Show("xCenter y0 AutoSize")  ; Resize the window to match the picture size.
}
; Example: Simple text editor with menu bar.

; Make these variables accessible for all the functions below:
global Gui, MainEdit, CurrentFileName, About

; Create the GUI window:
Gui := GuiCreate("+Resize", "Untitled")  ; Make the window resizable.

; Create the sub-menus for the menu bar:
Menu("FileMenu", "Add", "&New", "MenuFileNew")
Menu("FileMenu", "Add", "&Open", "MenuFileOpen")
Menu("FileMenu", "Add", "&Save", "MenuFileSave")
Menu("FileMenu", "Add", "Save &As", "MenuFileSaveAs")
Menu("FileMenu", "Add") ; Separator line.
Menu("FileMenu", "Add", "E&xit", "MenuFileExit")
Menu("HelpMenu", "Add", "&About", "MenuHelpAbout")

; 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:
MainEdit := Gui.Add("Edit", "WantTab W600 R20")

; Apply events:
Gui.OnEvent("DropFiles", "Gui_DropFiles")
Gui.OnEvent("Size", "Gui_Size")

MenuFileNew()  ; Apply default settings.
Gui.Show()  ; Display the window.

MenuFileNew()
{
  MainEdit.Value := ""  ; Clear the Edit control.
  Menu("FileMenu", "Disable", "3&")  ; Gray out &Save.
  Gui.Title := "Untitled"
}

MenuFileOpen()
{
  Gui.Opt("+OwnDialogs")  ; Force the user to dismiss the FileSelect dialog before returning to the main window.
  SelectedFileName := FileSelect(3,, "Open File", "Text Documents (*.txt)")
  if SelectedFileName = "" ; No file selected.
    return
  CurrentFileName := readContent(SelectedFileName)
}

MenuFileSave()
{
  saveContent(CurrentFileName)
}

MenuFileSaveAs()
{
  Gui.Opt("+OwnDialogs")  ; Force the user to dismiss the FileSelect dialog before returning to the main window.
  SelectedFileName := FileSelect("S16",, "Save File, Text Documents (*.txt)")
  if SelectedFileName = "" ; No file selected.
    return
  CurrentFileName := saveContent(SelectedFileName)
}

MenuFileExit()  ; User chose "Exit" from the File menu.
{
  WinClose()
}

MenuHelpAbout()
{
  About := GuiCreate("+owner%Gui.Hwnd%")  ; Make the main window the owner of the "about box".
  Gui.Opt("+Disabled")  ; Disable main window.
  About.Add("Text",, "Text for about box.")
  About.Add("Button", "Default", "OK").OnEvent("Click", "About_Close")
  About.OnEvent("Close", "About_Close")
  About.OnEvent("Escape", "About_Close")
  About.Show()
}

readContent(FileName)
{
  FileContent := FileRead(FileName)  ; Read the file's contents into the variable.
  if ErrorLevel
  {
    MsgBox("Could not open '%FileName%'.")
    return
  }
  MainEdit.Value := FileContent  ; Put the text into the control.
  Menu("FileMenu", "Enable", "3&")  ; Re-enable &Save.
  Gui.Title := FileName  ; Show file name in title bar.
  return FileName
}

saveContent(FileName)
{
  if FileExist(FileName)
  {
    FileDelete(FileName)
    if ErrorLevel
    {
      MsgBox("The attempt to overwrite '%FileName%' failed.")
      return
    }
  }
  FileAppend(MainEdit.Value, FileName)  ; Save the contents to the file.
  ; Upon success, Show file name in title bar (in case we were called by MenuFileSaveAs):
  Gui.Title := FileName
  return FileName
}

About_Close()
{
  Gui.Opt("-Disabled")  ; Re-enable the main window (must be done prior to the next step).
  About.Destroy()  ; Destroy the about box.
}

Gui_DropFiles(Gui, FileArray)  ; Support drag & drop.
{
  CurrentFileName := readContent(FileArray[1])  ; Read the first file only (in case there's more than one).
}

Gui_Size(Gui, MinMax, Width, Height)
{
  if MinMax = -1  ; The window has been minimized. No action needed.
    return
  ; Otherwise, the window has been resized or maximized. Resize the Edit control to match.
  MainEdit.Move("W%Width-20% H%Height-20%")
}