My Technical Notes

Sunday, 15 January 2017

Basic Dialog/Window In AutoHotkey

This example displays a simple GUI using AutoHotkey. It asks for a forename and surname and displays the entered data in a message box.


; Create a new GUI called "PersonGui"
Gui, PersonGui:New
; 1. +AlwaysOnTop - make it always on top so that users can see it
; 2. -SysMenu gets rid of the top-left icon, and the minimize, maximize and close buttons
; 3. +Owner removes the dialog's taskbar icon
Gui, +AlwaysOnTop -SysMenu +Owner 
; Add the forename and surname labels
Gui, Add, Text,, Forename:
Gui, Add, Text,, Surname:
; Add forename and surname textboxes. The ym option starts a new column of controls.
Gui, Add, Edit, vForename ym
Gui, Add, Edit, vSurname
; Add an "OK" button, which, when when pressed, will run the PersonGuiOK label.
; "Default" makes it the default action when Enter key is pressed
Gui, Add, Button, gPersonGuiOK Default, OK
; We want the "Cancel" button to be next to the "OK" button with a margin of 5 pixels
GuiControlGet, OK, Pos
NewXPos := OKX + OKW + 5
; Add the "Cancel" button, running label "PersonGuiCancel", 
; setting its location to be next to the "OK" button, by setting its xy coordinates.
Gui, Add, Button, gPersonGuiCancel x%NewXPos% y%OKY%, Cancel
; Show the dialog, with the title of "Person Details"
Gui, Show,, Person Details
; return ends the auto-execute section. This script is idle until the user does something with the GUI.
return 

 ; PersonGuiOK label is associated with the "OK" button
PersonGuiOK:
; Gui, Submit saves the input from the user to each control's associated variable.
Gui, Submit 
; Show the dialog with the entered Forename and Surname values
MsgBox You entered "%Forename% %Surname%".
; ExitApp terminates the script
ExitApp

; GuiEscape will be run when the user presses the Escape key while the GUI is active 
PersonGuiGuiEscape:
; GuiClose will be run when the dialog is closed.
PersonGuiGuiClose:
; PersonGuiCancel is the label associated with the "Cancel" button
PersonGuiCancel:
; Gui, Destroy: destroy the GUI
Gui, Destroy
ExitApp

If you had more than one GUI in your app, and you wanted to set this this particular GUI `PersonGui` as the default that commands such as `Add` operate on, we use the `Default` sub-command:


Gui, PersonGui:Default

If on the other-hand, you wanted to add a control to a GUI without setting it as the `Default`, you can specify the GUI's name:


Gui, PersonGui:Add, Text,, Forename:

No comments: