### Select Folder Starting at This PC using CLSID Source: https://www.autohotkey.com/docs/v2/lib/DirSelect.htm This example demonstrates how to use DirSelect to start the folder selection dialog at 'This PC' (formerly My Computer) by providing its CLSID as the StartingFolder parameter. ```AutoHotkey SelectedFolder := DirSelect("::{20D04FE0-3AEA-1069-A2D8-08002B30309D}") ``` -------------------------------- ### Get Process Name and Path Example Source: https://www.autohotkey.com/docs/v2/lib/ProcessGetName.htm This example demonstrates how to get the name and path of a process by first launching a file with the Run function and then using ProcessGetName and ProcessGetPath with the returned PID. Error handling is included using a try-catch block. ```autohotkey Run "license.rtf",,, &pid _; This is likely to exist in C:WindowsSystem32._ try { name := ProcessGetName(pid) path := ProcessGetPath(pid) } MsgBox "Name: " (name ?? "could not be retrieved") "`n" . "Path: " (path ?? "could not be retrieved") ``` -------------------------------- ### Example 2: Get Process List via COM Source: https://www.autohotkey.com/docs/v2/lib/Process.htm Shows a list of running processes retrieved via COM and Win32_Process. ```APIDOC ## Example 2: Get Process List via COM Shows a list of running processes retrieved via COM and Win32_Process. ```autohotkey MyGui := Gui(, "Process List") LV := MyGui.Add("ListView", "x2 y0 w400 h500", ["Process Name", "Command Line"]) for process in ComObjGet("winmgmts:").ExecQuery("Select * from Win32_Process") LV.Add("", process.Name, process.CommandLine) MyGui.Show() ``` ``` -------------------------------- ### Example 1: Get Process List via DllCall Source: https://www.autohotkey.com/docs/v2/lib/Process.htm Shows a list of running processes retrieved via DllCall and EnumProcesses. ```APIDOC ## Example 1: Get Process List via DllCall Shows a list of running processes retrieved via DllCall and EnumProcesses. ```autohotkey MyGui := Gui() LV := MyGui.Add("ListView", "w1300 r25", ["#", "PID", "Name", "Path"]) for Index, Proc in GetProcessList() LV.Add("", Index, Proc.PID, Proc.Name, Proc.Path) LV.ModifyCol() MyGui.Title := LV.GetCount() " Processes" MyGui.Show() GetProcessList(MaxProcs := 1024) { Arr := [] _; array to store the process information_ DllCall("Psapi.dllEnumProcesses" , "Ptr", Buf := Buffer(MaxProcs * 4) _; buffer to store all PIDs_ , "UInt", Buf.Size , "UIntP", &ByteCnt := 0) _; number of bytes returned by DllCall_ Loop (ByteCnt // 4) { PID := NumGet(Buf, (A_Index - 1) * 4, "UInt") try Arr.Push({ Name: ProcessGetName(PID), Path: ProcessGetPath(PID), PID: PID }) } return Arr } ``` ``` -------------------------------- ### Start InputHook Source: https://www.autohotkey.com/docs/v2/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, overriding previous ones. ```AutoHotkey InputHookObj.Start() ``` -------------------------------- ### Goto Example with Label Source: https://www.autohotkey.com/docs/v2/lib/Goto.htm This example demonstrates jumping to a label named 'MyLabel' and continuing execution from there. The label is defined with a colon. ```autohotkey Goto MyLabel ; ... MyLabel: Sleep 100 ; ... ``` -------------------------------- ### Create a Moving Progress Bar Overlay Source: https://www.autohotkey.com/docs/v2/lib/Gui.htm This example shows how to create a GUI with a background image and a moving progress bar. It includes a button to start the progress bar's movement. The 'wp' option for the text control means 'use width of previous'. ```AutoHotkey MyGui := Gui() MyGui.BackColor := "White" MyGui.Add("Picture", "x0 y0 h350 w450", A_WinDir "WebWallpaperWindowsimg0.jpg") MyBtn := MyGui.Add("Button", "Default xp+20 yp+250", "Start the Bar Moving") MyBtn.OnEvent("Click", MoveBar) MyProgress := MyGui.Add("Progress", "w416") MyText := MyGui.Add("Text", "wp") _; wp means "use width of previous"._ MyGui.Show() ``` -------------------------------- ### Drive Functions Example Source: https://www.autohotkey.com/docs/v2/lib/Drive.htm Example demonstrating how to use various drive functions to analyze a selected drive. ```APIDOC ## Example: Drive Analysis Allows the user to select a drive in order to analyze it. ```autohotkey folder := DirSelect( , 3, "Pick a drive to analyze:") if not folder return MsgBox ( "All Drives: " DriveGetList() "\n" "Selected Drive: " folder "\n" "Drive Type: " DriveGetType(folder) "\n" "Status: " DriveGetStatus(folder) "\n" "Capacity: " DriveGetCapacity(folder) " MB\n" "Free Space: " DriveGetSpaceFree(folder) " MB\n" "Filesystem: " DriveGetFilesystem(folder) "\n" "Volume Label: " DriveGetLabel(folder) "\n" "Serial Number: " DriveGetSerial(folder) ) ``` ``` -------------------------------- ### Get Shortcut Information Source: https://www.autohotkey.com/docs/v2/lib/FileGetShortcut.htm This example demonstrates how to use FileGetShortcut to retrieve and display information about a user-selected shortcut file. It prompts the user to select an .lnk file and then displays its target, directory, arguments, description, icon, icon number, and run state. ```autohotkey LinkFile := FileSelect(32,, "Pick a shortcut to analyze.", "Shortcuts (*.lnk)") if LinkFile = "" return FileGetShortcut LinkFile, &OutTarget, &OutDir, &OutArgs, &OutDesc, &OutIcon, &OutIconNum, &OutRunState MsgBox OutTarget "`n" OutDir "`n" OutArgs "`n" OutDesc "`n" OutIcon "`n" OutIconNum "`n" OutRunState ``` -------------------------------- ### Eject All Removable Drives Example Source: https://www.autohotkey.com/docs/v2/lib/DriveEject.htm Example demonstrating how to iterate through removable drives and prompt the user before ejecting each one. ```APIDOC ## Eject All Removable Drives ### Description Ejects all removable drives (except CD/DVD drives) after user confirmation. ### Method N/A (Script Logic) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```apidoc Loop Parse DriveGetList("REMOVABLE") { if MsgBox("Eject " A_LoopField ":, even if files are open?",, "y/n") = "yes" DriveEject(A_LoopField) } else MsgBox "No removable drives found." ``` ### Response #### Success Response (200) N/A #### Response Example None ``` -------------------------------- ### GetMethod Example: Retrieving and Reporting Method Info Source: https://www.autohotkey.com/docs/v2/lib/GetMethod.htm This example demonstrates how to retrieve information about the GetMethod method itself. It shows that GetMethod can be used to inspect its own properties. ```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._ ``` -------------------------------- ### MouseMove Examples Source: https://www.autohotkey.com/docs/v2/lib/MouseMove.htm Illustrative examples of how to use the MouseMove function. ```APIDOC ## MouseMove Examples ### Description Examples demonstrating the usage of the MouseMove function. ### Code Examples 1. **Moves the mouse cursor to a new position:** ```autohotkey MOUSEMOVE 200, 100 ``` 2. **Moves the mouse cursor slowly (speed 50 vs. 2) by 20 pixels to the right and 30 pixels down from its current location:** ```autohotkey MOUSEMOVE 20, 30, 50, "R" ``` ``` -------------------------------- ### ImageList Creation and Usage Example Source: https://www.autohotkey.com/docs/v2/lib/TreeView.htm Example demonstrating how to create and use an ImageList with a TreeView control. ```APIDOC ## ImageLists ### Description An Image-List is a group of identically sized icons stored in memory. This example demonstrates how to put icons into a TreeView. ### Code Example ```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() ``` ### Remarks - The `SetImageList` method can be used as an alternative to the `ImageList` option. - Unlike ListViews, a TreeView's ImageList is not automatically destroyed when the TreeView is destroyed. A script should call `IL_Destroy` after destroying a TreeView's window if the ImageList will not be used for anything else. However, this is not necessary if the script will soon be exiting because all ImageLists are automatically destroyed at that time. ``` -------------------------------- ### Install Additional AutoHotkey Version Source: https://www.autohotkey.com/docs/v2/Program.htm Install an additional version of AutoHotkey from a source directory. Execute this from the current installation directory, adjusting the path to AutoHotkey32.exe if necessary. ```bash AutoHotkey32.exe UX\install.ahk /install "%SOURCE%" ``` -------------------------------- ### Get Current Winamp Track Number Source: https://www.autohotkey.com/docs/v2/misc/Winamp.htm This example retrieves the currently active or playing track number from Winamp. It uses the SendMessage command and adjusts the result as Winamp's track count starts at 0. ```ahk TrackNumber := SendMessage(0x0400, 0, 120,, "ahk_class Winamp v1.x") if (TrackNumber != "") { TrackNumber += 1 ; Winamp's count starts at 0, so adjust by 1. MsgBox "Track #" TrackNumber " is active or playing." } ``` -------------------------------- ### Example: Populate ListView with Icons Source: https://www.autohotkey.com/docs/v2/lib/ListView.htm Demonstrates creating a GUI, a ListView, an ImageList, adding icons from a DLL to the ImageList, assigning the ImageList to the ListView, and adding rows with icons. ```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() ``` -------------------------------- ### Example Usage Source: https://www.autohotkey.com/docs/v2/lib/WinMinimizeAll.htm Demonstrates how to use WinMinimizeAll and WinMinimizeAllUndo together with a delay. ```APIDOC ## Example: Minimize and Unminimize All Windows ### Description Minimizes all windows for 1 second and then unminimizes them. ### Method N/A (Commands) ### Endpoint N/A (Commands) ### Parameters None ### Request Example ```autohotkey WinMinimizeAll Sleep 1000 WinMinimizeAllUndo ``` ### Response N/A (Commands) ### Response Example N/A (Commands) ``` -------------------------------- ### dbgp_listvars.ahk - List Variables Example Source: https://www.autohotkey.com/docs/v2/AHKL_DBGPClients.htm An example client that lists the variables of all running scripts. It requires the dbgp.ahk library and assumes a DBGp connection is established. ```autohotkey ; dbgp_listvars.ahk ; Example client which just lists the variables of all running scripts #Include ; Example usage (replace with actual DBGp connection details) ; Connect to a script ; dbgp_connect("127.0.0.1", 9000) ; Send command to list variables ; dbgp_send("list_vars") ; Receive and display variables ; response := dbgp_receive() ; MsgBox, % response ; Disconnect ; dbgp_disconnect() ``` -------------------------------- ### FileInstall Example - AutoHotkey v2 Source: https://www.autohotkey.com/docs/v2/lib/FileInstall.htm Demonstrates how to use FileInstall to embed a file named 'My File.txt' into the compiled script and extract it to the user's desktop as 'Example File.txt', overwriting if it already exists. ```autohotkey FileInstall "My File.txt", A_Desktop "Example File.txt", 1 ``` -------------------------------- ### Get Tab Control Page Count Source: https://www.autohotkey.com/docs/v2/lib/ControlGetItems.htm This example demonstrates how to get the total number of pages in a tab control using SendMessage with the TCM_GETITEMCOUNT message. ```autohotkey PageCount := SendMessage(0x1304,,, "SysTabControl321", WinTitle) _; 0x1304 is TCM_GETITEMCOUNT._ ``` -------------------------------- ### Open and Maximize Notepad Source: https://www.autohotkey.com/docs/v2/lib/WinMaximize.htm This example shows how to open Notepad, wait for its window to appear, and then maximize it using the WinMaximize function. ```AutoHotkey Run "notepad.exe" WinWait "Untitled - Notepad" WinMaximize _; Use the window found by WinWait._ ``` -------------------------------- ### Start and Stop Repeating Action with Hotkey Source: https://www.autohotkey.com/docs/v2/FAQ.htm This example demonstrates a hotkey that toggles a repeating action within a loop. The same hotkey starts the loop on the first press and stops it on subsequent presses. ```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 ``` -------------------------------- ### Activate Notepad or Calculator Source: https://www.autohotkey.com/docs/v2/lib/WinActivate.htm This example demonstrates how to activate Notepad if it exists, otherwise it activates the Calculator window. It utilizes WinExist to check for the window's presence before attempting activation. ```autohotkey if WinExist("Untitled - Notepad") WinActivate _; Use the window found by WinExist._ else WinActivate "Calculator" ``` -------------------------------- ### Get Transparency of Window Under Mouse - AutoHotkey v2 Source: https://www.autohotkey.com/docs/v2/lib/WinGetTransparent.htm This example retrieves the transparency of the window currently under the mouse cursor. It first gets the window handle using MouseGetPos and then passes it to WinGetTransparent. ```AutoHotkey MouseGetPos ,, &MouseWin TransDegree := WinGetTransparent(MouseWin) ``` -------------------------------- ### SplitPath Example: Fetching All Information Source: https://www.autohotkey.com/docs/v2/lib/SplitPath.htm Illustrates fetching all components of a file path using SplitPath, including filename, directory, extension, name without extension, and drive. All output variables must be prefixed with '&'. ```AutoHotkey FullFileName := "C:My DocumentsAddress List.txt" _; To fetch all info:_ SplitPath FullFileName, &name, &dir, &ext, &name_no_ext, &drive _; The above will set the variables as follows: ; name = Address List.txt ; dir = C:My Documents ; ext = txt ; name_no_ext = Address List ; drive = C:_ ``` -------------------------------- ### Get Logon Server Environment Variable Source: https://www.autohotkey.com/docs/v2/lib/EnvGet.htm Example of retrieving the 'LogonServer' environment variable and storing its value. ```AutoHotkey LogonServer := EnvGet("LogonServer") ``` -------------------------------- ### Launch a URL Source: https://www.autohotkey.com/docs/v2/lib/Run.htm Open a web address in the user's default browser. ```autohotkey Run "https://www.google.com" ``` -------------------------------- ### Basic RegEx Match Source: https://www.autohotkey.com/docs/v2/lib/RegExMatch.htm Finds the first occurrence of a pattern in a string and returns its starting position. Requires no special setup. ```autohotkey MsgBox RegExMatch("xxxabc123xyz", "abc.*xyz") ``` -------------------------------- ### Launch Internet Explorer with ComObject Source: https://www.autohotkey.com/docs/v2/lib/ComObject.htm This example demonstrates launching an instance of Internet Explorer, making it visible, and navigating to a specific URL using the ComObject function. ```autohotkey ie := ComObject("InternetExplorer.Application") ie.Visible := true _; This is known to work incorrectly on IE7._ ie.Navigate("https://www.autohotkey.com/") ``` -------------------------------- ### Create and Assign MenuBar with Submenus Source: https://www.autohotkey.com/docs/v2/lib/Gui.htm Example demonstrating how to create Menu objects, add items with shortcuts, combine them into a MenuBar, and assign it to a GUI. ```AutoHotkey FileMenu := Menu() FileMenu.Add("&Open\tCtrl+O", (*) => FileSelect()) _; See remarks below about Ctrl+O._ FileMenu.Add("E&xit", (*) => ExitApp()) HelpMenu := Menu() HelpMenu.Add("&About", (*) => MsgBox("Not implemented")) Menus := MenuBar() Menus.Add("&File", FileMenu) _; Attach the two submenus that were created above._ Menus.Add("&Help", HelpMenu) MyGui := Gui() MyGui.MenuBar := Menus MyGui.Show("w300 h200") ``` -------------------------------- ### Get Collected Input Text Source: https://www.autohotkey.com/docs/v2/lib/InputHook.htm Retrieves any text collected since the input was last started. This can be used while input is in progress or after it has ended. ```AutoHotkey String := InputHookObj.Input ``` -------------------------------- ### Load, Call, and Free DLL Example Source: https://www.autohotkey.com/docs/v2/lib/DllCall.htm Demonstrates loading a DLL, making repeated calls to a function within it, and then freeing the DLL to conserve memory. This avoids repeated LoadLibrary and FreeLibrary calls within a loop. ```autohotkey hModule := DllCall("LoadLibrary", "Str", "MyFunctions.dll", "Ptr") _; Avoids the need for DllCall in the loop to load the library. entire_loop_body_here Loop Files, "C:My Documents*.*", "R" result := DllCall("MyFunctionsBackupFile", "Str", A_LoopFilePath) DllCall("FreeLibrary", "Ptr", hModule) _; To conserve memory, the DLL may be unloaded after using it. ``` -------------------------------- ### Get Primary Monitor Number Source: https://www.autohotkey.com/docs/v2/lib/MonitorGetPrimary.htm Use MonitorGetPrimary to retrieve the primary monitor's number. This is always 1 in single-monitor setups. ```AutoHotkey Primary := MonitorGetPrimary() ``` -------------------------------- ### RemoveAt: Example of removing multiple items Source: https://www.autohotkey.com/docs/v2/lib/Array.htm Demonstrates removing two items starting at index 1 from an array with a missing element, and accessing the final element. ```autohotkey x := ["A", , "C"] MsgBox x.RemoveAt(1, 2) ; 1 MsgBox x[1] ; C ``` -------------------------------- ### Show GUI Window with Options Source: https://www.autohotkey.com/docs/v2/lib/Gui.htm Use the Show method to display a GUI window with specified options for size, position, and state. If omitted on the first call, options like width, height, and position will be auto-calculated. ```AutoHotkey MyGui.Show("xCenter y0") ``` ```AutoHotkey MyGui.Show("AutoSize Center") ``` ```AutoHotkey MyGui.Show("Hide x55 y66 w300 h200") ``` -------------------------------- ### Get Controller Button State Source: https://www.autohotkey.com/docs/v2/lib/GetKeyState.htm Retrieves the current physical state of a specific controller button. This example checks the second button on the first controller (Joy2). ```AutoHotkey state := GetKeyState("Joy2") ``` -------------------------------- ### Launch Notepad using Run Function Source: https://www.autohotkey.com/docs/v2/howto/RunPrograms.htm Launches Notepad directly. This is a basic example of the Run function. For practical use, consider assigning this to a hotkey. ```autohotkey Run "C:\Windows\notepad.exe" ``` -------------------------------- ### Get 8.3 Short Path Name Source: https://www.autohotkey.com/docs/v2/lib/FileGetAttrib.htm This example demonstrates how to retrieve the 8.3 short name of a file using a file loop and the A_LoopFileShortPath built-in variable. ```AutoHotkey Loop Files, "C:My DocumentsAddress List.txt" ShortPathName := A_LoopFileShortPath _; Will yield something similar to C:MYDOCU~1ADDRES~1.txt_ ``` -------------------------------- ### EditGetCurrentCol - Get Caret Column Source: https://www.autohotkey.com/docs/v2/lib/EditGetCurrentCol.htm Retrieves the current column number of the caret within an edit control. If text is selected, it returns the starting column of the selection. ```APIDOC ## EditGetCurrentCol ### Description Returns the column number in an edit control where the caret resides. ### Method Call ### Endpoint N/A (Function Call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```autohotkey CurrentCol := EditGetCurrentCol(ControlID , WinTitle, WinText, ExcludeTitle, ExcludeText) ``` ### Response #### Success Response (200) - **Return Value** (Integer) - The column number where the caret resides (1-based index). If text is selected, it's the starting column of the selection. #### Response Example ```json { "example": "3" } ``` ### Error Handling An exception is thrown on failure, or if the window or control could not be found. ### Remarks This function works best with common or predefined Microsoft controls; some applications use custom or modified controls, in which case the function might not work as expected. ### Related EditGetCurrentLine, EditGetLineCount, EditGetLine, EditGetSelectedText, EditPaste, Control functions ``` -------------------------------- ### Create Directory with Parent Directories Source: https://www.autohotkey.com/docs/v2/lib/DirCreate.htm This example demonstrates creating a new directory, including any necessary parent directories, using the DirCreate function. The path specified is an absolute path. ```autohotkey DirCreate "C:Test1My ImagesFolder2" ``` -------------------------------- ### Inspect Built-in Function - AutoHotkey v2 Source: https://www.autohotkey.com/docs/v2/lib/Func.htm This example demonstrates how to use the InspectFn function to get information about a built-in function like StrLen. It shows how to check if a function is built-in or user-defined. ```AutoHotkey InspectFn StrLen InspectFn InspectFn InspectFn(fn) { _; Display information about the passed function._ MsgBox fn.Name "() is " (fn.IsBuiltIn ? "built-in." : "user-defined.") } ``` -------------------------------- ### Display Environment Variables with cmd Source: https://www.autohotkey.com/docs/v2/howto/RunPrograms.htm Launch a command prompt to display environment variables starting with 'pro' using the 'Run' command. This example illustrates how processes inherit environment variables from their parent. ```autohotkey Run "cmd /k set pro" ``` -------------------------------- ### FormatTime Examples Source: https://www.autohotkey.com/docs/v2/lib/FormatTime.htm Demonstrates different usages of the FormatTime function for displaying current and specified date/time information in various formats. ```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 ``` ```AutoHotkey TimeString := FormatTime(, "Time") MsgBox "The current time is " TimeString ``` ```AutoHotkey TimeString := FormatTime("T12", "Time") MsgBox "The current 24-hour time is " TimeString ``` ```AutoHotkey TimeString := FormatTime(, "LongDate") MsgBox "The current date (long format) is " TimeString ``` ```AutoHotkey TimeString := FormatTime(20050423220133, "dddd MMMM d, yyyy hh:mm:ss tt") MsgBox "The specified date and time, when formatted, is " TimeString ``` ```AutoHotkey MsgBox FormatTime(200504, "'Month Name': MMMM`n'Day Name': dddd") ``` ```AutoHotkey YearWeek := FormatTime(20050101, "YWeek") MsgBox "January 1st of 2005 is in the following ISO year and week number: " YearWeek ``` -------------------------------- ### Get Active Track Number from Winamp Source: https://www.autohotkey.com/docs/v2/lib/SendMessage.htm Asks Winamp for the currently active track number. Winamp's track count starts at 0, so adjust by 1. Requires SetTitleMatchMode 2. ```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." ``` -------------------------------- ### Require Specific Version and Architecture Source: https://www.autohotkey.com/docs/v2/lib/_Requires.htm This example combines version and architecture requirements, ensuring the script runs on v2.0-rc.2 or later and only with a 64-bit interpreter. ```autohotkey #Requires AutoHotkey v2.0-rc.2 64-bit ``` -------------------------------- ### Get COM Object Class Name - AutoHotkey v2 Source: https://www.autohotkey.com/docs/v2/lib/ComObjQuery.htm This example demonstrates how to retrieve the class name of a COM object by querying for the IProvideClassInfo interface and then using ComCall to extract type information. ```autohotkey obj := ComObject("Scripting.Dictionary") MsgBox "Interface name: " ComObjType(obj, "name") IID_IProvideClassInfo := "{B196B283-BAB4-101A-B69C-00AA00341D07}" _; Request the object's IProvideClassInfo interface._ try pci := ComObjQuery(obj, IID_IProvideClassInfo) catch { MsgBox "IProvideClassInfo interface not supported." return } _; Call GetClassInfo to retrieve a pointer to the ITypeInfo interface._ ComCall(3, pci, "ptr*", &ti := 0) _; Wrap ti to ensure automatic cleanup._ ti := ComValue(13, ti) _; Call GetDocumentation to get the object's full type name._ ComCall(12, ti, "int", -1, "ptr*", &pname := 0, "ptr", 0, "ptr", 0, "ptr", 0) _; Convert the BSTR pointer to a usable string._ name := StrGet(pname, "UTF-16") _; Clean up._ DllCall("oleaut32SysFreeString", "ptr", pname) pci := ti := "" _; Display the type name!_ MsgBox "Class name: " name ``` -------------------------------- ### Simple Auto-Complete Example Source: https://www.autohotkey.com/docs/v2/lib/InputHook.htm This script provides a basic auto-completion feature. Start typing a day of the week, press Tab to complete, or Esc to exit. It uses InputHook to capture characters and key presses. ```AutoHotkey WordList := "Monday`nTuesday`nWednesday`nThursday`nFriday`nSaturday`nSunday" Suffix := "" SacHook := InputHook("V", "{Esc}") SacHook.OnChar := SacChar SacHook.OnKeyDown := SacKeyDown SacHook.KeyOpt("{Backspace}", "N") SacHook.Start() SacChar(ih, char) _; Called when a character is added to SacHook.Input. _ { global Suffix := "" if RegExMatch(ih.Input, "`nm)\w+$", &prefix) && RegExMatch(WordList, "`nmi)^" prefix[0] "\K.*", &Suffix) Suffix := Suffix[0] if CaretGetPos(&cx, &cy) ToolTip Suffix, cx + 15, cy else ToolTip Suffix _; Intercept Tab only while we're showing a tooltip. _ ih.KeyOpt("{Tab}", Suffix = "" ? "-NS" : "+NS") } SacKeyDown(ih, vk, sc) { if (vk = 8) _; Backspace_ SacChar(ih, "") else if (vk = 9) _; Tab_ Send "{Text}" Suffix } ``` -------------------------------- ### Launch This PC using CLSID Source: https://www.autohotkey.com/docs/v2/lib/Run.htm Opens 'This PC' (formerly 'My Computer') by executing its CLSID. ```autohotkey Run "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}" ``` -------------------------------- ### Get Audio Peak Value Source: https://www.autohotkey.com/docs/v2/lib/SoundGetInterface.htm This example demonstrates retrieving the peak audio value using the IAudioMeterInformation interface. It continuously updates a tooltip with the peak value and releases the interface when done or if an error occurs. ```AutoHotkey ; IAudioMeterInformation_ audioMeter := SoundGetInterface("{C02216F6-8C67-4B5B-9D00-D008E73E0064}") if audioMeter { try loop _; Until the script exits or an error occurs._ { _; audioMeter->GetPeakValue(&peak)_ ComCall 3, audioMeter, "float*", &peak:=0 ToolTip peak > 0 ? peak : "" Sleep 15 } ObjRelease audioMeter } else MsgBox "Unable to get audio meter" ``` -------------------------------- ### Get AutoHotkey Executable Path Source: https://www.autohotkey.com/docs/v2/Variables.htm Retrieves the full path of the running AutoHotkey executable. For compiled scripts, it points to the script itself. For non-compiled scripts, it points to the AutoHotkey.exe. This example shows how to construct the path manually. ```AutoHotkey InstallDir := RegRead("HKLMSOFTWAREAutoHotkey", "InstallDir", "") AhkPath := InstallDir ? InstallDir "AutoHotkey.exe" : "" ``` -------------------------------- ### Initialize GUI and Tray Menu Source: https://www.autohotkey.com/docs/v2/scripts/KeyboardOnScreen.ahk Sets up the GUI window properties, font, and customizes the tray icon menu. The GUI is configured as a tool window, always on top, and disabled to prevent interaction with itself. ```autohotkey MyGui := Gui("-Caption +ToolWindow +AlwaysOnTop +Disabled") MyGui.SetFont("s" k_FontSize " " k_FontStyle, k_FontName) MyGui.MarginY := 0, MyGui.MarginX := 0 A_TrayMenu.Delete() A_TrayMenu.Add(k_MenuItemHide, k_ShowHide) A_TrayMenu.Add("&Exit", (*) => ExitApp()) A_TrayMenu.Default := k_MenuItemHide ``` -------------------------------- ### Retrieve Transparent Color of Window Under Mouse - AutoHotkey v2 Source: https://www.autohotkey.com/docs/v2/lib/WinGetTransColor.htm This example demonstrates how to get the transparent color of the window currently under the mouse cursor. It first retrieves the window handle using MouseGetPos and then passes it to WinGetTransColor. ```AutoHotkey MouseGetPos ,, &MouseWin TransColor := WinGetTransColor(MouseWin) ``` -------------------------------- ### Send Keys Example Source: https://www.autohotkey.com/docs/v2/lib/Send.htm Demonstrates basic usage of Send, SendText, SendEvent, SendInput, and SendPlay commands. These commands simulate keystrokes and mouse clicks to the active window. ```AutoHotkey Send Keys SendText Keys SendEvent Keys SendInput Keys SendPlay Keys ``` -------------------------------- ### Demonstrate WinSetTransparent and WinSetTransColor Source: https://www.autohotkey.com/docs/v2/lib/WinSetTransparent.htm This example shows how to use WinSetTransparent and WinSetTransColor with hotkeys. It includes functions to make the color under the mouse cursor invisible, turn off transparency, and display current transparency settings. ```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 } #o:: _; Press Win+O to turn off transparency for the window under the mouse._ { MouseGetPos ,, &MouseWin WinSetTransColor "Off", MouseWin } #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 Gui Title using GuiFromHwnd Source: https://www.autohotkey.com/docs/v2/lib/GuiFromHwnd.htm This example demonstrates how to create a GUI, show it, and then retrieve its title using GuiFromHwnd with the GUI's HWND. Ensure the GUI is created and shown before attempting to retrieve its object. ```AutoHotkey MyGui := Gui(, "Title of Window") MyGui.Add("Text",, "Some text to display.") MyGui.Show() MsgBox(GuiFromHwnd(MyGui.Hwnd).Title) ``` -------------------------------- ### Get Current Column in Edit Control Source: https://www.autohotkey.com/docs/v2/lib/EditGetCurrentCol.htm Retrieves the column number of the caret in an edit control. If text is selected, it returns the starting column of the selection. The first column is 1. Works best with common Microsoft controls. ```autohotkey CurrentCol := EditGetCurrentCol(ControlID , WinTitle, WinText, ExcludeTitle, ExcludeText) ``` -------------------------------- ### Create a Map with Initial Items Source: https://www.autohotkey.com/docs/v2/lib/Map.htm Use the Call static method to create a Map and initialize it with key-value pairs in a single step. This is an efficient way to populate a new map. ```AutoHotkey MapObj := Map.Call(Key1, Value1, Key2, Value2, ...) ``` -------------------------------- ### Open Notepad, Wait for it, then Wait for Close Source: https://www.autohotkey.com/docs/v2/lib/WinWaitClose.htm This example first runs Notepad, then waits for its window to appear using WinWait, and subsequently uses WinWaitClose to pause execution until the Notepad window is closed. ```autohotkey Run "notepad.exe" WinWait "Untitled - Notepad" WinWaitClose _; Use the window found by WinWait._ MsgBox "Notepad is now closed." ``` -------------------------------- ### Continuously Display Mouse Cursor Control Info Source: https://www.autohotkey.com/docs/v2/lib/ControlGetPos.htm This example uses a loop to continuously get the mouse position, identify the control under the cursor, and display its properties using ToolTip. It demonstrates the practical application of ControlGetPos in real-time. ```autohotkey Loop { Sleep 100 MouseGetPos ,, &WhichWindow, &WhichControl try ControlGetPos &x, &y, &w, &h, WhichControl, WhichWindow ToolTip WhichControl "`nX" X "`tY" Y "`nW" W "`t" H } ``` -------------------------------- ### Get Menu Item Count and Last Item ID Source: https://www.autohotkey.com/docs/v2/lib/Menu.htm Retrieves the number of items in a menu and the ID of the last item using `DllCall` with `GetMenuItemCount` and `GetMenuItemID`. This example demonstrates direct interaction with the underlying Windows API for menu information. ```autohotkey MyMenu := Menu() MyMenu.Add("Item 1", NoAction) MyMenu.Add("Item 2", NoAction) MyMenu.Add("Item B", NoAction) _; Retrieve the number of items in a menu. M item_count := DllCall("GetMenuItemCount", "ptr", MyMenu.Handle) _; Retrieve the ID of the last item. M last_id := DllCall("GetMenuItemID", "ptr", MyMenu.Handle, "int", item_count-1) MsgBox("MyMenu has " item_count " items, and its last item has ID " last_id) NoAction(*) { _; Do nothing. M } ``` -------------------------------- ### Open, Wait for, and Activate Notepad Source: https://www.autohotkey.com/docs/v2/misc/WinTitle.htm Demonstrates opening Notepad, waiting for its specific title, and then activating it using the last found window. ```autohotkey Run "Notepad" WinWait "Untitled - Notepad" WinActivate _; Use the window found by WinWait._ ``` -------------------------------- ### Activate Notepad or Another Window Source: https://www.autohotkey.com/docs/v2/lib/WinExist.htm This example demonstrates activating a window using WinExist to check for Notepad or another window specified by a variable. The space between the keyword and criterion can be omitted, especially useful with variables. ```autohotkey if WinExist("ahk_class Notepad") or WinExist("ahk_class" ClassName) WinActivate _; ``` -------------------------------- ### Disable Win Key Menu Activation Source: https://www.autohotkey.com/docs/v2/lib/A_MenuMaskKey.htm This example disables the left Win key's ability to activate the Start Menu while still allowing it to function as a modifier. It uses the vkE8 virtual key code, which is documented as unassigned and generally has no side effects. ```autohotkey ~LWin::Send "{Blind}{vkE8}" ``` -------------------------------- ### Wait for Notepad Window with Timeout Source: https://www.autohotkey.com/docs/v2/lib/WinWait.htm This example demonstrates opening Notepad and waiting up to 3 seconds for its window to appear. If the window is found, it's minimized; otherwise, a timeout message is displayed. The underscore `_` is used to refer to the window found by WinWait. ```autohotkey Run "notepad.exe" if WinWait("Untitled - Notepad", , 3) WinMinimize _; else MsgBox "WinWait timed out." ``` -------------------------------- ### Add and Use an IP Address Control in AutoHotkey v2 Source: https://www.autohotkey.com/docs/v2/lib/Gui.htm This example demonstrates how to add and interact with an IP address control. It includes functions to set and get the IP address, and event handlers for changes in the edit control and field modifications. Requires the 'ClassSysIPAddress32' control. ```AutoHotkey MyGui := Gui() IP := MyGui.Add("Custom", "ClassSysIPAddress32 r1 w150") IP.OnCommand(0x300, IP_EditChange) _; 0x300 = EN_CHANGE_ IP.OnNotify(-860, IP_FieldChange) _; -860 = IPN_FIELDCHANGED_ IPText := MyGui.Add("Text", "wp") IPField := MyGui.Add("Text", "wp y+m") MyGui.Add("Button", "Default", "OK").OnEvent("Click", OK_Click) MyGui.Show() IPCtrlSetAddress(IP, SysGetIPAddresses()[1]) OK_Click(*) { MyGui.Hide() MsgBox("You chose " IPCtrlGetAddress(IP)) ExitApp() } IP_EditChange(*) { IPText.Text := "New text: " IP.Text } IP_FieldChange(thisCtrl, NMIPAddress) { _; Extract info from the NMIPAddress structure._ iField := NumGet(NMIPAddress, 3*A_PtrSize + 0, "int") iValue := NumGet(NMIPAddress, 3*A_PtrSize + 4, "int") if (iValue >= 0) IPField.Text := "Field #" iField " modified: " iValue else IPField.Text := "Field #" iField " left empty" } IPCtrlSetAddress(GuiCtrl, 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, GuiCtrl) } IPCtrlGetAddress(GuiCtrl) { static WM_USER := 0x0400 static IPM_GETADDRESS := WM_USER + 102 AddrWord := Buffer(4) SendMessage(IPM_GETADDRESS, 0, AddrWord, GuiCtrl) IPPart := [] Loop 4 IPPart.Push(NumGet(AddrWord, 4 - A_Index, "UChar")) return IPPart[1] "." IPPart[2] "." IPPart[3] "." IPPart[4] } ``` -------------------------------- ### Install Keyboard Hook with Parameters Source: https://www.autohotkey.com/docs/v2/lib/InstallKeybdHook.htm Installs or uninstalls the keyboard hook using the Install and Force parameters. Use 'Install, Force' to reinstall the hook, giving it precedence over other processes. ```autohotkey InstallKeybdHook Install, Force ``` -------------------------------- ### Install AutoHotkey to Destination Directory Source: https://www.autohotkey.com/docs/v2/Program.htm Use the /installto or /to switch to directly install AutoHotkey to a specified destination directory. Ensure you are running this command from within the source directory. ```bash AutoHotkey_setup.exe /installto "%DESTINATION%" ``` ```bash AutoHotkey32.exe UX\install.ahk /to "%DESTINATION%" ```