### Make Classic Start Menu Transparent Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/WinSetTransparent.htm This example makes the classic Start Menu transparent. Ensure hidden windows are detected if necessary. ```AutoHotkey DetectHiddenWindows True WinSetTransparent 150, "ahk_class BaseBar" ``` -------------------------------- ### Run a Basic AutoHotkey Script Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/howto/RunExamples.htm This is a simple 'Hello, world!' example that can be run as-is to demonstrate its effect. It requires no special setup. ```autohotkey MsgBox "Hello, world!" ``` -------------------------------- ### Write to Registry (Example) Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/Scripts.htm This line demonstrates writing a string value to the registry. Ensure AutoHotkey is installed for expected behavior. ```AutoHotkey RegWrite cmd, "REG_SZ", "HKCU\Software\Classes\" key ``` -------------------------------- ### Start InputHook Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/InputHook.htm Starts collecting input. This method installs the keyboard hook if it's not already active and places the new InputHook on top of the stack. ```autohotkey InputHookObj.Start() ``` -------------------------------- ### Direct Installation to Destination Directory Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/Program.htm Use this command to install AutoHotkey directly to a specified destination directory. This can be done using either the setup executable or extracted files. ```batch AutoHotkey_setup.exe /installto "%DESTINATION%" ``` ```batch AutoHotkey32.exe UX\install.ahk /to "%DESTINATION%" ``` -------------------------------- ### HotIfWinActive Example Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/HotIf.htm This example demonstrates using HotIfWinActive to create hotkeys and hotstrings that only work when Notepad is active. ```APIDOC ## HotIfWinActive Example ### Description Creates context-sensitive hotkeys and hotstrings that are active only when a specific window (e.g., Notepad) is active. ### Method Function Call ### Endpoint N/A (Function Call) ### Parameters - **WinTitle** (String) - Criteria for the target window (e.g., "ahk_class Notepad"). ### Request Example ```apidoc HotIfWinActive "ahk_class Notepad" Hotkey "^!a", ShowMsgBox Hotkey "#c", ShowMsgBox Hotstring "::btw", "This replacement text will occur only in Notepad." HotIfWinActive Hotkey "#c", (\*)=> MsgBox("You pressed Win-C in a window other than Notepad.") ShowMsgBox(HotkeyName) { MsgBox "You pressed " HotkeyName " while Notepad is active." } ``` ### Response N/A (Function Call) ``` -------------------------------- ### Start Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/InputHook.htm Starts collecting input for the InputHook. ```APIDOC ## InputHookObj.Start() ### Description Starts collecting input. Has no effect if the Input is already in progress. The newly started Input is placed on the top of the [InputHook stack](#stack), which allows it to override any previously started Input. This method installs the [keyboard hook](InstallKeybdHook.htm) (if it was not already). ``` -------------------------------- ### Example: Enabling Hidden Window Detection Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/DetectHiddenWindows.htm This example demonstrates how to enable the detection of hidden windows using the DetectHiddenWindows function. ```APIDOC ```apidoc DetectHiddenWindows true ``` ``` -------------------------------- ### Example: Evaluate Expression as New Script Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/Run.htm An example demonstrating the ExecScript function by taking user input for an expression, appending it to a temporary script file, and executing it. ```AutoHotkey ; Example: ib := InputBox("Enter an expression to evaluate as a new script.",,, 'Ord("*")') if ib.result = "Cancel" return result := ExecScript('FileAppend ' ib.value ', "*") MsgBox "Result: " result ``` -------------------------------- ### HotIf with Callback Example Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/HotIf.htm This example shows how to use HotIf with a callback function to dynamically determine the context for hotkeys and hotstrings. ```APIDOC ## HotIf with Callback Example ### Description Uses a callback function with HotIf to define dynamic context sensitivity for hotkeys and hotstrings. ### Method Function Call ### Endpoint N/A (Function Call) ### Parameters - **Callback Function** - A function that returns true if the context is met, false otherwise. ### Request Example ```apidoc HotIf MyCallback Hotkey "^!a", ShowMsgBox Hotkey "#c", ShowMsgBox Hotstring "::btw", "This replacement text will occur only in Notepad." HotIf Hotkey "#c", (\*)=> MsgBox("You pressed Win-C in a window other than Notepad.") MyCallback(\*) { if WinActive("ahk_class Notepad") return true else return false } ShowMsgBox(HotkeyName) { MsgBox "You pressed " HotkeyName " while Notepad is active." } ``` ### Response N/A (Function Call) ``` -------------------------------- ### For Loop Example: Listing Object Properties Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/For.htm A practical example of using a for-loop to list the properties owned by an object. ```AutoHotkey for name in ObjOwnProps(myObject) OutputVar := OutputVar name "`n" ``` -------------------------------- ### Loop File Example Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/LoopFiles.htm Example demonstrating how to retrieve the short path name of a file using the Loop Files command. ```APIDOC ## Example Usage To retrieve the complete 8.3 path and name for a single file or folder: ```autohotkey Loop Files, "C:\My Documents\Address List.txt" ShortPathName := A_LoopFileShortPath ``` ``` -------------------------------- ### Return Expression Examples Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/Return.htm Demonstrates various valid expressions that can be returned from a function. The 'return true' example returns the number 1 to signify true. ```AutoHotkey return 3 ``` ```AutoHotkey return "literal string" ``` ```AutoHotkey return MyVar ``` ```AutoHotkey return i + 1 ``` ```AutoHotkey return true _; Returns the number 1 to mean "true". ``` ```AutoHotkey return ItemCount < MaxItems _; Returns a true or false value. ``` ```AutoHotkey return FindColor(TargetColor) ``` -------------------------------- ### Hotkey Examples with Actions Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/Tutorial.htm Examples of hotkeys that perform actions like running programs or sending keystrokes. Comments explain the purpose of each hotkey and its associated action. ```AutoHotkey ^n:: _; CTRL+N hotkey_ { Run "notepad.exe" _; Run Notepad when you press CTRL+N._ } _; This ends the hotkey. The code below this will not be executed when pressing the hotkey._ ``` ```AutoHotkey ^b:: _; CTRL+B hotkey_ { Send "{Ctrl down}c{Ctrl up}" _; Copies the selected text. ^c could be used as well, but this method is more secure._ SendInput "[b]{Ctrl down}v{Ctrl up}[/b]" _; Wraps the selected text in BBCode tags to make it bold in a forum._ } _; This ends the hotkey. The code below this will not be executed when pressing the hotkey._ ``` -------------------------------- ### Install Additional Version from Source Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/Program.htm Installs AutoHotkey as an additional version from a specified source directory. The source directory should contain AutoHotkey*.exe files. Adjust the path to AutoHotkey32.exe as necessary. ```batch AutoHotkey32.exe UX\install.ahk /install "%SOURCE%" ``` -------------------------------- ### Example: Activating a Window Based on Existence Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/WinExist.htm Demonstrates how to use WinExist to check for the existence of either Notepad or another window identified by a variable, and then activate the found window. ```APIDOC ## Example: Activating a Window Based on Existence ### Description Activates either Notepad or another window, depending on which of them was found by the WinExist functions above. Note that the space between an "ahk_" keyword and its criterion value can be omitted; this is especially useful when using variables, as shown by the second WinExist. ### Code ```apidoc if WinExist("ahk_class Notepad") or WinExist("ahk_class" ClassName) WinActivate _ ``` ### Notes - The underscore `_` in `WinActivate _` refers to the window found by the preceding `WinExist` function. ``` -------------------------------- ### Class Initialization Order Example Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/Objects.htm Demonstrates the initialization order of two interdependent classes, A and B, highlighting potential issues with circular references and undefined properties during script startup. ```AutoHotkey class A { static SharedArray := B.SharedArray _; A1 ; B3_ static SharedValue := 42 _; B4_ } class B { static SharedArray := StrSplit("XYZ") _; A2 ; B1_ static SharedValue := A.SharedValue _; A3 (Error) ; B2_ } ``` -------------------------------- ### Timeout Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/InputHook.htm Gets or sets the timeout value in seconds. A value of 0 means no timeout. The timeout period ordinarily starts when Start is called, but will restart if this property is assigned a value while Input is in progress. ```APIDOC ## Timeout ### Description Gets or sets the timeout value in seconds. ### Method GET/SET ### Endpoint InputHookObj.Timeout ### Parameters #### Set Parameters - **NewSeconds** (float) - Description: A floating-point number representing the timeout in seconds. 0 means no timeout. ### Response #### Success Response (GET) - **CurrentSeconds** (float) - The current timeout value in seconds. ``` -------------------------------- ### Example: Minimize and Restore Windows Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/WinMinimizeAll.htm Demonstrates how to use WinMinimizeAll and WinMinimizeAllUndo to temporarily minimize all windows for a specified duration. ```APIDOC ## Example: Minimize and Restore Windows ### Description This example minimizes all windows for 1 second and then restores them. ### Code ```autohotkey WinMinimizeAll Sleep 1000 WinMinimizeAllUndo ``` ``` -------------------------------- ### Capacity Property Example Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/Array.htm Demonstrates getting and setting the capacity of an array. Setting a capacity less than the current length truncates the array. ```AutoHotkey MaxItems := ArrayObj.Capacity ArrayObj.Capacity := MaxItems ``` -------------------------------- ### FileInstall Example - Include and Extract File Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/FileInstall.htm Includes a text file within the compiled script and extracts it to another location with a different name upon execution. Existing files at the destination will be overwritten. ```AutoHotkey FileInstall "My File.txt", A_Desktop "\Example File.txt", 1 ``` -------------------------------- ### Tray Menu Example Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/Menu.htm Demonstrates managing the system tray menu using the Menu object. ```APIDOC ## Tray Menu Management ### Description This example demonstrates how to manipulate the system tray menu, including deleting default items, adding custom items, and using various management methods. ### Methods Used - **A_TrayMenu**: Accesses the system tray menu object. - **Delete()**: Deletes menu items. - **Add(Name, Handler)**: Adds menu items. - **ToggleCheck(ItemName)**: Toggles check state. - **ToggleEnable(ItemName)**: Toggles enabled state. - **Default := "ItemName"**: Sets the default item. - **AddStandard()**: Adds standard items. - **Rename(OldName, NewName)**: Renames items. ### Example Code ```autohotkey #SingleInstance Persistent Tray := A_TrayMenu Tray.Delete() ; Delete the standard items Tray.Add() ; separator Tray.Add("TestToggleCheck", TestToggleCheck) Tray.Add("TestToggleEnable", TestToggleEnable) Tray.Add("TestDefault", TestDefault) Tray.Add("TestAddStandard", TestAddStandard) Tray.Add("TestDelete", TestDelete) Tray.Add("TestDeleteAll", TestDeleteAll) Tray.Add("TestRename", TestRename) Tray.Add("Test", Test) TestToggleCheck(*) { Tray.ToggleCheck("TestToggleCheck") Tray.Enable("TestToggleEnable") Tray.Add("TestDelete", TestDelete) } TestToggleEnable(*) { Tray.ToggleEnable("TestToggleEnable") } TestDefault(*) { if Tray.Default = "TestDefault" Tray.Default := "" else Tray.Default := "TestDefault" } TestAddStandard(*) { Tray.AddStandard() } TestDelete(*) { Tray.Delete("TestDelete") } TestDeleteAll(*) { Tray.Delete() } TestRename(*) { static OldName := "", NewName := "" if NewName != "renamed" { OldName := "TestRename" NewName := "renamed" } else { OldName := "renamed" NewName := "TestRename" } Tray.Rename(OldName, NewName) } Test(Item, *) { MsgBox("You selected " Item) } ``` ``` -------------------------------- ### Advanced ListView Example with File Display Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/ListView.htm This example demonstrates creating a GUI with a ListView to display files from a user-selected folder, including icons, file sizes, and types. It also includes event handling for double-clicking files, context menus, and GUI resizing. ```AutoHotkey ; Create a GUI window: MyGui := Gui("+Resize") ; Allow the user to maximize or drag-resize the window. ; Create some buttons: B1 := MyGui.Add("Button", "Default", "Load a folder") B2 := MyGui.Add("Button", "x+20", "Clear List") B3 := MyGui.Add("Button", "x+20", "Switch View") ; Create the ListView and its columns: LV := MyGui.Add("ListView", "xm r20 w700", ["Name", "In Folder", "Size (KB)", "Type"]) LV.ModifyCol(3, "Integer") ; For sorting, indicate that the Size column is an integer. ; Create an ImageList so that the ListView can display some icons: ImageListID1 := IL_Create(10) ImageListID2 := IL_Create(10, 10, true) ; A list of large icons to go with the small ones. ; Attach the ImageLists to the ListView so that it can later display the icons: LV.SetImageList(ImageListID1) LV.SetImageList(ImageListID2) ; Apply control events: LV.OnEvent("[DoubleClick](GuiOnEvent.htm#DoubleClick)", RunFile) LV.OnEvent("[ContextMenu](GuiOnEvent.htm#Ctrl-ContextMenu)", ShowContextMenu) B1.OnEvent("Click", LoadFolder) B2.OnEvent("Click", (\*)=> LV.Delete()) B3.OnEvent("Click", SwitchView) ; Apply window events: MyGui.OnEvent("Size", Gui_Size) ; Create a popup menu to be used as the context menu: ContextMenu := Menu() ``` -------------------------------- ### Disable Left Win Key Activation of Start Menu Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/A_MenuMaskKey.htm This example demonstrates how to prevent the left Win key from activating the Start Menu while still allowing it to be used as a modifier. It sends a blind vkE8 keystroke when the left Win key is pressed. ```AutoHotkey ~LWin::Send "{Blind}{vkE8}" ``` -------------------------------- ### Basic Window Manipulation Example Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/howto/ManageWindows.htm Opens Notepad, waits for it, activates it, and then moves it to a specific screen position. This demonstrates a common workflow for interacting with application windows. ```AutoHotkey Run "notepad.exe" WinWait "Untitled - Notepad" WinActivate "Untitled - Notepad" WinMove 0, 0, A_ScreenWidth/4, A_ScreenHeight/2, "Untitled - Notepad" ``` -------------------------------- ### Length Property Example Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/Array.htm Demonstrates getting and setting the length of an array. Increasing the length adds uninitialized elements, while decreasing it truncates the array. ```AutoHotkey MsgBox ["A", "B", "C"].Length ; 3 MsgBox ["A", , "C"].Length ; 3 ``` -------------------------------- ### Retrieve Mouse Button Count Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/SysGet.htm This example demonstrates how to use SysGet with parameter 43 to get the number of mouse buttons available on the system. ```APIDOC ## Retrieve Mouse Button Count ### Description Retrieves the number of mouse buttons and stores it in MouseButtonCount. ### Method SysGet(43) ### Parameters #### Input Parameter - **43** (Integer) - Specifies to retrieve the mouse button count. ### Return Value An integer representing the number of mouse buttons. ``` -------------------------------- ### Create and Show a Basic Menu Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/Menu.htm Demonstrates creating a simple menu with a submenu, separator, and items, and showing it via a hotkey. ```autohotkey MyMenu.Add("My Submenu", Submenu1) MyMenu.Add() _; Add a separator line below the submenu._ MyMenu.Add("Item 3", MenuHandler) _; Add another menu item beneath the submenu._ MenuHandler(Item, \*) { MsgBox("You selected " Item) } #z::MyMenu.Show() _; i.e. press the Win-Z hotkey to show the menu._ ``` -------------------------------- ### Get Pixel Color at Mouse Cursor - AutoHotkey v2 Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/PixelGetColor.htm This example demonstrates how to get the color of the pixel under the current mouse cursor position when a hotkey is pressed. It uses MouseGetPos to find the cursor coordinates and then PixelGetColor to retrieve the color, displaying it in a message box. ```AutoHotkey ^!z:: _; Control+Alt+Z hotkey. { MouseGetPos &MouseX, &MouseY MsgBox "The color at the current cursor position is " PixelGetColor(MouseX, MouseY) } ``` -------------------------------- ### Create an Edit Control Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/GuiControls.htm Example of creating an Edit control with specified dimensions and initial text. Omit the text parameter to start with an empty control. ```AutoHotkey MyEdit := MyGui.Add("Edit", "r9 w135", "Text to appear inside the edit control (omit this parameter to start off empty).") ``` -------------------------------- ### Hide and Show Notepad Window Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/WinHide.htm This example demonstrates opening Notepad, waiting for it to appear, hiding it briefly, and then showing it again. It uses the last found window implicitly. ```autohotkey Run "notepad.exe" WinWait "Untitled - Notepad" Sleep 500 WinHide _; Use the window found by WinWait._ Sleep 1000 WinShow _; Use the window found by WinWait._ ``` -------------------------------- ### Example: Retrieving the Active Window's HWND Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/WinExist.htm Shows how to get the unique identifier (HWND) of the currently active window using WinExist with the 'A' option. ```APIDOC ## Example: Retrieving the Active Window's HWND ### Description Retrieves and reports the [HWND](../misc/WinTitle.htm#ahk_id) of the active window. ### Code ```apidoc MsgBox "The active window's HWND is " WinExist("A") ``` ``` -------------------------------- ### Retrieve Virtual Screen Height Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/SysGet.htm This example demonstrates using SysGet with parameter 79 to get the total height of the virtual screen, encompassing all displays. ```APIDOC ## Retrieve Virtual Screen Height ### Description Retrieves the height of the virtual screen and stores it in VirtualScreenHeight. ### Method SysGet(79) ### Parameters #### Input Parameter - **79** (Integer) - Specifies to retrieve the virtual screen height. ### Return Value An integer representing the virtual screen height in pixels. ``` -------------------------------- ### Create and Populate ListView with Icons Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/ListView.htm Demonstrates creating a GUI, adding a ListView, creating an ImageList, assigning it to the ListView, and populating both the ImageList and ListView with icons. This is useful for displaying icons alongside ListView rows. ```autohotkey MyGui := Gui() LV := MyGui.Add("ListView", "h200 w180", ["Icon & Number", "Description"]) ImageListID := IL_Create(10) LV.SetImageList(ImageListID) Loop 10 IL_Add(ImageListID, "shell32.dll", A_Index) Loop 10 LV.Add("Icon" . A_Index, A_Index, "n/a") MyGui.Show() ``` -------------------------------- ### Retrieve Version of AutoHotkey Executable - AutoHotkey Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/FileGetVersion.htm This example shows how to retrieve the version of the AutoHotkey executable by dynamically locating its installation path. It relies on the A_ProgramFiles built-in variable. ```AutoHotkey Version := FileGetVersion(A_ProgramFiles "\\AutoHotkey\\AutoHotkey.exe") ``` -------------------------------- ### Write and Read File Example Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/FileOpen.htm Demonstrates writing text to a file and then reading it back. Use \`r\`n for newlines when writing to ensure compatibility. The file is opened in write mode and then reopened in read-only mode with exclusive access. ```AutoHotkey FileName := FileSelect("S16",, "Create a new file:") if (FileName = "") return try FileObj := FileOpen(FileName, "w") catch as Err { MsgBox "Can't open '" FileName "' for writing." . "\`n\`n" Type(Err) ": " Err.Message 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._ FileObj.Write(TestString) FileObj.Close() _; Now that the file was written, read its contents back into memory._ try FileObj := FileOpen(FileName, "r-d") _; read the file ("r"), share all access except for delete ("-d")_ catch as Err { MsgBox "Can't open '" FileName "' for reading." . "\`n\`n" Type(Err) ": " Err.Message return } CharsToRead := StrLen(TestString) TestString := FileObj.Read(CharsToRead) FileObj.Close() MsgBox "The following string was read from the file: " TestString ``` -------------------------------- ### RemoveAt Example (Multiple Items) Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/Array.htm Removes a range of items from an array starting at a specified index with a given length, and returns the removed value(s). Remaining items are shifted left. ```AutoHotkey x := ["A", , "C"] MsgBox x.RemoveAt(1, 2) ; 1 (blank value at index 1) MsgBox x[1] ; C ``` -------------------------------- ### Example Usage Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/IsSet.htm Demonstrates the usage of IsSet and IsSetRef for variable initialization and checking within functions. ```APIDOC ## Examples ### Basic Usage ```autohotkey Loop 2 if !IsSet(MyVar) _; Is this the first "use" of MyVar?_ MyVar := A_Index _; Initialize on first "use"._ MsgBox Function1(&MyVar) MsgBox Function2(&MyVar) Function1(&Param) _; ByRef parameter._ { if IsSet(Param) _; Pass Param itself, which is an alias for MyVar._ return Param _; ByRef parameters are automatically dereferenced._ else return "unset" } Function2(Param) { if IsSetRef(Param) _; Pass the VarRef contained by Param._ return %Param% _; Explicitly dereference Param._ else return "unset" } ``` ``` -------------------------------- ### Get Current Time and Date Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/FormatTime.htm Retrieves the current time and date in different default formats. The first example shows time first, and the second shows date first. ```AutoHotkey TimeString := FormatTime() MsgBox "The current time and date (time first) is " TimeString ``` ```AutoHotkey TimeString := FormatTime("R") MsgBox "The current time and date (date first) is " TimeString ``` -------------------------------- ### Set Timeout for WinWait Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/howto/ManageWindows.htm Prevent scripts from getting stuck indefinitely by using the optional Timeout parameter in WinWait. This example waits for a maximum of 5 seconds for the window to appear. ```AutoHotkey Run "notepad.exe",,, ¬epad_pid if WinWait("ahk_pid " notepad_pid,, 5) { WinActivate ``` -------------------------------- ### Transparency and TransColor Example Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/WinSetTransparent.htm Demonstrates the combined effects of WinSetTransparent and WinSetTransColor. Note potential interaction issues with mouse hovering over invisible pixels. ```AutoHotkey #t:: _; Press Win+T to make the color under the mouse cursor invisible._ { MouseGetPos &MouseX, &MouseY, &MouseWin MouseRGB := PixelGetColor(MouseX, MouseY) _; It seems necessary to turn off any existing transparency first:_ WinSetTransColor "Off", MouseWin WinSetTransColor MouseRGB " 220", MouseWin } ``` ```AutoHotkey #o:: _; Press Win+O to turn off transparency for the window under the mouse._ { MouseGetPos ,, &MouseWin WinSetTransColor "Off", MouseWin } ``` ```AutoHotkey #g:: _; Press Win+G to show the current settings of the window under the mouse._ { MouseGetPos ,, &MouseWin TransDegree := WinGetTransparent(MouseWin) TransColor := WinGetTransColor(MouseWin) ToolTip "Translucency:\t" TransDegree "\nTransColor:\t" TransColor } ``` -------------------------------- ### Get Primary Monitor Number - AutoHotkey v2 Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/MonitorGetPrimary.htm Call MonitorGetPrimary() to retrieve the number of the primary monitor. This function requires no parameters. In a single-monitor setup, it will always return 1. ```autohotkey Primary := MonitorGetPrimary() ``` -------------------------------- ### Activate Last Found Window (Notepad Example) Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/misc/WinTitle.htm Opens Notepad, waits for its window to appear, and then activates it using the 'Last Found Window' feature. This avoids repeating window identification parameters. ```AutoHotkey Run "Notepad" WinWait "Untitled - Notepad" WinActivate ; Use the window found by WinWait. ``` -------------------------------- ### Create and Populate TreeView with ImageList Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/TreeView.htm Demonstrates creating an ImageList, populating it with icons from a system DLL, and then creating a TreeView that uses this ImageList. Icons are referenced by name when adding items. ```AutoHotkey MyGui := Gui() ImageListID := IL_Create(10) _; Create an ImageList with initial capacity for 10 icons._ Loop 10 _; Load the ImageList with some standard system icons._ IL_Add(ImageListID, "shell32.dll", A_Index) TV := MyGui.Add("TreeView", "ImageList" . ImageListID) TV.Add("Name of Item", 0, "Icon4") _; Add an item to the TreeView and give it a folder icon._ MyGui.Show() ``` -------------------------------- ### Toggle Repeating Action with a Hotkey Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/FAQ.htm This example demonstrates how to start and stop a repeating action within a script using a single hotkey. It utilizes a static variable to maintain the state of the loop. ```AutoHotkey #MaxThreadsPerHotkey 3 #z:: { static KeepWinZRunning := false if KeepWinZRunning { KeepWinZRunning := false return } KeepWinZRunning := true Loop { ToolTip "Press Win-Z again to stop this from flashing." Sleep 1000 ToolTip Sleep 1000 if not KeepWinZRunning break } KeepWinZRunning := false } #MaxThreadsPerHotkey 1 ``` -------------------------------- ### Launch Notepad Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/howto/RunPrograms.htm Launches Notepad directly. This is an immediate execution as no hotkey is defined. ```AutoHotkey Run "C:\\Windows\\notepad.exe" ``` -------------------------------- ### Get Winamp Track Number Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/SendMessage.htm Asks Winamp for the currently active track number. Winamp's track count starts at 0, so the result is incremented by 1 for user display. ```autohotkey SetTitleMatchMode 2 TrackNumber := SendMessage(0x0400, 0, 120,, "- Winamp") TrackNumber++ _; Winamp's count starts at 0, so adjust by 1._ MsgBox "Track #" TrackNumber " is active or playing." ``` -------------------------------- ### Retrieve Transparent Color of Window Under Mouse Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/WinGetTransColor.htm This example retrieves the transparent color of the window currently under the mouse cursor. It first gets the mouse position and the window at that position, then calls WinGetTransColor with the identified window. ```AutoHotkey MouseGetPos ,, &MouseWin TransColor := WinGetTransColor(MouseWin) ``` -------------------------------- ### InputHook Constructor and Basic Usage Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/InputHook.htm Demonstrates how to create an InputHook object, start it, wait for termination, and retrieve the captured input and termination key. ```APIDOC ## InputHook Constructor ### Description Creates an InputHook object to capture user input. ### Parameters - **Options** (string) - Optional. Options to configure the InputHook, similar to the Input command's options. - **EndKeys** (string) - Optional. A list of keys that will terminate the input. - **MatchList** (string) - Optional. A list of strings to match against the input for termination. ### Usage ih := InputHook(Options, EndKeys, MatchList) ## InputHook.Start() ### Description Starts the InputHook, enabling it to capture input. ### Usage ih.Start() ## InputHook.Wait() ### Description Waits for the InputHook to be terminated by an end key, match, or other condition. Returns the termination reason. ### Return Value - **ErrorLevel** (string) - The reason for termination. Can be "EndKey", "Match", or other specific codes. If "EndKey", it can be appended with ":" followed by the specific end key pressed. ### Usage ErrorLevel := ih.Wait() ## InputHook.Input ### Description Retrieves the input captured by the InputHook up to the current point. ### Return Value - **OutputVar** (string) - The captured input string. ### Usage OutputVar := ih.Input ## InputHook.EndKey ### Description When ErrorLevel from Wait() is "EndKey", this property returns the specific key that terminated the input. ### Return Value - **EndKey** (string) - The name of the key that terminated the input. ### Usage if (ErrorLevel = "EndKey") ErrorLevel .= ":" ih.EndKey ``` -------------------------------- ### Get Previous Key Press Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/Variables.htm A_PriorKey identifies the last key pressed before the most recent key event, excluding AutoHotkey-generated input. Requires the keyboard or mouse hook to be installed and key history enabled. ```AutoHotkey MsgBox "The key pressed before the last one was: " A_PriorKey ``` -------------------------------- ### Format Function Usage Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/Format.htm Demonstrates basic usage of the Format function with positional and default index placeholders. ```autohotkey String := Format("{1:i} {2:i}", 10, 20) ; String is now "10 20" String := Format("{:i} {:i}", 10, 20) ; String is now "10 20" String := Format("{:i} {}", 10, 20) ; String is now "10 20" String := Format("{{}} {}", 10) ; String is now "{} 10" ``` -------------------------------- ### Get Monitor Coordinates with MonitorGet Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/MonitorGet.htm Use this snippet to retrieve the bounding coordinates of a specific monitor. Ensure the monitor number is valid; otherwise, an exception will be caught. This example demonstrates how to display the coordinates in a message box. ```autohotkey try { MonitorGet 2, &Left, &Top, &Right, &Bottom MsgBox "Left: " Left " -- Top: " Top " -- Right: " Right " -- Bottom: " Bottom } catch MsgBox "Monitor 2 doesn't exist or an error occurred." ``` -------------------------------- ### SplitPath - Fetching All Information Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/SplitPath.htm Demonstrates fetching all available components of a file path using SplitPath. All output variables are referenced using '&'. ```AutoHotkey SplitPath FullFileName, &name, &dir, &ext, &name_no_ext, &drive ``` -------------------------------- ### InputBox Options Example Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/v2-changes.htm Demonstrates the use of various options for the InputBox function, such as position, size, timeout, and password input. ```autohotkey InputBoxObj := InputBox("Enter password:", "Secure Input", "w300 h100 T5 Password*") ``` -------------------------------- ### Example #Requires Directive with Prefer Comment Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/Program.htm Shows how to specify interpreter preferences directly within a script using the #Requires directive. Preferences are appended as a comment starting with 'prefer' and ending with a full stop or line ending. ```autohotkey #Requires AutoHotkey v1.1.35 _; prefer 64-bit, Unicode. More comments._ ``` -------------------------------- ### Get Notepad Client Area Position if Exists Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/WinGetClientPos.htm Checks if a window titled 'Untitled - Notepad' exists. If it does, it retrieves and displays the X and Y coordinates of its client area. This example uses the output variable '_' to ignore the width and height. ```AutoHotkey if WinExist("Untitled - Notepad") { WinGetClientPos &Xpos, &Ypos _; MsgBox "Notepad's client area is at " Xpos "," Ypos } ``` -------------------------------- ### FormatTime with Current Local Date and Time Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/FormatTime.htm If the YYYYMMDDHH24MISS parameter is blank or omitted, FormatTime uses the current local date and time. This example shows how to get the current date and time formatted as 'yyyy-MM-dd HH:mm:ss'. ```AutoHotkey OutputVar := FormatTime(,"yyyy-MM-dd HH:mm:ss") ; Example Output: 2023-10-27 10:30:00 ``` -------------------------------- ### Launch Notepad and Set Priority Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/ProcessSetPriority.htm Launches Notepad, sets its priority to high, and reports its current PID. Ensure the 'Run' function is available for launching processes. ```AutoHotkey Run "notepad.exe", , , &NewPID ProcessSetPriority "High", NewPID MsgBox "The newly launched Notepad's PID is " NewPID ``` -------------------------------- ### Using LastFound with WinSetTransColor Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/Gui.htm Example demonstrating how to use `+LastFound` to set the transparency color of a GUI window before it is shown. ```autohotkey MyGui.Opt("+LastFound") WinSetTransColor(CustomColor " 150") MyGui.Show() ``` -------------------------------- ### MinSendLevel Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/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 causes all input generated by SendEvent to be ignored, while a value of 1 only ignores input at the default send level (zero). ```APIDOC ## MinSendLevel ### Description Gets or sets the minimum send level of input to collect. ### Method GET/SET ### Endpoint InputHookObj.MinSendLevel ### Parameters #### Set Parameters - **NewLevel** (integer) - Description: An integer between 0 and 101. Events which have a send level lower than this value are ignored. ### Response #### Success Response (GET) - **CurrentLevel** (integer) - The current minimum send level. ``` -------------------------------- ### Re-register Current Installation Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/Program.htm Re-registers the current AutoHotkey installation. This command should be executed from within the installation directory. ```batch AutoHotkey32.exe UX\install.ahk ``` -------------------------------- ### Open This PC Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/Run.htm Launches 'This PC' (formerly My Computer or Computer) using its CLSID. ```AutoHotkey Run "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}" ``` -------------------------------- ### FileSetAttrib Examples Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/FileSetAttrib.htm Illustrative examples of using the FileSetAttrib function. ```APIDOC ## Examples ### Turn on "read-only" and "hidden" attributes for all files and directories: FileSetAttrib "+RH", "C:\MyFiles\*.*", "DF" ### Toggle the "hidden" attribute of a single directory: FileSetAttrib "^H", "C:\MyFiles" ### Turn off "read-only" and turn on "archive" for a single file: FileSetAttrib "-R+A", "C:\New Text File.txt" ### Recurse through all .ini files and turn on their "archive" attribute: FileSetAttrib "+A", "C:\*.ini", "R" ### Copy attributes from file2 to file1: FileSetAttrib "(FileGetAttrib(file2))", "file1" ``` -------------------------------- ### Expression Statement Starting with Parentheses Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/Language.htm Expressions starting with an opening parenthesis `(` are allowed as statements, provided there is a matching closing parenthesis `)` on the same line. Otherwise, the line might be interpreted as the start of a continuation section. ```AutoHotkey (MyVar + 1) ``` -------------------------------- ### Minimize all windows for 1 second and unminimize Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/WinMinimizeAll.htm This example demonstrates minimizing all windows, pausing for 1 second, and then restoring them. Ensure WinMinimizeAll and WinMinimizeAllUndo are available in your AutoHotkey version. ```autohotkey WinMinimizeAll Sleep 1000 WinMinimizeAllUndo ``` -------------------------------- ### InStr Examples Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/InStr.htm Illustrates various use cases of the InStr function with code examples. ```APIDOC ### Examples **Basic Usage:** ```apidoc Haystack := "The Quick Brown Fox Jumps Over the Lazy Dog" Needle := "Fox" If InStr(Haystack, Needle) MsgBox "The string was found." Else MsgBox "The string was not found." ``` **Case-Insensitive and Occurrence:** ```apidoc Haystack := "The Quick Brown Fox Jumps Over the Lazy Dog" Needle := "the" MsgBox InStr(Haystack, Needle, false, 1, 2) ; case-insensitive search, return start position of second occurence MsgBox InStr(Haystack, Needle, true) ; case-sensitive search, return start position of first occurence ``` **Finding Position:** ```apidoc MsgBox InStr("123abc789", "abc") ; Returns 4 ``` ``` -------------------------------- ### Retrieve and Report GetMethod Information Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/GetMethod.htm This example demonstrates retrieving the GetMethod function itself and then querying its properties like MaxParams. It also shows that GetMethod is equivalent to GetMethod({}, "GetMethod"). ```AutoHotkey method := GetMethod({}, "GetMethod") _; It's also a method._ MsgBox method.MaxParams _; Takes 3 parameters, including 'this'._ MsgBox method = GetMethod _; Actually the same object in this case._ ``` -------------------------------- ### Example: Simple Usage Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/ComObjArray.htm A basic example demonstrating the creation and population of a one-dimensional SafeArray. ```APIDOC ## Example: Simple Usage ```apidoc arr := ComObjArray(VT_VARIANT:=12, 3) arr[0] := "Auto" arr[1] := "Hot" arr[2] := "key" t := "" Loop arr.MaxIndex() + 1 t .= arr[A_Index-1] MsgBox t ``` ``` -------------------------------- ### Calculate Folder Size Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/FileGetSize.htm This example demonstrates how to calculate the total size of a folder, including all its subfolders and files, by iterating through them and summing their sizes. ```AutoHotkey FolderSize := 0 WhichFolder := DirSelect() _; Ask the user to pick a folder._ Loop Files, WhichFolder "\*.", "R" FolderSize += A_LoopFileSize MsgBox "Size of " WhichFolder " is " FolderSize " bytes." ``` -------------------------------- ### Basic Substring Extraction Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/lib/SubStr.htm Extracts a substring of a specified length starting from a given position. The starting position is 1-based. ```AutoHotkey MsgBox SubStr("123abc789", 4, 3) ; Returns abc ``` -------------------------------- ### Open File with Program and Parameters Source: https://github.com/mike-clark-8192/autohotkeyv2docs/blob/v2/docs/howto/RunPrograms.htm Opens a specific file (license.txt) with Notepad. Assumes Notepad is in the system's PATH and the file exists in the default AutoHotkey installation directory. ```AutoHotkey Run "notepad C:\\Program Files\\AutoHotkey\\license.txt" ```