### Starting the Screen Saver Source: https://www.autohotkey.com/docs/v1/lib/PostMessage.htm This example starts the user's chosen screen saver by sending the WM_SYSCOMMAND message with the SC_SCREENSAVE parameter. ```AutoHotkey SendMessage, 0x0112, 0xF140, 0,, Program Manager _; 0x0112 is WM_SYSCOMMAND, and 0xF140 is SC_SCREENSAVE._ ``` -------------------------------- ### Install AutoHotkey with Command Line Options Source: https://www.autohotkey.com/docs/v1/FAQ.htm Use command line options for silent installation or to extract setup files. This is useful when the standard installer hangs or encounters issues. ```bash setup.exe /S ``` ```bash AutoHotkeyU32.exe Installer.ahk /S ``` -------------------------------- ### Create Installer Screen with Progress Overlay Source: https://www.autohotkey.com/docs/v1/lib/Progress.htm Demonstrates creating a professional-looking installer screen by overlaying a Progress window on a SplashImage. It iterates through files, updating the progress bar and displaying installation status. ```autohotkey if FileExist("C:WINDOWSsystem32 timage.gif") SplashImage, %A_WinDir%system32 timage.gif, A,,, Installation Loop, %A_WinDir%system32*.* { Progress, %A_Index%, %A_LoopFileName%, Installing..., Draft Installation Sleep, 50 if (A_Index = 100) break } ``` -------------------------------- ### Example: Play a WAV file Source: https://www.autohotkey.com/docs/v1/lib/SoundPlay.htm This example demonstrates how to play a .wav file located in the Windows directory. ```APIDOC ## Example: Play a .wav file ``` SoundPlay, %A_WinDir%\Media\ding.wav ``` ``` -------------------------------- ### Download Text File Example Source: https://www.autohotkey.com/docs/v1/lib/Download.htm This example demonstrates downloading a text file from a URL and saving it locally. ```autohotkey UrlDownloadToFile, https://www.autohotkey.com/download/1.1/version.txt, C:AutoHotkey Latest Version.txt ``` -------------------------------- ### Example: Minimize Notepad Source: https://www.autohotkey.com/docs/v1/lib/WinMinimize.htm This example demonstrates how to open Notepad, wait for it to exist, and then minimize it using the WinMinimize command. ```APIDOC ## Example: Minimize Notepad ### Code ``` Run, notepad.exe WinWait, Untitled - Notepad WinMinimize ; Use the window found by WinWait. ``` ``` -------------------------------- ### FileSelectFile with Root Directory and Filename Source: https://www.autohotkey.com/docs/v1/lib/FileSelectFile.htm Shows how to specify a starting directory and a default filename for the FileSelectFile dialog. The examples illustrate absolute paths, relative paths, and only a filename. ```autohotkey C:\My Pictures\Default Image Name.gif ; Both RootDir and Filename are present. ``` ```autohotkey C:\My Pictures ; Only RootDir is present. ``` ```autohotkey My Pictures ; Only RootDir is present, and it's relative to the current working directory. ``` ```autohotkey My File ; Only Filename is present (but if "My File" exists as a folder, it is assumed to be RootDir). ``` -------------------------------- ### Example: Restore Notepad Window Source: https://www.autohotkey.com/docs/v1/lib/WinRestore.htm This example demonstrates how to unminimize or unmaximize the Notepad window if it is currently minimized or maximized. ```autohotkey WinRestore, Untitled - Notepad ``` -------------------------------- ### Gosub Example Source: https://www.autohotkey.com/docs/v1/lib/Gosub.htm This example demonstrates the flow of Gosub. It jumps to Label1, executes its MsgBox, returns, and then continues execution after the Gosub statement. ```autohotkey Gosub, Label1 MsgBox, The Label1 subroutine has returned (it is finished). return Label1: MsgBox, The Label1 subroutine is now running. return ``` -------------------------------- ### Download Zip File Example Source: https://www.autohotkey.com/docs/v1/lib/Download.htm This example shows how to download a zip file from a URL to a specified local path. ```autohotkey UrlDownloadToFile, https://someorg.org/archive.zip, C:SomeOrg's Archive.zip ``` -------------------------------- ### InputBox Examples Source: https://www.autohotkey.com/docs/v1/lib/InputBox.htm Practical examples demonstrating the usage of the InputBox command for various scenarios. ```APIDOC ## Examples Allows the user to enter a hidden password. ```autohotkey InputBox, password, Enter Password, (your input will be hidden), hide ``` Allows the user to enter a phone number. ```autohotkey InputBox, UserInput, Phone Number, Please enter a phone number., , 640, 480 if ErrorLevel MsgBox, CANCEL was pressed. else MsgBox, You entered "%UserInput%" ``` ``` -------------------------------- ### Example: Hiding and Showing Notepad Source: https://www.autohotkey.com/docs/v1/lib/WinHide.htm This example demonstrates how to open Notepad, hide it for a short duration, and then show it again. ```APIDOC ## Example: Hiding and Showing Notepad ### Code ``` Run, notepad.exe WinWait, Untitled - Notepad Sleep, 500 WinHide _; Use the window found by WinWait._ Sleep, 1000 WinShow _; Use the window found by WinWait._ ``` ``` -------------------------------- ### Pre-loading and Reusing Images in a GUI Source: https://www.autohotkey.com/docs/v1/lib/LoadPicture.htm This example pre-loads multiple images from files into an array and then cycles through them in a GUI Picture control. It demonstrates using LoadPicture to get HBITMAP handles and displaying them dynamically. ```AutoHotkey Pics := [] _; Find some pictures to display._ Loop, Files, %A_WinDir%WebWallpaper*.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: Checking for Non-Existent Window Source: https://www.autohotkey.com/docs/v1/lib/WinExist.htm This example demonstrates how to check if a specific window (Calculator) does not exist and return if it doesn't. ```APIDOC ## Example: Checking for Non-Existent Window ### Description Returns if the calculator does not exist. ### Code ``` if not WinExist("Calculator") return ``` ``` -------------------------------- ### Add and Use an IP Address Control Source: https://www.autohotkey.com/docs/v1/lib/Gui.htm This example demonstrates adding and managing an IP address control within a GUI. It includes functions to set and get the IP address, and handles control events like changes. Requires v1.1.10+. ```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. (Requires v1.1.10+) if (A_EventInfo = 0x0300) _; EN_CHANGE_ ToolTip Control changed! } else if (A_GuiEvent = "N") { _; WM_NOTIFY was received. (Requires v1.1.10+) ; 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. (Requires v1.1.10+) 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% return NumGet(AddrWord, 3, "UChar") "." NumGet(AddrWord, 2, "UChar") "." NumGet(AddrWord, 1, "UChar") "." NumGet(AddrWord, 0, "UChar") } ``` -------------------------------- ### Pause Command Examples Source: https://www.autohotkey.com/docs/v1/lib/Pause.htm Examples demonstrating how to use the Pause command. ```APIDOC ## Examples Press a hotkey once to pause the script. Press it again to unpause. ``` Pause::Pause _; The Pause/Break key._ #p::Pause _; Win+P_ ``` Sends a Pause command to another script. ``` DetectHiddenWindows, On WM_COMMAND := 0x0111 ID_FILE_PAUSE := 65403 PostMessage, WM_COMMAND, ID_FILE_PAUSE,,, C:YourScript.ahk ahk_class AutoHotkey ``` ``` -------------------------------- ### ControlFocus Example Source: https://www.autohotkey.com/docs/v1/lib/ControlFocus.htm This example demonstrates how to use the ControlFocus command to set focus to the 'OK' button in a specified window. ```APIDOC ## Examples Sets keyboard focus to the OK button in a GUI or non-GUI window. ``` ControlFocus, OK, Some Window Title ``` ``` -------------------------------- ### FileOpen() Example - Standard Streams Source: https://www.autohotkey.com/docs/v1/lib/FileOpen.htm Examples demonstrating how to open standard input, output, and error streams using FileOpen(). ```APIDOC ### Standard Input/Output/Error Streams ``` FileOpen("*", "r") ; for stdin FileOpen("*", "w") ; for stdout FileOpen("**", "w") ; for stderr ``` ``` -------------------------------- ### Example: Generate a simple beep Source: https://www.autohotkey.com/docs/v1/lib/SoundPlay.htm This example shows how to generate a simple beep sound using the SoundPlay command with a system sound identifier. ```APIDOC ## Example: Generate a simple beep ``` SoundPlay *-1 ``` ``` -------------------------------- ### MouseClick Examples Source: https://www.autohotkey.com/docs/v1/lib/MouseClick.htm Examples demonstrating how to use MouseClick for various scenarios, including modifier keys and loops. ```APIDOC ## Remarks ### Example #1: Control-Click ``` Send, {Control down} MouseClick, left, 55, 233 Send, {Control up} ``` ### Example #2: Shift-Click ``` Send, {Shift down} MouseClick, left, 55, 233 Send, {Shift up} ``` ### Example #3: Multiple Wheel Rotations (for applications that only support one notch) ``` Loop, 5 MouseClick, WheelUp ``` ``` -------------------------------- ### Getting Winamp Track Number Source: https://www.autohotkey.com/docs/v1/lib/PostMessage.htm This example asks Winamp which track number is currently active. It adjusts the result by 1 because 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. } ``` -------------------------------- ### Example: Select and Analyze a Shortcut File Source: https://www.autohotkey.com/docs/v1/lib/FileGetShortcut.htm This example demonstrates how to prompt the user to select a shortcut file using FileSelectFile and then display its properties using FileGetShortcut. It covers retrieving target, directory, arguments, description, icon details, and run state. ```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: Minimize Active Window with Hotkey Source: https://www.autohotkey.com/docs/v1/lib/WinMinimize.htm This example shows how to assign a hotkey (Ctrl+Down) to minimize the currently active window. ```APIDOC ## Example: Minimize Active Window with Hotkey ### Code ``` ^Down::WinMinimize, A ; Ctrl+Down ``` ``` -------------------------------- ### Automate IE with ComObjQuery() Source: https://www.autohotkey.com/docs/v1/lib/ComObjQuery.htm This example shows how to get a WebBrowserApp interface pointer from an existing Internet Explorer window using ComObjQuery() after obtaining the document object. It requires the IID_IWebBrowserApp and SID_SWebBrowserApp GUIDs. ```AutoHotkey sURL := "https://www.autohotkey.com/boards/" if WebBrowser := GetWebBrowser() WebBrowser.Navigate(sURL) return GetWebBrowser() { _; Get a raw pointer to the document object of the top-most IE window._ static msg := DllCall("RegisterWindowMessage", "Str", "WM_HTML_GETOBJECT") SendMessage msg, 0, 0, Internet Explorer_Server1, ahk_class IEFrame if (ErrorLevel = "FAIL") return _; IE not found._ lResult := ErrorLevel DllCall("oleaccObjectFromLresult", "Ptr", lResult , "Ptr", GUID(IID_IHTMLDocument2,"{332C4425-26CB-11D0-B483-00C04FD90119}") , "Ptr", 0, "Ptr*", pdoc) _; Query for the WebBrowserApp service. In this particular case, ; the SID and IID are the same, but it isn't always this way._ static IID_IWebBrowserApp := "{0002DF05-0000-0000-C000-000000000046}" static SID_SWebBrowserApp := IID_IWebBrowserApp pweb := ComObjQuery(pdoc, SID_SWebBrowserApp, IID_IWebBrowserApp) _; Release the document object pointer._ ObjRelease(pdoc) _; Return the WebBrowser object, wrapped for usability:_ static VT_DISPATCH := 9, F_OWNVALUE := 1 return ComObject(VT_DISPATCH, pweb, F_OWNVALUE) } GUID(ByRef GUID, sGUID) _; Converts a string to a binary GUID and returns its address._ { VarSetCapacity(GUID, 16, 0) return DllCall("ole32CLSIDFromString", "WStr", sGUID, "Ptr", &GUID) >= 0 ? &GUID : "" } ``` -------------------------------- ### Example: Activating a Window Based on Existence Source: https://www.autohotkey.com/docs/v1/lib/WinExist.htm This example demonstrates how to activate either Notepad or another window based on whether they exist, using WinExist() in conjunction with an OR condition. ```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 ``` if WinExist("ahk_class Notepad") or WinExist("ahk_class" ClassName) WinActivate _; Use the window found by WinExist._ ``` ``` -------------------------------- ### Example: Retrieving Local AppData Directory Source: https://www.autohotkey.com/docs/v1/lib/EnvGet.htm This example retrieves and reports the path of the current user's Local AppData directory. ```APIDOC ## Example: Retrieve Local AppData Directory ### Description Retrieves and reports the path of the current user's Local AppData directory. ### Code ``` EnvGet, LocalAppData, LocalAppData MsgBox, %A_UserName%'s Local directory is located at: %LocalAppData% ``` ``` -------------------------------- ### InputHook.Start() Source: https://www.autohotkey.com/docs/v1/lib/InputHook.htm Starts collecting input. Has no effect if the Input is already in progress. Installs the keyboard hook if not already installed. ```APIDOC ## Start Starts collecting input. ``` InputHook.Start() ``` Has no effect if the Input is already in progress. The newly started Input is placed on the top of the InputHook stack, which allows it to override any previously started Input. This method installs the keyboard hook (if it was not already). ``` -------------------------------- ### Example Usage Source: https://www.autohotkey.com/docs/v1/lib/WinMinimizeAll.htm Demonstrates how to use WinMinimizeAll and WinMinimizeAllUndo together to temporarily minimize all windows. ```APIDOC ## Example: Minimize all windows for 1 second ### Description This example shows how to minimize all windows, pause for 1 second, and then restore them. ### Code ```apidoc WinMinimizeAll Sleep, 1000 WinMinimizeAllUndo ``` ``` -------------------------------- ### Example: Retrieving LogonServer Environment Variable Source: https://www.autohotkey.com/docs/v1/lib/EnvGet.htm This example demonstrates how to retrieve the value of the 'LogonServer' environment variable and store it in the 'OutputVar' variable. ```APIDOC ## Example: Retrieve LogonServer ### Description Retrieves the value of an environment variable and stores it in OutputVar. ### Code ``` EnvGet, OutputVar, LogonServer ``` ``` -------------------------------- ### Start InputHook Source: https://www.autohotkey.com/docs/v1/lib/InputHook.htm Starts collecting input. Has no effect if input is already in progress. Installs the keyboard hook if not already present. ```autohotkey InputHook.Start() ``` -------------------------------- ### Function Call Example Source: https://www.autohotkey.com/docs/v1/Language.htm Basic example of calling a function. Note the absence of space between the function name and the opening parenthesis. ```AutoHotkey GetKeyState("Shift") ``` -------------------------------- ### Minimize and Restore All Windows Example Source: https://www.autohotkey.com/docs/v1/lib/WinMinimizeAll.htm This example demonstrates minimizing all windows, pausing for 1 second, and then restoring them. It's a practical way to temporarily hide all applications and then bring them back. ```autohotkey WinMinimizeAll Sleep, 1000 WinMinimizeAllUndo ``` -------------------------------- ### Get Pixel Color at Mouse Cursor Source: https://www.autohotkey.com/docs/v1/lib/PixelGetColor.htm This example shows how to get the color of the pixel at the current mouse cursor position when a hotkey is pressed. Ensure MouseGetPos is used to get the coordinates. ```autohotkey ^!z:: _; Control+Alt+Z hotkey._ MouseGetPos, MouseX, MouseY PixelGetColor, color, %MouseX%, %MouseY% MsgBox The color at the current cursor position is %color%. return ``` -------------------------------- ### Get Character from Code - AutoHotkey Source: https://www.autohotkey.com/docs/v1/lib/Chr.htm Use this snippet to retrieve the character string corresponding to a given character code. The example shows how to get the character 't' using its code 116. ```AutoHotkey MsgBox % Chr(116) ; Reports "t". ``` -------------------------------- ### Example: Get and Report Active Window Details Source: https://www.autohotkey.com/docs/v1/lib/WinGetActiveStats.htm This example demonstrates how to use WinGetActiveStats to capture the active window's title, size, and position, then display this information in a message box. ```autohotkey WinGetActiveStats, Title, Width, Height, X, Y MsgBox, The active window "%Title%" is %Width% wide`, %Height% tall`, and positioned at %X%`,%Y%. ``` -------------------------------- ### Get Menu Item Count and Last Item ID Source: https://www.autohotkey.com/docs/v1/lib/MenuGetHandle.htm This example demonstrates how to use the retrieved menu handle with DllCall to get the number of items in a menu and the ID of the last item. Ensure the menu exists before calling. ```AutoHotkey Menu MyMenu, Add, Item 1, no Menu MyMenu, Add, Item 2, no Menu MyMenu, Add, Item B, no _; Retrieve the number of items in a menu. _ item_count := DllCall("GetMenuItemCount", "ptr", MenuGetHandle("MyMenu")) _; Retrieve the ID of the last item. _ last_id := DllCall("GetMenuItemID", "ptr", MenuGetHandle("MyMenu"), "int", item_count-1) MsgBox, MyMenu has %item_count% items, and its last item has ID %last_id%. no: return ``` -------------------------------- ### StrPut() Examples with Parameters Source: https://www.autohotkey.com/docs/v1/lib/StrPut.htm Demonstrates various ways to use StrPut() with different parameter combinations for encoding and buffer size specification. ```AutoHotkey StrPut(str, address, "cp0") _; Code page 0, unspecified buffer size_ StrPut(str, address, n, 0) _; Maximum n chars, code page 0_ StrPut(str, address, 0) _; Unsupported (maximum 0 chars)_ ``` -------------------------------- ### Get Object Class Name with ComObjQuery() Source: https://www.autohotkey.com/docs/v1/lib/ComObjQuery.htm This example demonstrates how to retrieve an object's class name by querying for the IProvideClassInfo interface and then using its methods to get type information. Ensure interface pointers are released after use. ```AutoHotkey obj := ComObjCreate("Scripting.Dictionary") MsgBox % "Interface name: " ComObjType(obj, "name") IID_IProvideClassInfo := "{B196B283-BAB4-101A-B69C-00AA00341D07}" _; Request a pointer to the object's IProvideClassInfo interface._ if !(pci := ComObjQuery(obj, IID_IProvideClassInfo)) { MsgBox IProvideClassInfo interface not supported. return } _; Call GetClassInfo to retrieve a pointer to the ITypeInfo interface._ DllCall(vtable(pci, 3), "ptr", pci, "ptr*", ti) _; Call GetDocumentation to get the object's full type name._ DllCall(vtable(ti, 12), "ptr", ti, "int", -1, "ptr*", pname, "ptr", 0, "ptr", 0, "ptr", 0) _; Convert the BSTR pointer to a usable string._ name := StrGet(pname, "UTF-16") _; Free the BSTR referenced by pname._ DllCall("OleAut32SysFreeString", "ptr", pname) _; Release raw interface pointers._ ObjRelease(ti) ObjRelease(pci) _; Display the type name!_ MsgBox % "Class name: " name vtable(ptr, n) { _; NumGet(ptr+0) returns the address of the object's virtual function ; table (vtable for short). The remainder of the expression retrieves ; the address of the nth function's address from the vtable._ return NumGet(NumGet(ptr+0), n*A_PtrSize) } ``` -------------------------------- ### Write and Read File with CreateFile/WriteFile Source: https://www.autohotkey.com/docs/v1/lib/DllCall.htm Demonstrates writing text to a file and then reading it back using CreateFile, WriteFile, and CloseHandle. Requires v1.0.34+. For v1.0.90+, FileOpen() is recommended. ```AutoHotkey FileSelectFile, FileName, S16,, Create a new file: if (FileName = "") return GENERIC_WRITE := 0x40000000 _; Open the file for writing rather than reading._ CREATE_ALWAYS := 2 _; Create new file (overwriting any existing file)._ hFile := DllCall("CreateFile", "Str", FileName, "UInt", GENERIC_WRITE, "UInt", 0, "Ptr", 0, "UInt", CREATE_ALWAYS, "UInt", 0, "Ptr", 0) if not hFile { 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._ StrLen := StrLen(TestString) * (A_IsUnicode ? 2 : 1) DllCall("WriteFile", "Ptr", hFile, "Str", TestString, "UInt", StrLen, "UIntP", BytesActuallyWritten, "Ptr", 0) DllCall("CloseHandle", "Ptr", hFile) _; Close the file._ _; Now that the file was written, read its contents back into memory._ GENERIC_READ := 0x80000000 _; Open the file for reading rather than writing._ OPEN_EXISTING := 3 _; This mode indicates that the file to be opened must already exist._ FILE_SHARE_READ := 0x1 _; This and the next are whether other processes can open the file while we have it open._ FILE_SHARE_WRITE := 0x2 hFile := DllCall("CreateFile", "Str", FileName, "UInt", GENERIC_READ, "UInt", FILE_SHARE_READ|FILE_SHARE_WRITE, "Ptr", 0, "UInt", OPEN_EXISTING, "UInt", 0, "Ptr", 0) if not hFile { MsgBox Can't open "%FileName%" for reading. return } ``` -------------------------------- ### Get UTF-8 String from Clipboard Source: https://www.autohotkey.com/docs/v1/lib/Transform.htm This example demonstrates how to get the UTF-8 string representation of Unicode text currently on the clipboard using the deprecated Transform Unicode sub-command. It then constructs a line of code that can be pasted into a script to achieve the same result. ```autohotkey ^!u:: _; Control+Alt+U hotkey._ 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 ``` -------------------------------- ### Get Network Adapter IP Addresses Source: https://www.autohotkey.com/docs/v1/Variables.htm Retrieves the IP addresses for the first four network adapters installed on the computer. ```AutoHotkey A_IPAddress1 A_IPAddress2 A_IPAddress3 A_IPAddress4 ``` -------------------------------- ### Array of Functions Example Source: https://www.autohotkey.com/docs/v1/lib/Array.htm Demonstrates creating an array of function references and calling them with parameters or implicitly. ```AutoHotkey array := [Func("FirstFunc"), Func("SecondFunc")] _; Call each function, passing "foo" as a parameter:_ Loop 2 array[A_Index].Call("foo") _; Call each function, implicitly passing the array itself as a parameter:_ Loop 2 array[A_Index]() FirstFunc(param) { MsgBox % A_ThisFunc ": " (IsObject(param) ? "object" : param) } SecondFunc(param) { MsgBox % A_ThisFunc ": " (IsObject(param) ? "object" : param) } ``` -------------------------------- ### InputHook.Input Source: https://www.autohotkey.com/docs/v1/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 ## 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. ``` -------------------------------- ### Get Collected Input Text Source: https://www.autohotkey.com/docs/v1/lib/InputHook.htm Retrieves any text collected since the InputHook was started. This can be accessed while input is in progress or after it has ended. ```autohotkey String := InputHook.Input ``` -------------------------------- ### Example: Accessing Registry Views - AutoHotkey v1 Source: https://www.autohotkey.com/docs/v1/lib/SetRegView.htm Demonstrates how to set specific registry views (32-bit and 64-bit) and interact with registry keys that are subject to redirection via WOW64. It also shows how to restore the default registry view. ```autohotkey ; Access the registry as a 32-bit application would. SetRegView 32 RegWrite REG_SZ, HKLM, SOFTWARETest.ahk, Value, 123 ; Access the registry as a 64-bit application would. SetRegView 64 RegRead value, HKLM, SOFTWAREWow6432NodeTest.ahk, Value RegDelete HKLM, SOFTWAREWow6432NodeTest.ahk MsgBox Read value '%value%' via Wow6432Node. ; Restore the registry view to the default, ; which depends on whether the script is 32-bit or 64-bit. SetRegView Default ; ... ``` -------------------------------- ### DriveSpaceFree Command Example Source: https://www.autohotkey.com/docs/v1/ChangeLogHelp.htm Use DriveSpaceFree to get the free space in MB for a specified drive. The output is stored in the provided OutputVar. ```autohotkey DriveSpaceFree, OutputVar, C: ``` -------------------------------- ### PostExec Example: UPX Compression Source: https://www.autohotkey.com/docs/v1/misc/Ahk2ExeDirectives.htm Specifies UPX.exe for compression with specific parameters when no compression is otherwise defined. ```autohotkey ;@Ahk2Exe-PostExec "UPX.exe" "%A_WorkFileName%" ;@Ahk2Exe-Cont -q --all-methods --compress-icons=0, 0,, 1_ ``` -------------------------------- ### Retrieve and Report Calculator Position and Size Source: https://www.autohotkey.com/docs/v1/lib/WinGetPos.htm This example demonstrates how to get the position and size of the 'Calculator' window and display it in a message box. ```autohotkey WinGetPos, X, Y, W, H, Calculator MsgBox, Calculator is at %X%,%Y% and its size is %W%x%H% ``` -------------------------------- ### Conditional Expression Example Source: https://www.autohotkey.com/docs/v1/ChangeLogHelp.htm Demonstrates the use of complex expressions within IF statements by starting the condition with a parenthesis. This allows for more sophisticated conditional logic. ```AutoHotkey if (X < Y + 10) and (Color = "Blue") ``` -------------------------------- ### PostExec Example: MPRESS Compression Source: https://www.autohotkey.com/docs/v1/misc/Ahk2ExeDirectives.htm Specifies MPRESS.exe for compression with specific parameters when no compression is otherwise defined. ```autohotkey ;@Ahk2Exe-PostExec "MPRESS.exe" "%A_WorkFileName%" -q -x, 0,, 1_ ``` -------------------------------- ### Get Primary Monitor Number Source: https://www.autohotkey.com/docs/v1/lib/SysGet.htm Retrieve the number of the primary monitor using the MonitorPrimary sub-command. In a single-monitor setup, this will always return 1. ```AutoHotkey SysGet, OutputVar, MonitorPrimary ``` -------------------------------- ### Example: Retrieving Program Files Directory Source: https://www.autohotkey.com/docs/v1/lib/EnvGet.htm This example retrieves and reports the path of the 'Program Files' directory, dynamically selecting the correct variable based on whether the OS is 64-bit. ```APIDOC ## Example: Retrieve Program Files Directory ### Description Retrieves and reports the path of the "Program Files" directory. See RegRead example #2 for an alternative method. ### Code ``` EnvGet, OutputVar, % A_Is64bitOS ? "ProgramW6432" : "ProgramFiles" MsgBox, Program files are in: %OutputVar% ``` ``` -------------------------------- ### Get Numeric System Value Source: https://www.autohotkey.com/docs/v1/lib/SysGet.htm Retrieve a specific numeric system value by providing its corresponding number as the SubCommand. For example, retrieving the mouse button count. ```AutoHotkey SysGet, OutputVar, N ``` ```AutoHotkey SysGet, MouseButtonCount, 43 ``` -------------------------------- ### Example: Hide and Unhide Notepad Window Source: https://www.autohotkey.com/docs/v1/lib/WinShow.htm This example demonstrates opening Notepad, hiding it briefly, and then unhiding it. It utilizes WinWait to ensure Notepad is open before proceeding. ```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._ ``` -------------------------------- ### Get Focused Control in Notepad Source: https://www.autohotkey.com/docs/v1/lib/ControlGetFocus.htm This example activates the Notepad window and then retrieves the ClassNN of the control that has keyboard focus. It checks the ErrorLevel to report success or failure. ```autohotkey WinActivate, ahk_class Notepad ControlGetFocus, OutputVar, ahk_class Notepad if ErrorLevel MsgBox, The target window doesn't exist or none of its controls has keyboard focus. else MsgBox, Control with focus = %OutputVar% ``` -------------------------------- ### Example: Get Calculator Text - AutoHotkey v1 Source: https://www.autohotkey.com/docs/v1/lib/WinGetText.htm Opens the calculator, waits for it to exist, then retrieves and displays its text content. This demonstrates basic usage with WinWait and MsgBox. ```AutoHotkey Run, Calc.exe WinWait, Calculator WinGetText, text _ ; Use the window found by WinWait. MsgBox, The text is:`n%text% ``` -------------------------------- ### WinMove Examples Source: https://www.autohotkey.com/docs/v1/lib/WinMove.htm Illustrates practical usage of the WinMove command with various scenarios. ```APIDOC ## Examples Opens the calculator, waits until it exists and moves it to the upper-left corner of the screen. ``` Run, calc.exe WinWait, Calculator WinMove, 0, 0 _; Use the window found by WinWait._ ``` Creates a fixed-size popup window that shows the contents of the clipboard and moves it to the upper-left corner of the screen. ``` SplashTextOn, 400, 300, Clipboard, The clipboard contains:`n%Clipboard% WinMove, Clipboard,, 0, 0 MsgBox, Press OK to dismiss the SplashText SplashTextOff ``` Centers a window on the screen. ``` CenterWindow("ahk_class Notepad") CenterWindow(WinTitle) { WinGetPos,,, Width, Height, %WinTitle% WinMove, %WinTitle%,, (A_ScreenWidth/2)-(Width/2), (A_ScreenHeight/2)-(Height/2) } ``` ``` -------------------------------- ### Get and Report Active Window Title Source: https://www.autohotkey.com/docs/v1/lib/WinGetActiveTitle.htm This example demonstrates how to retrieve the active window's title and display it in a message box. Ensure the OutputVar is correctly defined. ```autohotkey WinGetActiveTitle, Title MsgBox, The active window is "%Title%". ``` -------------------------------- ### Creating and Reading a Pseudo-Array from a File Source: https://www.autohotkey.com/docs/v1/misc/Arrays.htm This example illustrates how to populate a pseudo-array by reading lines from a text file and then how to access elements using a loop and the array's count. ```AutoHotkey _**; Write to the array:**_ ArrayCount := 0 Loop, Read, %A_WinDir%system.ini _; This loop retrieves each line from the file, one at a time._ { ArrayCount += 1 _; Keep track of how many items are in the array._ Array%ArrayCount% := A_LoopReadLine _; Store this line in the next array element._ } _**; Read from the array:**_ Loop %ArrayCount% { _; The following line uses the := operator to retrieve an array element:_ element := Array%A_Index% _; A_Index is a built-in variable._ _; Alternatively, you could use the "% " prefix to make MsgBox or some other command expression-capable:_ MsgBox % "Element number " . A_Index . " is " . Array%A_Index% ``` -------------------------------- ### Set Slider Selection Range Source: https://www.autohotkey.com/docs/v1/misc/Styles.htm Use SendMessage with MCM_SETSELSTART and MCM_SETSELEND to define the selection range for a Slider control. This example sets the start to 55 and the end to 66. ```AutoHotkey SendMessage, 0x040B, 1, 55, msctls_trackbar321, WinTitle SendMessage, 0x040C, 1, 66, msctls_trackbar321, WinTitle ``` -------------------------------- ### Maximize Notepad Window Source: https://www.autohotkey.com/docs/v1/lib/WinMaximize.htm This example demonstrates opening Notepad, waiting for it to become available, and then maximizing it using the WinMaximize command. The underscore signifies using the window identified by the preceding WinWait command. ```autohotkey Run, notepad.exe WinWait, Untitled - Notepad WinMaximize _ ``` -------------------------------- ### Get Screen DPI Source: https://www.autohotkey.com/docs/v1/Variables.htm Retrieves the number of pixels per logical inch along the screen width. This value is consistent across all monitors in a multi-monitor setup and is typically 96. ```AutoHotkey A_ScreenDPI ``` -------------------------------- ### GetKeyState Command Syntax Examples Source: https://www.autohotkey.com/docs/v1/lib/GetKeyState.htm Illustrates the command syntax for checking key and button states, including toggle states. ```autohotkey GetKeyState, state, RButton _; Right mouse button._ GetKeyState, state, Joy2 _; The second button of the first controller._ GetKeyState, state, Shift if (state = "D") MsgBox At least one Shift key is down. else MsgBox Neither Shift key is down. GetKeyState, state, CapsLock, T _; D if CapsLock is ON or U otherwise._ ``` -------------------------------- ### Get String Length and Report Source: https://www.autohotkey.com/docs/v1/lib/StrLen.htm This example demonstrates how to use StrLen() to find the length of a string and display it using MsgBox. Ensure the string variable is properly assigned before calling StrLen(). ```autohotkey StrValue := "The quick brown fox jumps over the lazy dog" MsgBox % "The length of the string is " StrLen(StrValue) _; Result: 43_ ``` -------------------------------- ### Getting the Path to the AutoHotkey Executable Source: https://www.autohotkey.com/docs/v1/Variables.htm A_AhkPath provides the full path to the AutoHotkey executable. For compiled scripts, it may point to the script itself or the installed AutoHotkey.exe depending on the version and compilation method. ```AutoHotkey MsgBox, The AutoHotkey executable path is: %A_AhkPath% ``` ```AutoHotkey RegRead InstallDir, HKLMSOFTWAREAutoHotkey, InstallDir AhkPath := ErrorLevel ? "" : InstallDir "AutoHotkey.exe" ``` -------------------------------- ### Activate and Maximize Last Found Window (Notepad) Source: https://www.autohotkey.com/docs/v1/misc/WinTitle.htm This example shows how to activate and maximize a Notepad window identified by WinExist(). The underscore `_` is used with WinActivate and WinMaximize to refer to the window found by the preceding WinExist() command. ```autohotkey if WinExist("Untitled - Notepad") { WinActivate _ ; Use the window found by WinExist. WinMaximize _ ; Same as above. Send, Some text.{Enter} } ``` -------------------------------- ### Launch Internet Explorer with ComObjCreate() Source: https://www.autohotkey.com/docs/v1/lib/ComObjCreate.htm Launches an instance of Internet Explorer, makes it visible, and navigates to a specified URL. Note that the visibility setting might behave unexpectedly with IE7. ```autohotkey ie := ComObjCreate("InternetExplorer.Application") ie.Visible := true _; This is known to work incorrectly on IE7._ ie.Navigate("https://www.autohotkey.com/") ``` -------------------------------- ### Create a Moving Progress Bar Overlay Source: https://www.autohotkey.com/docs/v1/lib/Gui.htm Displays a progress bar overlaid on a background image. This example includes a button to start the progress bar animation and a text control to display status. ```AutoHotkey Gui, Color, White Gui, Add, Picture, x0 y0 h350 w450, %A_WinDir%system32 timage.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". M; Gui, Show return ``` -------------------------------- ### Sending a String via PostMessage Source: https://www.autohotkey.com/docs/v1/lib/PostMessage.htm This example demonstrates sending a string as a parameter using the address operator (&). The receiver can then recognize the string without extra steps, provided the parameter starts with an ampersand. ```AutoHotkey SendMessage, 0x000C, 0, &MyVar, ClassNN, WinTitle _; 0x000C is WM_SETTEXT_ ``` -------------------------------- ### Create and Populate TreeView ImageList Source: https://www.autohotkey.com/docs/v1/lib/TreeView.htm This example shows how to create an ImageList, add system icons to it, and then associate it with a TreeView control. It also demonstrates adding an item to the TreeView with a specified icon. ```AutoHotkey ImageListID := IL_Create(10) _; Create an ImageList with initial capacity for 10 icons. entire Loop 10 _; Load the ImageList with some standard system icons. IL_Add(ImageListID, "shell32.dll", A_Index) Gui, Add, TreeView, ImageList%ImageListID% TV_Add("Name of Item", 0, "Icon4") _; Add an item to the TreeView and give it a folder icon. Gui, Show ``` -------------------------------- ### Goto Example Source: https://www.autohotkey.com/docs/v1/lib/Goto.htm Demonstrates jumping to a label named 'MyLabel' and continuing execution. The use of Goto is generally discouraged. ```autohotkey Goto, MyLabel _; ..._ MyLabel: Sleep, 100 _; ..._ ``` -------------------------------- ### Input Validation: Check if User Input is Within a Numeric Range Source: https://www.autohotkey.com/docs/v1/lib/IfBetween.htm This example demonstrates how to get user input and validate if it falls within a predefined numeric range using the `InputBox` and `If Var Not Between` commands. ```AutoHotkey LowerLimit := 1 UpperLimit := 10 InputBox, UserInput, Enter a number between %LowerLimit% and %UpperLimit% if UserInput not between %LowerLimit% and %UpperLimit% MsgBox Your input is not within the valid range. ``` -------------------------------- ### Example: Add Text and Edit Field Source: https://www.autohotkey.com/docs/v1/lib/Gui.htm A simple example demonstrating how to add a text label and an edit field to a GUI, followed by showing the window. ```autohotkey Gui, Add, Text,, Please enter your name: Gui, Add, Edit, vName Gui, Show ``` -------------------------------- ### Get Ordinal Value of a Character - AutoHotkey Source: https://www.autohotkey.com/docs/v1/lib/Ord.htm Use Ord() to retrieve the numeric character code of the first character in a string. This example shows that only the first character is considered, even if the string contains multiple characters. ```AutoHotkey MsgBox, % Ord("t") MsgBox, % Ord("test") ```