### Create Installer Screen with SplashImage and Progress Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/Progress.htm Demonstrates creating a professional-looking installer screen by overlaying a Progress window on a SplashImage. This example iterates through files, updating the progress bar. ```AutoHotkey if FileExist("C:\WINDOWS\system32\ntimage.gif") SplashImage, %A_WinDir%\system32\ntimage.gif, A,,, Installation Loop, %A_WinDir%\system32\*.* { Progress, %A_Index%, %A_LoopFileName%, Installing..., Draft Installation Sleep, 50 if (A_Index = 100) break } ``` -------------------------------- ### Example: Get Control Under Mouse Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/ControlGetPos.htm This example continuously updates and displays the name and position of the control currently under the mouse cursor. ```APIDOC ## Example: Continuously update control info under mouse ```autohotkey Loop { Sleep, 100 MouseGetPos, , , WhichWindow, WhichControl ControlGetPos, x, y, w, h, %WhichControl%, ahk_id %WhichWindow% ToolTip, %WhichControl%`nX%X%`tY%Y%`nW%W%`t%H% } ``` ### Explanation * The `Loop` continuously executes the code within it. * `Sleep, 100` pauses the script for 100 milliseconds to avoid excessive CPU usage. * `MouseGetPos` retrieves the coordinates of the mouse cursor and identifies the window and control under it. * `ControlGetPos` is then used with the identified control and window to get its position (`x`, `y`) and dimensions (`w`, `h`). * `ToolTip` displays the control's identifier, position, and dimensions. ``` -------------------------------- ### Make Classic Start Menu Transparent Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/WinSet.htm Applies transparency to the classic Start Menu. To make submenus transparent, a separate example is provided. ```AutoHotkey DetectHiddenWindows, On WinSet, Transparent, 150, ahk_class BaseBar ``` -------------------------------- ### Start Method Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/InputHook.htm Starts the InputHook, enabling it to capture input according to its configuration. ```APIDOC ih.Start() ``` -------------------------------- ### Silent Installation with Command Line Options Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/FAQ.htm Use the /S flag with setup.exe or the script name for silent installation. ```autohotkey setup.exe /S ``` ```autohotkey AutoHotkeyU32.exe Installer.ahk /S ``` -------------------------------- ### Example: Enable a Hotstring Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/Hotstring.htm This example demonstrates enabling a previously disabled hotstring. ```AutoHotkey Hotstring("::btw", "", "On") ``` -------------------------------- ### InputHook.Start Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/InputHook.htm Starts collecting input. This method installs the keyboard hook if it's not already active and places the new input session at the top of the InputHook stack, allowing it to override previous sessions. ```APIDOC ## InputHook.Start ### Description Starts collecting input. Has no effect if input is already in progress. Installs the keyboard hook if not already active and places the new input on top of the InputHook stack. ### Method InputHook.Start() ### Remarks This method installs the keyboard hook (if it was not already). ### Example ```apidoc InputHook.Start() ``` ``` -------------------------------- ### Example: Create a Simple Hotstring Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/Hotstring.htm This example demonstrates creating a basic hotstring that replaces 'btw' with 'by the way'. ```AutoHotkey Hotstring("::btw", "by the way") ``` -------------------------------- ### Create Windows Explorer-like TreeView and ListView Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/TreeView.htm Builds a TreeView displaying folders from the Start Menu and a side-by-side ListView showing folder contents. Includes a StatusBar for file information and supports window resizing. This example requires the `AddSubFoldersToTree` function (not provided here) to populate the TreeView. ```AutoHotkey ; The following folder will be the root folder for the TreeView. Note that loading might take a long ; time if an entire drive such as C:\ is specified:_ TreeRoot := A_StartMenuCommon TreeViewWidth := 280 ListViewWidth := A_ScreenWidth - TreeViewWidth - 30 ; Allow the user to maximize or drag-resize the window:_ Gui +Resize ; Create an ImageList and put some standard system icons into it:_ ImageListID := IL_Create(5) Loop 5 IL_Add(ImageListID, "shell32.dll", A_Index) ; Create a TreeView and a ListView side-by-side to behave like Windows Explorer:_ Gui, Add, TreeView, vMyTreeView r20 w%TreeViewWidth% gMyTreeView [ImageList](#ImageList)%ImageListID% Gui, Add, ListView, vMyListView r20 w%ListViewWidth% x+10, Name|Modified ; Set the ListView's column widths (this is optional):_ Col2Width := 70 _; Narrow to reveal only the YYYYMMDD part._ LV_ModifyCol(1, ListViewWidth - Col2Width - 30) _; Allows room for vertical scrollbar._ LV_ModifyCol(2, Col2Width) ; Create a status bar to give info about the number of files and their total size:_ Gui, Add, StatusBar SB_SetParts(60, 85) _; Create three parts in the bar (the third part fills all the remaining width)._ ; Add folders and their subfolders to the tree. Display the status in case loading takes a long time:_ SplashTextOn, 200, 25, TreeView and StatusBar Example, Loading the tree... AddSubFoldersToTree(TreeRoot) SplashTextOff ``` -------------------------------- ### IP Address Control Example Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/Gui.htm Demonstrates adding and using a custom IP address control. It includes functions to set and get the IP address, and handles associated events like field changes. ```AutoHotkey Gui, Add, Custom, ClassSysIPAddress32 r1 w150 hwndhIPControl gIPControlEvent Gui, Add, Button, Default, OK IPCtrlSetAddress(hIPControl, A_IPAddress1) Gui, Show return GuiClose: ExitApp ButtonOK: Gui, Hide ToolTip MsgBox % "You chose " IPCtrlGetAddress(hIPControl) ExitApp IPControlEvent: if (A_GuiEvent = "Normal") { _; WM_COMMAND was received._ if (A_EventInfo = 0x0300) _; EN_CHANGE_ ToolTip Control changed! } else if (A_GuiEvent = "N") { _; WM_NOTIFY was received. ; Get the notification code. Normally this field is UInt but the IP address ; control uses negative codes, so for convenience we read it as a signed int._ nmhdr_code := NumGet(A_EventInfo + 2*A_PtrSize, "int") if (nmhdr_code != -860) _; IPN_FIELDCHANGED_ return _; Extract info from the NMIPADDRESS structure_ iField := NumGet(A_EventInfo + 3*A_PtrSize + 0, "int") iValue := NumGet(A_EventInfo + 3*A_PtrSize + 4, "int") if (iValue >= 0) ToolTip Field #%iField% modified: %iValue% else ToolTip Field #%iField% left empty } return IPCtrlSetAddress(hControl, IPAddress) { static WM_USER := 0x0400 static IPM_SETADDRESS := WM_USER + 101 _; Pack the IP address into a 32-bit word for use with SendMessage._ IPAddrWord := 0 Loop, Parse, IPAddress, . IPAddrWord := (IPAddrWord * 256) + A_LoopField SendMessage IPM_SETADDRESS, 0, IPAddrWord,, ahk_id %hControl% } IPCtrlGetAddress(hControl) { static WM_USER := 0x0400 static IPM_GETADDRESS := WM_USER + 102 VarSetCapacity(AddrWord, 4) SendMessage IPM_GETADDRESS, 0, &AddrWord,, ahk_id %hControl% } ``` -------------------------------- ### Get Shortcut Information - AutoHotkey Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/FileGetShortcut.htm This example demonstrates how to prompt the user to select a shortcut file and then display its properties using FileGetShortcut. Ensure the .lnk extension is included when selecting the file. ```AutoHotkey FileSelectFile, file, 32,, Pick a shortcut to analyze., Shortcuts (\*.lnk) if file = return FileGetShortcut, %file%, OutTarget, OutDir, OutArgs, OutDesc, OutIcon, OutIconNum, OutRunState MsgBox %OutTarget%\`n%OutDir%\`n%OutArgs%\`n%OutDesc%\`n%OutIcon%\`n%OutIconNum%\`n%OutRunState% ``` -------------------------------- ### Example: Toggle a Hotstring Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/Hotstring.htm This example illustrates toggling the enabled/disabled state of a hotstring. ```AutoHotkey Hotstring("::btw", "", "Toggle") ``` -------------------------------- ### Example: Execute a Function on Hotstring Trigger Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/Hotstring.htm This example creates a hotstring that triggers a specified function. ```AutoHotkey Hotstring("::myhotstring", "MyFunction", "X") ``` -------------------------------- ### Advanced ListView Example with Icons and Context Menu Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/ListView.htm A comprehensive example demonstrating how to create a ListView, populate it with file information, assign icons, and implement a context menu for file operations. It includes setting up ImageLists and handling user interactions. ```autohotkey Gui +Resize Gui, Add, Button, Default gButtonLoadFolder, Load a folder Gui, Add, Button, x+20 gButtonClear, Clear List Gui, Add, Button, x+20, Switch View Gui, Add, ListView, xm r20 w700 vMyListView gMyListView, Name|In Folder|Size (KB)|Type LV_ModifyCol(3, "Integer") ; For sorting, indicate that the Size column is an integer. ImageListID1 := IL_Create(10) ImageListID2 := IL_Create(10, 10, true) ; A list of large icons to go with the small ones. LV_SetImageList(ImageListID1) LV_SetImageList(ImageListID2) Menu, MyContextMenu, Add, Open, ContextOpenFile Menu, MyContextMenu, Add, Properties, ContextProperties Menu, MyContextMenu, Add, Clear from ListView, ContextClearRows Menu, MyContextMenu, Default, Open ; Make "Open" a bold font to indicate that double-click does the same thing. ``` -------------------------------- ### Get AutoHotkey Installation Path Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/Variables.htm Reads the AutoHotkey installation directory from the registry. If the registry key is not found, AhkPath will be an empty string. ```AutoHotkey RegRead InstallDir, HKLM\SOFTWARE\AutoHotkey, InstallDir AhkPath := ErrorLevel ? "" : InstallDir "\\AutoHotkey.exe" ``` -------------------------------- ### WinMove Example: SplashText Window Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/WinMove.htm An example showing how to create a SplashText window and then use WinMove to position it. ```APIDOC ## Example: SplashText Window This example creates a fixed-size popup window displaying clipboard content and then moves it to the upper-left corner. ```autohotkey SplashTextOn, 400, 300, Clipboard, The clipboard contains:\n%Clipboard% WinMove, Clipboard,, 0, 0 MsgBox, Press OK to dismiss the SplashText SplashTextOff ``` ``` -------------------------------- ### Example Subroutine with Gosub Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/Language.htm Demonstrates calling a subroutine using Gosub and returning from it. Labels are used as subroutine entry points. ```AutoHotkey gosub Label1 Label1: MsgBox %A_ThisLabel% return ``` -------------------------------- ### Basic WinWait Example Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/WinWait.htm Opens Notepad and waits for it to exist for a maximum of 3 seconds. If it times out, an error message is displayed; otherwise, Notepad is minimized. ```AutoHotkey Run, notepad.exe WinWait, Untitled - Notepad,, 3 if ErrorLevel { MsgBox, WinWait timed out. return } else WinMinimize _; Use the window found by WinWait._ ``` -------------------------------- ### RegExMatch with Starting Position Offset Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/RegExMatch.htm This example shows how to specify a starting position for the search, allowing you to find matches beyond the beginning of the string. ```APIDOC ## RegExMatch with Starting Position ### Description Initiates the regular expression search from a specified offset within the haystack string. ### Method RegExMatch(Haystack, Needle, OutputVar, Offset) ### Parameters - **Haystack** (string) - The string to search within. - **Needle** (string) - The regular expression pattern to search for. - **OutputVar** (variable, optional) - Variable to store captured subpatterns. - **Offset** (integer) - The zero-based offset within Haystack to start the search. ### Return Value - Returns the starting position of the match relative to the beginning of the Haystack string. ### Request Example ```apidoc MsgBox % RegExMatch("abc123abc456", "abc\d+",, 2) ``` ### Response #### Success Response (Position of match) - Returns the starting index (1-based) of the first match found at or after the specified offset. #### Response Example ```apidoc ; For MsgBox % RegExMatch("abc123abc456", "abc\d+",, 2) ; Returns: 7 ``` ``` -------------------------------- ### Start and Stop Repeating Action with Hotkey Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/FAQ.htm This example demonstrates a hotkey that starts and stops its own repeating action. The first press starts the loop, and the second press stops it by setting a flag that the loop checks. ```AutoHotkey #MaxThreadsPerHotkey 3 #z:: _**; Win+Z hotkey (change this hotkey to suit your preferences).**_ #MaxThreadsPerHotkey 1 if KeepWinZRunning _; This means an underlying [thread](misc/Threads.htm) is already running the loop below._ { KeepWinZRunning := false _; Signal that thread's loop to stop._ return _; End this thread so that the one underneath will resume and see the change made by the line above._ } _; Otherwise:_ KeepWinZRunning := true Loop { _**; The next four lines are the action you want to repeat (update them to suit your preferences):**_ ToolTip, Press Win-Z again to stop this from flashing. Sleep 1000 ToolTip Sleep 1000 _**; But leave the rest below unchanged.**_ if not KeepWinZRunning _; The user signaled the loop to stop by pressing Win-Z again._ break _; Break out of this loop._ } KeepWinZRunning := false _; Reset in preparation for the next press of this hotkey._ return ``` -------------------------------- ### Basic Gosub Example Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/Gosub.htm Demonstrates a simple subroutine call. The script jumps to Label1, executes its MsgBox, returns, and then continues execution after the Gosub command. ```AutoHotkey Gosub, Label1 MsgBox, The Label1 subroutine has returned (it is finished). return Label1: MsgBox, The Label1 subroutine is now running. return ``` -------------------------------- ### Example: Get Master Mute Status Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/SoundGet.htm Retrieves and displays the master mute status (ON or OFF). ```APIDOC ## Example: Get Master Mute Status ### Description Retrieves and reports the master mute setting. ### Code ```autohotkey SoundGet, master_mute, , Mute MsgBox, Master mute is currently %master_mute%. ``` ``` -------------------------------- ### Create and Use a Basic Object with a Method Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/Objects.htm Demonstrates how to create an object, assign a property, and define a method using a function reference. When calling the method, the object itself is passed as the first parameter. ```autohotkey _; Create an object. thing := {} _; Store a value. thing.foo := "bar" _; Create a method by storing a function reference. thing.test := Func("thing_test") _; Call the method. thing.test() thing_test(this) { MsgBox % this.foo } ``` -------------------------------- ### StringMid Example: Extract Left of Position Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/StringMid.htm Extracts characters to the left of the specified start position. If the start position is beyond the string length, only characters within reach of the count are extracted. ```AutoHotkey InputVar := "The Red Fox" StringMid, OutputVar, InputVar, 7, 3, L ``` -------------------------------- ### InputHook.Timeout Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/InputHook.htm Gets or sets the timeout value in seconds. A value of 0 means no timeout. The timeout period starts when Start is called and restarts if this property is assigned a value while Input is in progress. ```APIDOC ## InputHook.Timeout ### Description Gets or sets the timeout value in seconds. ### Usage ``` CurrentSeconds := InputHook.Timeout InputHook.Timeout := NewSeconds ``` ### Parameters * `NewSeconds` (float) - The timeout value in seconds. `0` indicates no timeout. ``` -------------------------------- ### Write and Read File Example Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/FileOpen.htm Demonstrates writing text to a file and then reading it back. Use `r`n for newlines when writing to ensure cross-platform compatibility. The file is opened with read access and exclusive delete sharing (`r-d`). ```AutoHotkey FileSelectFile, FileName, S16,, Create a new file: if (FileName = "") return file := FileOpen(FileName, "w") if !IsObject(file) { MsgBox Can't open "%FileName%" for writing. return } TestString := "This is a test string.\`r`n" _; When writing a file this way, use `r`n rather than `n to start a new line.வைகள் file.Write(TestString) file.Close() _; Now that the file was written, read its contents back into memory. file := FileOpen(FileName, "r-d") _; read the file ("r"), share all access except for delete ("-d") if !IsObject(file) { MsgBox Can't open "%FileName%" for reading. return } CharsToRead := StrLen(TestString) TestString := file.Read(CharsToRead) file.Close() MsgBox The following string was read from the file: %TestString% ``` -------------------------------- ### Example: Get Microphone Mute Status Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/SoundGet.htm Retrieves the microphone mute setting and checks if it is currently off. ```APIDOC ## Example: Get Microphone Mute Status ### Description Retrieves the microphone mute setting. If the microphone is not muted, a message box is displayed. ### Code ```autohotkey SoundGet, microphone_mute, Microphone, Mute if (microphone_mute = "Off") MsgBox, The microphone is not muted. ``` ``` -------------------------------- ### Basic Substring Extraction Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/SubStr.htm Example demonstrating how to extract a substring of a specific length starting from a given position. ```APIDOC ## Example: Basic Substring Extraction ### Description Retrieves a substring with a length of 3 characters at position 4. ### Code ```autohotkey MsgBox % SubStr("123abc789", 4, 3) ``` ### Result `abc` ``` -------------------------------- ### Compare Pre-release and Standard Versions Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/VerCompare.htm Demonstrates comparing pre-release version strings against standard versions and other pre-release versions. Note the return values indicating the comparison result. ```AutoHotkey MsgBox % VerCompare("2.0-a137", "2.0-a136") _; Returns 1_ ``` ```AutoHotkey MsgBox % VerCompare("2.0-a137", "2.0") _; Returns -1_ ``` ```AutoHotkey MsgBox % VerCompare("10.2-beta.3", "10.2.0") _; Returns -1_ ``` -------------------------------- ### Example: Get Master Volume Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/SoundGet.htm Retrieves and displays the master volume percentage of the default sound device. ```APIDOC ## Example: Get Master Volume ### Description Retrieves and reports the master volume. ### Code ```autohotkey SoundGet, master_volume MsgBox, Master volume is %master_volume% percent. ``` ``` -------------------------------- ### Run Multiple Websites Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/Tutorial.htm Demonstrates running different websites using the Run command. ```AutoHotkey Run, https://www.autohotkey.com ``` ```AutoHotkey Run, https://www.google.com ``` -------------------------------- ### Get Primary Monitor Number Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/SysGet.htm Retrieves the number of the primary monitor. In a single-monitor setup, this will always be 1. ```AutoHotkey SysGet, OutputVar, MonitorPrimary ``` -------------------------------- ### Basic Key Remapping Examples Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/misc/Remap.htm These examples demonstrate simple remapping of one key to another. Ensure specific remappings like CapsLock toggling are placed before general ones. ```autohotkey CapsLock::Ctrl ``` ```autohotkey +CapsLock::CapsLock ``` ```autohotkey XButton2::^LButton ``` ```autohotkey RAlt::AppsKey ``` ```autohotkey RCtrl::RWin ``` ```autohotkey Ctrl::Alt ``` ```autohotkey ^x::^c ``` ```autohotkey RWin::Return ``` -------------------------------- ### StringMid Example: Extract Left with Start Beyond Length Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/StringMid.htm Demonstrates extracting characters to the left of a start position that is beyond the string's length. The output will contain characters up to the specified count from the end of the string. ```AutoHotkey InputVar := "The Red Fox" StringMid, OutputVar, InputVar, 14, 6, L ``` -------------------------------- ### Example: Wait for Notepad to be Active Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/WinWaitActive.htm Opens Notepad and waits for it to become the active window for a maximum of 2 seconds. If it times out, an error message is displayed; otherwise, the window is minimized. ```autohotkey Run, notepad.exe WinWaitActive, Untitled - Notepad,, 2 if ErrorLevel { MsgBox, WinWait timed out. return } else WinMinimize _; Use the window found by WinWaitActive._ ``` -------------------------------- ### StringMid Example: Extract Substring Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/StringMid.htm Retrieves a substring with a specified length from a given position in a string. The starting position is 1-based. ```AutoHotkey Source := "Hello this is a test." StringMid, the_word_this, Source, 7, 4 ``` -------------------------------- ### InputHook.Input Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/InputHook.htm Gets any text collected since the last time Input was started. This property can be used while the Input is in progress, or after it has ended. ```APIDOC ## InputHook.Input Gets any text collected since the last time Input was started. String := InputHook.Input This property can be used while the Input is in progress, or after it has ended. ``` -------------------------------- ### ControlGet, List Sub-command Example Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/ControlGet.htm Example demonstrating how to retrieve all entries from a list box, combo box, or drop-down list using the 'List' sub-command and then parse them. ```APIDOC ## ControlGet, List ### Description Retrieves a list of entries/rows from a list box, combo box, drop-down list, or list-view control. ### Syntax ControlGet, OutputVar, List , Options, ControlID, WinTitle, WinText, ExcludeTitle, ExcludeText ### Usage for List Box, Combo Box, and Drop-Down List * The _Options_ parameter is ignored. * All text in the control is retrieved. * Each entry except the last is terminated by a linefeed character (\`n). ### Example ```autohotkey ; Assume ComboBox1 is a ComboBox control ControlGet, Entries, List,, ComboBox1, WinTitle Loop, Parse, Entries, `n MsgBox Entry number %A_Index% is %A_LoopField% ``` ### Parameters * **OutputVar**: The name of the variable to store the retrieved list. * **SubCommand**: Must be 'List'. * **Options**: Ignored for List Box, Combo Box, and Drop-Down List. * **ControlID**: The identifier for the target control (e.g., ComboBox1). * **WinTitle**: The title of the window containing the control. * **WinText**: Optional text to further identify the window. * **ExcludeTitle**: Optional title to exclude. * **ExcludeText**: Optional text to exclude. ``` -------------------------------- ### Substring Extraction from Beginning and End Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/SubStr.htm Examples showing how to extract substrings from the beginning and end of a string using positive and negative starting positions. ```APIDOC ## Example: Substring Extraction from Beginning and End ### Description Retrieves a substring from the beginning and end of a string. ### Code ```autohotkey String := "The Quick Brown Fox Jumps Over the Lazy Dog" MsgBox % SubStr(String, 1, 19) _; Returns "The Quick Brown Fox"_ MsgBox % SubStr(String, -7) _; Returns "Lazy Dog"_ ``` ### Result `The Quick Brown Fox` `Lazy Dog` ``` -------------------------------- ### #InstallKeybdHook Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/index.htm Forces the unconditional installation of the keyboard hook. ```APIDOC ## #InstallKeybdHook ### Description Forces the unconditional installation of the keyboard hook. ### Method Not specified (typically a directive in AutoHotkey script) ### Endpoint Not applicable (scripting directive) ### Parameters Not specified in the provided text. ### Request Example Not applicable. ### Response Not specified. ``` -------------------------------- ### Get Numeric System Value Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/SysGet.htm Retrieves a specific numeric system value by its corresponding number. For example, retrieving the number of mouse buttons. ```AutoHotkey SysGet, MouseButtonCount, 43 ``` -------------------------------- ### Tilde Prefix Hotkey Examples Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/Hotkeys.htm Shows how the tilde prefix allows the native function of a key to be sent to the active window when the hotkey fires. The second example demonstrates combining the tilde prefix with key combinations. ```AutoHotkey ~RButton::MsgBox You clicked the right mouse button. ``` ```AutoHotkey ~RButton & C::MsgBox You pressed C while holding down the right mouse button. ``` -------------------------------- ### Example: Get Bass Level with Error Handling Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/SoundGet.htm Attempts to retrieve the bass level for the master component and displays an error message if it fails. ```APIDOC ## Example: Get Bass Level with Error Handling ### Description Retrieves and reports the master bass level if possible, otherwise an error message is displayed. ### Code ```autohotkey SoundGet, bass_level, Master, Bass if ErrorLevel MsgBox, Error description: %ErrorLevel% else MsgBox, The BASS level for MASTER is %bass_level% percent. ``` ``` -------------------------------- ### Create and Launch Internet Explorer Instance Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/ComObjCreate.htm Launches an instance of Internet Explorer, makes it visible, and navigates to a specified website. Note that visibility settings may not work correctly on IE7. ```AutoHotkey ie := ComObjCreate("InternetExplorer.Application") ie.Visible := true _; This is known to work incorrectly on IE7._ ie.Navigate("https://www.autohotkey.com/") ``` -------------------------------- ### Create and Populate ListView with Files Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/ListView.htm Creates a ListView with 'Name' and 'Size (KB)' columns, populates it with files from 'My Documents', and sets up a 'DoubleClick' handler. Use this to display file system information in a GUI. ```AutoHotkey Gui, Add, ListView, r20 w700 gMyListView, Name|Size (KB) Loop, %A_MyDocuments%\ LV_Add("", A_LoopFileName, A_LoopFileSizeKB) LV_ModifyCol() ; Auto-size each column to fit its contents. LV_ModifyCol(2, "Integer") ; For sorting purposes, indicate that column 2 is an integer. Gui, Show return MyListView: if (A_GuiEvent = "DoubleClick") { LV_GetText(RowText, A_EventInfo) ; Get the text from the row's first field. ToolTip You double-clicked row number %A_EventInfo%. Text: "%RowText%" } return GuiClose: ExitApp ``` -------------------------------- ### Get InputHook Input Text Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/InputHook.htm Retrieves any text collected since the last time Input was started. This can be used while Input is in progress or after it has ended. ```autohotkey String := InputHook.Input ``` -------------------------------- ### Get Character String from Code - AutoHotkey Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/Chr.htm Returns the string corresponding to the character code 116. This is a basic usage example of the Chr() function. ```AutoHotkey MsgBox % Chr(116) ; Reports "t". ``` -------------------------------- ### Pre-loading and Reusing Images in a Slideshow Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/LoadPicture.htm This example pre-loads multiple JPG images from a specified directory and displays them in a GUI window, cycling through them at a set interval. It demonstrates efficient image handling for dynamic content. ```AutoHotkey Pics := [] _; Find some pictures to display._ Loop, Files, %A_WinDir%\Web\Wallpaper\*.jpg, R { _; Load each picture and add it to the array._ Pics.Push(LoadPicture(A_LoopFileFullPath)) } if !Pics.Length() { _; If this happens, edit the path on the Loop line above._ MsgBox, No pictures found! Try a different directory. ExitApp } _; Add the picture control, preserving the aspect ratio of the first picture._ Gui, Add, Pic, w600 h-1 vPic +Border, % "HBITMAP:\*" Pics.1 Gui, Show Loop { _; Switch pictures!_ GuiControl, , Pic, % "HBITMAP:\*" Pics[Mod(A_Index, Pics.Length())+1] Sleep 3000 } return GuiClose: GuiEscape: ExitApp ``` -------------------------------- ### Example: Using Numeric OnOffToggle (v1.1.30+) Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/Hotstring.htm Demonstrates using numeric values (1 for On, 0 for Off, -1 for Toggle) to control the hotstring state, available in v1.1.30 and later. ```AutoHotkey Hotstring("::btw", "", 1) ; Enable Hotstring("::btw", "", 0) ; Disable Hotstring("::btw", "", -1) ; Toggle ``` -------------------------------- ### Basic RegExMatch Usage Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/RegExMatch.htm This example demonstrates the basic usage of RegExMatch to find a substring matching a regular expression and returns the starting position of the match. ```APIDOC ## Basic RegExMatch ### Description Finds the first occurrence of a regular expression pattern within a string. ### Method RegExMatch(Haystack, Needle [, OutputVar, Offset, Limit]) ### Parameters - **Haystack** (string) - The string to search within. - **Needle** (string) - The regular expression pattern to search for. - **OutputVar** (variable, optional) - If provided, this variable will store captured subpatterns. - **Offset** (integer, optional) - The zero-based offset within Haystack at which to begin the search. Defaults to 0. - **Limit** (integer, optional) - The maximum number of matches to find. Defaults to 1. ### Return Value - Returns the starting position of the first match found, or 0 if no match is found. ### Request Example ```apidoc MsgBox % RegExMatch("xxxabc123xyz", "abc.*xyz") ``` ### Response #### Success Response (Position of match) - Returns the starting index (1-based) of the first match. #### Response Example ```apidoc ; For MsgBox % RegExMatch("xxxabc123xyz", "abc.*xyz") ; Returns: 4 ``` ``` -------------------------------- ### FormatTime - Basic Usage Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/FormatTime.htm Demonstrates the default behavior of FormatTime for current date and time, and how to specify date-first or time-first output. ```autohotkey FormatTime, TimeString MsgBox The current time and date (time first) is %TimeString%. ``` ```autohotkey FormatTime, TimeString, R MsgBox The current time and date (date first) is %TimeString%. ``` -------------------------------- ### End-of-line Comment Example Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/Language.htm Add comments at the end of a command line by placing a semicolon after at least one space or tab. The semicolon signifies the start of the comment. ```autohotkey Run Notepad _; This is a comment on the same line as a command._ ``` -------------------------------- ### Get Active Track Number from Winamp Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/PostMessage.htm Asks Winamp which track number is currently active. Adjusts the result as Winamp's count starts at 0. ```AutoHotkey SetTitleMatchMode, 2 SendMessage, 0x0400, 0, 120,, - Winamp if (ErrorLevel != "FAIL") { ErrorLevel++ _; Winamp's count starts at "0", so adjust by 1._ MsgBox, Track #%ErrorLevel% is active or playing. } ``` -------------------------------- ### Get Free Space for C Drive - AutoHotkey Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/DriveSpaceFree.htm Retrieves the free disk space of the C drive and stores it in the FreeSpace variable. This is a basic usage example. ```AutoHotkey DriveSpaceFree, FreeSpace, C:\\ ``` -------------------------------- ### Basic Conditional Hotkeys and Hotstrings Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/_IfWinActive.htm This example sets up hotkeys and a hotstring that are active only when Notepad is the active window, and a fallback hotkey for other windows. ```AutoHotkey #IfWinActive ahk_class Notepad ^!a::MsgBox You pressed Ctrl-Alt-A while Notepad is active. _; This hotkey will have no effect if pressed in other windows (and it will "pass through")._ #c::MsgBox You pressed Win-C while Notepad is active. ::btw::This replacement text for "btw" will occur only in Notepad. #IfWinActive #c::MsgBox You pressed Win-C in a window other than Notepad. ``` -------------------------------- ### Get ListView column widths using SendMessage Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/ListView.htm This example shows how to retrieve the width of each column in a ListView using the LVM_GETCOLUMNWIDTH message. It loops through the columns and displays each width. ```autohotkey Gui +LastFound Loop % LV_GetCount("Column") { SendMessage, 0x101D, A_Index - 1, 0, SysListView321 _; 0x101D is LVM_GETCOLUMNWIDTH._ MsgBox Column %A_Index%'s width is %ErrorLevel%. } ``` -------------------------------- ### Analyze Selected Drive Properties Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/DriveGet.htm This example allows a user to select a drive and then retrieves and displays various properties of that drive, including its type, status, capacity, free space, file system, volume label, and serial number. ```autohotkey FileSelectFolder, folder,, 3, Pick a drive to analyze: if not folder return DriveGet, list, List DriveGet, cap, Capacity, %folder% DriveSpaceFree, free, %folder% DriveGet, fs, FileSystem, %folder% DriveGet, label, Label, %folder% DriveGet, serial, Serial, %folder% DriveGet, type, Type, %folder% DriveGet, status, Status, %folder% MsgBox All Drives: %list%`nSelected Drive: %folder%`nDrive Type: %type%`nStatus: %status%`nCapacity: %cap% M`nFree Space: %free% M`nFilesystem: %fs%`nVolume Label: %label%`nSerial Number: %serial% ``` -------------------------------- ### Get Current Winamp Track Number Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/misc/Winamp.htm Retrieve the current track number playing in Winamp. Adjusts the returned value as Winamp's track count starts from 0. ```AutoHotkey [SendMessage](../lib/PostMessage.htm), 0x0400, 0, 120,, ahk_class Winamp v1.x if (ErrorLevel != "FAIL") { ErrorLevel += 1 _; Winamp's count starts at 0, so adjust by 1._ MsgBox, Track #%ErrorLevel% is active or playing. } ``` -------------------------------- ### Asc() Function Usage Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/Asc.htm Demonstrates how to use the Asc() function to get the numeric value of the first character in a string. Both examples show the same result as Asc() only considers the first character. ```APIDOC ## Asc() Function ### Description Returns the numeric value of the first byte or UTF-16 code unit in the specified string. ### Syntax Number := Asc(String) ### Parameters #### String - **String** (string) - The string whose numeric value is retrieved. ### Return Value - Returns a numeric value in the range 0 to 255 (for ANSI) or 0 to 0xFFFF (for Unicode). Returns 0 if the string is empty. ### Remarks - This function is equivalent to `Transform, OutputVar, Asc`. - For Unicode supplementary characters, use `Ord(String)` instead. ### Examples ```autohotkey MsgBox, % Asc("t") MsgBox, % Asc("test") ``` ### Related - [Transform](Transform.htm) - [Ord()](Ord.htm) - [Chr()](Chr.htm) ``` -------------------------------- ### Example: Change Active Window Title Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/WinSetTitle.htm This example shows how to open Notepad, wait for it to become active, and then change its title using the last found window. ```APIDOC ## Example: Change Active Window Title Opens Notepad, waits until it is active and changes its title. This example may fail on Windows 11 or later, as it requires the classic version of Notepad. ```autohotkey Run, notepad.exe WinWaitActive, Untitled - Notepad WinSetTitle, This is a new title ; Use the window found by WinWaitActive. ``` ``` -------------------------------- ### Create a Progress Bar Overlay Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/Gui.htm This example shows how to create a progress bar and overlay it on a background image. The progress bar's value and text can be updated dynamically, for instance, to show file processing status. ```AutoHotkey 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 ``` -------------------------------- ### InputHook.MinSendLevel Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/InputHook.htm Gets or sets the minimum send level of input to collect. Events with a send level lower than this value are ignored. For example, a value of 101 ignores all input generated by SendEvent. ```APIDOC ## InputHook.MinSendLevel ### Description Gets or sets the minimum send level of input to collect. ### Usage ``` CurrentLevel := InputHook.MinSendLevel InputHook.MinSendLevel := NewLevel ``` ### Parameters * `NewLevel` (integer) - An integer between 0 and 101. Events with a send level lower than this value are ignored. `SendInput` and `SendPlay` are always ignored. ``` -------------------------------- ### #InstallMouseHook Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/index.htm Forces the unconditional installation of the mouse hook. ```APIDOC ## #InstallMouseHook ### Description Forces the unconditional installation of the mouse hook. ### Method Not specified (typically a directive in AutoHotkey script) ### Endpoint Not applicable (scripting directive) ### Parameters Not specified in the provided text. ### Request Example Not applicable. ### Response Not specified. ``` -------------------------------- ### Hexadecimal Formatting Examples Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/Format.htm Illustrates different hexadecimal formatting options, including prefixes and case variations. ```autohotkey s .= Format("{1:#x} {2:X} 0x{3:x} ", 3735928559, 195948557, 0) ``` -------------------------------- ### Get Active Tab Page Index Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/ControlGet.htm Use ControlGet with the 'Tab' option to retrieve the index of the currently active page in a tab control. The index starts at 1 for the first page. ```AutoHotkey ControlGet, OutputVar, Tab ,, ControlID, WinTitle, WinText, ExcludeTitle, ExcludeText ``` -------------------------------- ### Create Directory with FileCreateDir Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/FileCreateDir.htm This example demonstrates creating a new directory. The command will automatically create any parent directories if they are missing. ```autohotkey FileCreateDir, C:\Test1\My Images\Folder2 ``` -------------------------------- ### Convert Unicode to UTF-8 String for Clipboard Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/Transform.htm This example demonstrates how to get the UTF-8 string representation of Unicode text on the clipboard, which can then be used to reconstruct the Unicode text later. It uses a hotkey to trigger the conversion. ```AutoHotkey ^!u:: MsgBox Copy some Unicode text onto the clipboard, then return to this window and press OK to continue. Transform, ClipUTF, Unicode Clipboard := "Transform, Clipboard, Unicode, %ClipUTF%\`r\n" MsgBox The clipboard now contains the following line that you can paste into your script. When executed, this line will cause the original Unicode string you copied to be placed onto the clipboard:`n`n%Clipboard% return ``` -------------------------------- ### Create a Simple Image Viewer Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/Gui.htm Build a basic image viewer that allows users to load images and choose between displaying them at actual size or fitting them to the screen. The window can be resized to match the image dimensions. ```AutoHotkey 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 not 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 ``` -------------------------------- ### Get Long Path Name from Command Line Parameters Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/LoopFile.htm This example shows how to retrieve the long, case-corrected path name for files passed as command-line parameters using the Loop command and A_LoopFileLongPath variable. ```AutoHotkey Loop %0% _; For each file dropped onto the script (or passed as a parameter)._ { GivenPath := %A_Index% _; Retrieve the next command line parameter._ Loop %GivenPath%, 1 LongPath := A_LoopFileLongPath MsgBox The case-corrected long path name of file`n%GivenPath%`nis:`n%LongPath% ``` -------------------------------- ### Create a Simple TreeView Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/TreeView.htm Demonstrates the basic syntax for creating a TreeView control and adding parent and child items. Includes a Gui, Show command to display the window and an ExitApp command for script termination. ```AutoHotkey Gui, Add, TreeView P1 := TV_Add("First parent") P1C1 := TV_Add("Parent 1's first child", P1) _; Specify P1 to be this item's parent._ P2 := TV_Add("Second parent") P2C1 := TV_Add("Parent 2's first child", P2) P2C2 := TV_Add("Parent 2's second child", P2) P2C2C1 := TV_Add("Child 2's first child", P2C2) Gui, Show _; Show the window and its TreeView._ return GuiClose: _; Exit the script when the user closes the TreeView's GUI window._ ExitApp ``` -------------------------------- ### Retrieve Active Window Stats Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/WinGetActiveStats.htm This example demonstrates how to use WinGetActiveStats to get the title, width, height, and position of the currently active window and display them in a message box. Ensure the output variables are correctly named. ```AutoHotkey WinGetActiveStats, Title, Width, Height, X, Y MsgBox, The active window "%Title%" is %Width% wide`, %Height% tall`, and positioned at %X%`,%Y%. ``` -------------------------------- ### Set Process Priority (Example) Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/Thread.htm This example demonstrates how to change the OS's priority level for the entire script using Process, Priority. This is a related but distinct command from setting individual thread priorities. ```autohotkey Process, Priority,, High ``` -------------------------------- ### Retrieve Text from Main Window Edit Control Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/ControlGetText.htm Retrieves and reports the current text from the main window's edit control. This example uses WinWaitActive to ensure the window is ready before attempting to get the text. ```autohotkey ListVars WinWaitActive ahk_class AutoHotkey ControlGetText, OutputVar, Edit1 _; Use the window found above._ MsgBox % OutputVar ``` -------------------------------- ### Selecting a Menu Item by Name Source: https://github.com/autohotkey/autohotkeydocs/blob/v1/docs/lib/WinMenuSelectItem.htm This example demonstrates how to select the 'Open' item from the 'File' menu in Notepad. ```APIDOC ## WinMenuSelectItem ### Description Selects a menu item from a window's menu bar. ### Syntax ```autohotkey WinMenuSelectItem, WinTitle, WinText, Menu, SubMenu... ``` ### Parameters * **WinTitle**: The title of the window. * **WinText**: The text of the window. * **Menu**: The name of the top-level menu item. * **SubMenu...**: One or more sub-menu item names, separated by the `&` character if needed. ### Example ```autohotkey WinMenuSelectItem, Untitled - Notepad,, File, Open ``` ```