└── docs ├── 404.htm ├── AHKL_DBGPClients.htm ├── ChangeLog.htm ├── Compat.htm ├── Concepts.htm ├── FAQ.htm ├── Functions.htm ├── HotkeyFeatures.htm ├── Hotkeys.htm ├── Hotstrings.htm ├── KeyList.htm ├── Language.htm ├── ObjList.htm ├── Objects.htm ├── Program.htm ├── Scripts.htm ├── Tutorial.htm ├── Variables.htm ├── howto ├── Install.htm ├── ManageWindows.htm ├── RunExamples.htm ├── RunPrograms.htm ├── SendKeys.htm └── WriteHotkeys.htm ├── index.htm ├── lib ├── A_Clipboard.htm ├── A_HotkeyModifierTimeout.htm ├── A_MaxHotkeysPerInterval.htm ├── A_MenuMaskKey.htm ├── Any.htm ├── Array.htm ├── Block.htm ├── BlockInput.htm ├── Break.htm ├── Buffer.htm ├── CallbackCreate.htm ├── CaretGetPos.htm ├── Catch.htm ├── Chr.htm ├── Class.htm ├── Click.htm ├── ClipWait.htm ├── ClipboardAll.htm ├── ComCall.htm ├── ComObjActive.htm ├── ComObjArray.htm ├── ComObjConnect.htm ├── ComObjFlags.htm ├── ComObjFromPtr.htm ├── ComObjGet.htm ├── ComObjQuery.htm ├── ComObjType.htm ├── ComObjValue.htm ├── ComObject.htm ├── ComValue.htm ├── Continue.htm ├── Control.htm ├── ControlAddItem.htm ├── ControlChooseIndex.htm ├── ControlChooseString.htm ├── ControlClick.htm ├── ControlDeleteItem.htm ├── ControlFindItem.htm ├── ControlFocus.htm ├── ControlGetChecked.htm ├── ControlGetChoice.htm ├── ControlGetClassNN.htm ├── ControlGetEnabled.htm ├── ControlGetFocus.htm ├── ControlGetHwnd.htm ├── ControlGetIndex.htm ├── ControlGetItems.htm ├── ControlGetPos.htm ├── ControlGetStyle.htm ├── ControlGetText.htm ├── ControlGetVisible.htm ├── ControlHide.htm ├── ControlHideDropDown.htm ├── ControlMove.htm ├── ControlSend.htm ├── ControlSetChecked.htm ├── ControlSetEnabled.htm ├── ControlSetStyle.htm ├── ControlSetText.htm ├── ControlShow.htm ├── ControlShowDropDown.htm ├── CoordMode.htm ├── Critical.htm ├── DateAdd.htm ├── DateDiff.htm ├── DetectHiddenText.htm ├── DetectHiddenWindows.htm ├── DirCopy.htm ├── DirCreate.htm ├── DirDelete.htm ├── DirExist.htm ├── DirMove.htm ├── DirSelect.htm ├── DllCall.htm ├── Download.htm ├── Drive.htm ├── DriveEject.htm ├── DriveGetCapacity.htm ├── DriveGetFileSystem.htm ├── DriveGetLabel.htm ├── DriveGetList.htm ├── DriveGetSerial.htm ├── DriveGetSpaceFree.htm ├── DriveGetStatus.htm ├── DriveGetStatusCD.htm ├── DriveGetType.htm ├── DriveLock.htm ├── DriveSetLabel.htm ├── DriveUnlock.htm ├── Edit.htm ├── EditGetCurrentCol.htm ├── EditGetCurrentLine.htm ├── EditGetLine.htm ├── EditGetLineCount.htm ├── EditGetSelectedText.htm ├── EditPaste.htm ├── Else.htm ├── Enumerator.htm ├── EnvGet.htm ├── EnvSet.htm ├── Error.htm ├── Exit.htm ├── ExitApp.htm ├── File.htm ├── FileAppend.htm ├── FileCopy.htm ├── FileCreateShortcut.htm ├── FileDelete.htm ├── FileEncoding.htm ├── FileExist.htm ├── FileGetAttrib.htm ├── FileGetShortcut.htm ├── FileGetSize.htm ├── FileGetTime.htm ├── FileGetVersion.htm ├── FileInstall.htm ├── FileMove.htm ├── FileOpen.htm ├── FileRead.htm ├── FileRecycle.htm ├── FileRecycleEmpty.htm ├── FileSelect.htm ├── FileSetAttrib.htm ├── FileSetTime.htm ├── Finally.htm ├── Float.htm ├── For.htm ├── Format.htm ├── FormatTime.htm ├── Func.htm ├── GetKeyName.htm ├── GetKeySC.htm ├── GetKeyState.htm ├── GetKeyVK.htm ├── GetMethod.htm ├── Goto.htm ├── GroupActivate.htm ├── GroupAdd.htm ├── GroupClose.htm ├── GroupDeactivate.htm ├── Gui.htm ├── GuiControl.htm ├── GuiControls.htm ├── GuiCtrlFromHwnd.htm ├── GuiFromHwnd.htm ├── GuiOnCommand.htm ├── GuiOnEvent.htm ├── GuiOnNotify.htm ├── HasBase.htm ├── HasMethod.htm ├── HasProp.htm ├── HotIf.htm ├── Hotkey.htm ├── Hotstring.htm ├── If.htm ├── ImageSearch.htm ├── InStr.htm ├── IniDelete.htm ├── IniRead.htm ├── IniWrite.htm ├── InputBox.htm ├── InputHook.htm ├── InstallKeybdHook.htm ├── InstallMouseHook.htm ├── Integer.htm ├── Is.htm ├── IsLabel.htm ├── IsObject.htm ├── IsSet.htm ├── KeyHistory.htm ├── KeyWait.htm ├── ListHotkeys.htm ├── ListLines.htm ├── ListVars.htm ├── ListView.htm ├── ListViewGetContent.htm ├── LoadPicture.htm ├── Loop.htm ├── LoopFiles.htm ├── LoopParse.htm ├── LoopRead.htm ├── LoopReg.htm ├── Map.htm ├── Math.htm ├── Menu.htm ├── MenuFromHandle.htm ├── MenuSelect.htm ├── Monitor.htm ├── MonitorGet.htm ├── MonitorGetCount.htm ├── MonitorGetName.htm ├── MonitorGetPrimary.htm ├── MonitorGetWorkArea.htm ├── MouseClick.htm ├── MouseClickDrag.htm ├── MouseGetPos.htm ├── MouseMove.htm ├── MsgBox.htm ├── NumGet.htm ├── NumPut.htm ├── Number.htm ├── ObjAddRef.htm ├── ObjBindMethod.htm ├── Object.htm ├── OnClipboardChange.htm ├── OnError.htm ├── OnExit.htm ├── OnMessage.htm ├── Ord.htm ├── OutputDebug.htm ├── Pause.htm ├── Persistent.htm ├── PixelGetColor.htm ├── PixelSearch.htm ├── PostMessage.htm ├── Process.htm ├── ProcessClose.htm ├── ProcessExist.htm ├── ProcessGetName.htm ├── ProcessGetParent.htm ├── ProcessSetPriority.htm ├── ProcessWait.htm ├── ProcessWaitClose.htm ├── Random.htm ├── RegCreateKey.htm ├── RegDelete.htm ├── RegDeleteKey.htm ├── RegExMatch.htm ├── RegExReplace.htm ├── RegRead.htm ├── RegWrite.htm ├── Reload.htm ├── Return.htm ├── Run.htm ├── RunAs.htm ├── Send.htm ├── SendLevel.htm ├── SendMessage.htm ├── SendMode.htm ├── SetControlDelay.htm ├── SetDefaultMouseSpeed.htm ├── SetKeyDelay.htm ├── SetMouseDelay.htm ├── SetNumScrollCapsLockState.htm ├── SetRegView.htm ├── SetStoreCapsLockMode.htm ├── SetTimer.htm ├── SetTitleMatchMode.htm ├── SetWinDelay.htm ├── SetWorkingDir.htm ├── Shutdown.htm ├── Sleep.htm ├── Sort.htm ├── Sound.htm ├── SoundBeep.htm ├── SoundGetInterface.htm ├── SoundGetMute.htm ├── SoundGetName.htm ├── SoundGetVolume.htm ├── SoundPlay.htm ├── SoundSetMute.htm ├── SoundSetVolume.htm ├── SplitPath.htm ├── StatusBarGetText.htm ├── StatusBarWait.htm ├── StrCompare.htm ├── StrGet.htm ├── StrLen.htm ├── StrLower.htm ├── StrPtr.htm ├── StrPut.htm ├── StrReplace.htm ├── StrSplit.htm ├── String.htm ├── SubStr.htm ├── Suspend.htm ├── Switch.htm ├── SysGet.htm ├── SysGetIPAddresses.htm ├── Thread.htm ├── Throw.htm ├── ToolTip.htm ├── TraySetIcon.htm ├── TrayTip.htm ├── TreeView.htm ├── Trim.htm ├── Try.htm ├── Type.htm ├── Until.htm ├── VarSetStrCapacity.htm ├── VerCompare.htm ├── While.htm ├── Win.htm ├── WinActivate.htm ├── WinActivateBottom.htm ├── WinActive.htm ├── WinClose.htm ├── WinExist.htm ├── WinGetClass.htm ├── WinGetClientPos.htm ├── WinGetControls.htm ├── WinGetControlsHwnd.htm ├── WinGetCount.htm ├── WinGetID.htm ├── WinGetIDLast.htm ├── WinGetList.htm ├── WinGetMinMax.htm ├── WinGetPID.htm ├── WinGetPos.htm ├── WinGetProcessName.htm ├── WinGetProcessPath.htm ├── WinGetStyle.htm ├── WinGetText.htm ├── WinGetTitle.htm ├── WinGetTransColor.htm ├── WinGetTransparent.htm ├── WinHide.htm ├── WinKill.htm ├── WinMaximize.htm ├── WinMinimize.htm ├── WinMinimizeAll.htm ├── WinMove.htm ├── WinMoveBottom.htm ├── WinMoveTop.htm ├── WinRedraw.htm ├── WinRestore.htm ├── WinSetAlwaysOnTop.htm ├── WinSetEnabled.htm ├── WinSetRegion.htm ├── WinSetStyle.htm ├── WinSetTitle.htm ├── WinSetTransColor.htm ├── WinSetTransparent.htm ├── WinShow.htm ├── WinWait.htm ├── WinWaitActive.htm ├── WinWaitClose.htm ├── _ClipboardTimeout.htm ├── _DllLoad.htm ├── _ErrorStdOut.htm ├── _HotIf.htm ├── _HotIfTimeout.htm ├── _Hotstring.htm ├── _Include.htm ├── _InputLevel.htm ├── _MaxThreads.htm ├── _MaxThreadsBuffer.htm ├── _MaxThreadsPerHotkey.htm ├── _NoTrayIcon.htm ├── _Requires.htm ├── _SingleInstance.htm ├── _SuspendExempt.htm ├── _UseHook.htm ├── _Warn.htm ├── _WinActivateForce.htm └── index.htm ├── license.htm ├── misc ├── Acknowledgements.htm ├── Ahk2ExeDirectives.htm ├── CLSID-List.htm ├── Colors.htm ├── DPIScaling.htm ├── Editors.htm ├── EscapeChar.htm ├── FontsStandard.htm ├── Functor.htm ├── ImageHandles.htm ├── Labels.htm ├── Languages.htm ├── LongPaths.htm ├── Macros.htm ├── Override.htm ├── Performance.htm ├── RegEx-QuickRef.htm ├── RegExCallout.htm ├── Remap.htm ├── RemapController.htm ├── SendMessage.htm ├── SendMessageList.htm ├── Styles.htm ├── Threads.htm ├── WinTitle.htm ├── Winamp.htm └── remove-userchoice.reg ├── scripts ├── ContextSensitiveHelp.ahk ├── ControllerMouse.ahk ├── ControllerTest.ahk ├── EasyWindowDrag.ahk ├── EasyWindowDrag_(KDE).ahk ├── EncodeHTML.ahk ├── FavoriteFolders.ahk ├── KeyboardOnScreen.ahk ├── MinimizeToTrayMenu.ahk ├── MsgBoxButtonNames.ahk ├── Numpad000.ahk ├── NumpadMouse.ahk ├── Seek_(SearchTheStartMenu).ahk ├── TooltipMouseMenu.ahk ├── UpDownCustomIncrements.ahk ├── VolumeOSD.ahk ├── WinLIRC.ahk ├── WindowShading.ahk └── index.htm ├── search.htm ├── settings.htm ├── static ├── ahk16.png ├── ahk16_pause.png ├── ahk16_pause_suspend.png ├── ahk16_suspend.png ├── ahk_logo.png ├── ahk_logo.svg ├── ahk_logo_no_text.png ├── ahkfile16.png ├── content.css ├── content.js ├── ctrl_button.png ├── ctrl_check.png ├── ctrl_combo.png ├── ctrl_datetime.png ├── ctrl_ddl.png ├── ctrl_edit.png ├── ctrl_group.png ├── ctrl_hotkey.png ├── ctrl_link.png ├── ctrl_list.png ├── ctrl_listview.png ├── ctrl_menu.png ├── ctrl_monthcal.png ├── ctrl_progress.png ├── ctrl_radio.png ├── ctrl_slider.png ├── ctrl_status.png ├── ctrl_tab.png ├── ctrl_text.png ├── ctrl_treeview.png ├── ctrl_updown.png ├── dark.css ├── dlg_file.png ├── dlg_folder.png ├── dlg_input.png ├── dlg_message.png ├── dlg_tooltip.png ├── dlg_traytip.png ├── fonts │ ├── icons.eot │ ├── icons.svg │ ├── icons.ttf │ └── icons.woff ├── highlighter │ ├── dark.css │ ├── highlighter.css │ ├── highlighter.js │ └── light.css ├── sound_levels.png ├── source │ ├── build_search.ahk │ ├── check_data.ahk │ ├── data_deprecate.js │ ├── data_index.js │ ├── data_search.js │ ├── data_toc.js │ └── data_translate.js └── theme.css ├── v1-changes.htm └── v2-changes.htm /docs/404.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |
6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |Looks like the document you're looking for doesn't exist.
16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /docs/AHKL_DBGPClients.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Additional debugging features are supported via DBGp, a common debugger protocol for languages and debugger UI communication. See Interactive Debugging for more details. Some UIs or "clients" known to be compatible with AutoHotkey are listed on this page:
16 |SciTE4AutoHotkey is a free, SciTE-based AutoHotkey script editor. In addition to DBGp support, it provides syntax highlighting, calltips/parameter info and auto-complete for AutoHotkey, and other useful editing features and scripting tools.
27 |Debugging features include:
28 |https://www.autohotkey.com/scite4ahk/
38 | 39 |The vscode-autohotkey-debug extension enables Visual Studio Code to act as a debugger client for AutoHotkey. The extension has support for all basic debugging features as well as some more advanced features, such as breakpoint directives (as comments) and conditional breakpoints.
41 | 42 |XDebugClient is a simple open-source front-end DBGp client based on the .NET Framework 2.0. XDebugClient was originally designed for PHP with Xdebug, but a custom build compatible with AutoHotkey is available below.
44 |Changes:
45 |Download: Binary; Source Code (also see SharpDevelop, Dockpanel Suite and Advanced TreeView.)
52 |Usage:
53 |Features:
61 |Issues:
69 |A DBGp client is available as a plugin for Notepad++ 32-bit. It is designed for PHP, but also works with AutoHotkey. The plugin has not been updated since 2012, and is not available for Notepad++ 64-bit.
76 |Download: See DBGp plugin for Notepad++.
77 |Usage:
78 |Note: File Mapping must be configured. Most users will not be debugging remotely, and therefore may simply put a checkmark next to Bypass all mapping (local windows setup).
82 |Features:
90 |Issues:
101 |a
will attempt to retrieve a
or a
.A script-based DBGp library and example clients are available from GitHub.
GitHub: Lexikos / dbgp
114 |The DebugVars script provides a graphical user interface for inspecting and changing the contents of variables and objects in any running script (except compiled scripts). It also serves as a demonstration of the dbgp.ahk library.
115 |GitHub: Lexikos / DebugVars
116 | 117 |A command-line client is available from xdebug.org, however this is not suitable for most users as it requires a decent understanding of DBGp (the protocol).
119 | 120 |A number of other DBGp clients are available, but have not been tested with AutoHotkey. For a list, see Xdebug: Documentation.
122 | 123 | 124 | 125 | -------------------------------------------------------------------------------- /docs/ChangeLog.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Changes from v1.1 to v2.0 covers the differences between v1.1 and v2.0.
15 |For full technical details of changes, refer to GitHub.
16 | 17 |Fixed memory out-of-bounds access during RegEx compilation.
19 |Fixed externally-released modifiers to not be "restored" post-Send.
20 |Fixed modal dialog boxes suppressing InputHook events.
21 |Fixed key-up erroneously being suppressed after key-repeat presses it down in some cases.
22 |Fixed Critical Error when loading large icons with no alpha channel.
23 |Fixed MouseGetPos to make Control blank and not throw if ClassNN cannot be determined.
24 |Fixed FileSelect to validate Options.
25 |Fixed unexpected Catch/Else/Finally/Until not being flagged as an error in some cases.
26 |Fixed Try/Catch/Else/Finally not executing Finally if Else returns.
27 |Fixed execution of if-else-if-else-if containing fat arrow functions.
28 | 29 |Fixed A_Clipboard silently exiting when GetClipboardData returns NULL.
31 |Fixed a.b[c] := d
to invoke the getter for a.b
if there is no setter.
Implemented an optimization to the WinText parameter by Descolada. [PR #335]
35 |Changed UnsetError message to suggest a global declaration instead of appending "(same name as a global)" after the variable name.
36 |Changed VarUnset warning message for consistency with UnsetError.
37 |Fixed the increment/decrement operators to throw UnsetError if the var is unset, not TypeError.
38 |Fixed OwnProps to assign the property name safely in cases where a property deletes itself.
39 |Fixed breakpoints to work in arrow functions under a control flow statement without a block.
40 |Fixed debugger to break at the line of the call when stepping out of a function. (This behaviour was added in Revision 31 and broken by v1.1.30.00.)
41 |Stepping out of a function which was called as a new thread now breaks at the line which was interrupted, instead of waiting until the next line is reached.
42 |Fixed debugger to not delete temporary breakpoints which are ignored while evaluating DBGp property_get or context_get.
43 | 44 |Fixed load-time errors sent to stdout showing incorrect file/line number in some cases.
46 |Fixed ExitApp on load-time error/warning dialogs to use exit code 2.
47 |Fixed locating WindowSpy.ahk in Current User (non-admin) installs.
48 |Fixed DBGp property_get paging items incorrectly (again).
49 |Fixed StrPut failing if Length/Buffer is specified and MultiByteToWideChar doesn't support the WC_NO_BEST_FIT_CHARS flag for the target codepage.
50 |Fixed Download to attempt anonymous authentication if the server requests client authentication.
51 | 52 |Fixed DBGp property_get failing to retrieve properties due to incorrect paging (since v2.0.14).
54 |Fixed DBGp property evaluation causing Try without Catch to fail (since v2.0.14).
55 |Fixed <base> debugger pseudo-property leaking a reference (since v2.0.14).
56 | 57 |Fixed the error dialog to handle letter key shortcuts even when text is focused.
59 |Fixed MonthCal W-n (number of month) width values to not be affected by DPI scaling.
60 |Fixed Click to not return an integer.
61 |Fixed detection of key::try {
as an error.
Fixed :B0*O:XY::Z
to produce XYZ rather than XZ (suppressing Y).
Fixed Send to leave any prior {modifier Down}
in effect even if the key happens to be physically held down.
Improved the reliability of the script taking focus when a menu popup is shown.
65 | 66 |Debugger improvements:
67 |Fixed stdout/stderr packets sent during the processing of another command to not corrupt the pending response.
68 |Fixed property_get -n <exception>.message
and similar.
Fixed corrupted results from property_get when a property returns a temporary object with a string, such as x.y.z
where y => {z:"a"}
.
Fixed crashes when an asynchronous command is received during the processing of another command.
71 |Fixed exceptions not being deleted after they are suppressed via property_set.
72 |Fixed property_get -c 0 -d 0
to allow global variables, as already allowed by -d 1
.
Fixed property_get paging enumerated items incorrectly.
74 | 75 |Improved property_get to support property getters with one parameter (previously only the implicit __Item property supported this).
76 |Improved property_get to support properties of primitive values. The value must still be contained by a variable or returned from a property.
77 |Improved property_get to allow calling functions with <=1 parameter.
78 |Improved property_get to support float keys/parameters.
79 | 80 |Changed debugger to suppress exceptions during property evaluation.
81 |Changed debugger to ignore errors thrown by __Enum (treat as no items).
82 |Changed the <enum> pseudo-property to require __Enum. This prevents the object itself from being called as an enumerator.
83 |Small code size optimizations in the debugger.
84 | 85 |Changed Hotkey function to throw ValueError if Options contains an invalid option.
87 |Fixed InputHook to respect the +S option for Backspace when acting as undo.
88 |Fixed debugger to safely handle property deletion during enumeration.
89 |Fixed OLE clipboard content (e.g. error dialog text) being lost on exit.
90 |Fixed detection of invalid suffix on a hotkey, such as Hotkey "a pu"
.
Fixed DllCall AStr*
arg type to copy back only if address changes.
Fixed #Include to correctly "close" any built-in variable it reads (no known impact on real-world scripts).
93 |Fixed WinTitles with two different ahk_id values to yield no match.
94 | 95 |Fixed Gui GetPos/GetClientPos when Gui has an owner window or +DPIScale.
97 |Fixed Until preventing subfolder recursion in file loops.
98 |Fixed DllCall to throw when arg type is UStr.
99 |Fixed a memory leak occurring for each regex callout.
100 |Fixed Send erroneously releasing a modifier due to a race condition. For example, ~LAlt::Send "{Blind}x"
intermittently released LAlt if some other keyboard hook was installed more recently than the script's own hook.
Fixed icon loader to prefer higher bit-depth when multiple bitmaps of the same size are present.
102 |Fixed SendInput failing to release LCtrl if it had already released RAlt and the layout does not have AltGr.
103 |Fixed key-up hotkeys not firing if the key repeats after modifiers change. For example, F1::Send "{Ctrl down}"
should allow F1 up::
to execute when the key is released even though Ctrl is down, but was not allowing it after key-repeat occurs.
Fixed an error message to refer to #HotIf rather than #IfWin. [PR #327]
105 |Fixed OwnProps erroneously skipping properties with optional parameters.
106 |Fixed inconsistent behaviour of cloned dynamic properties.
107 |a.b[c]
to evaluate as (a.b)[c]
).Fixed SysGetIPAddresses causing a Critical Error when the network subsystem is non-functional; e.g. in Windows safe mode.
112 |Changed ControlGetFocus to return 0 when focus can't be determined, such as when a console window is active.
113 | 114 |Added a workaround for the first shown menu not accepting keyboard input on Windows 10.
116 |Fixed the Add method (Gui) to support the ShortDate option for DateTime controls.
117 |Fixed a reference counting error with multi-level function nesting.
118 |Fixed #include <x>
causing a load-time crash if used inside a function.
Fixed ListView.Opt("NoSort")
.
Fixed a memory leak occurring when an object with no own properties is cloned.
121 |Fixed #include and FileInstall (non-compiled) to compare file names ordinally, not linguistically.
122 | 123 |Fixed crashing when a named function hotkey is used after #HotIf.
125 |Fixed numeric literals ending with a dot to not cause line continuation.
126 |Fixed pre-increment/decrement to work with chained array indexing.
127 |Fixed OnNotify/OnCommand applying styles only applicable to OnEvent.
128 |Fixed FileExist/DirExist leaking handles when emptydir\*
is used.
Fixed DirExist leaking handles when only files match.
130 | 131 |Fixed stacking of hotstrings with the X option.
133 |Fixed debugger not listing local vars if the function is at the bottom of the stack.
134 |Fixed Gui threads to show on the debugger's call stack.
135 |Fixed some combinations of &/ByRef causing stack overflow in ExitApp.
136 | 137 |Fixed ByRef parameters erroneously assigning the default value to the caller's VarRef if unset.
139 |Fixed some issues affecting suppressed Alt/Ctrl/Shift/Win hotkeys, such as:
140 |*LCtrl::
blocked LCtrl from the active window, but sending Alt-key combinations would fail because the system thinks Ctrl is down, and would therefore send WM_KEYDOWN instead of WM_SYSKEYDOWN.*LAlt::
caused the system to forget any prior {LAlt DownR}
, so a remapping such as LCtrl::LAlt
would not behave correctly while LAlt is physically down, even though LAlt was suppressed.Fixed some issues affecting continuation sections:
146 |````
to become one literal `
instead of two, ``n
to become a linefeed, and similar.`"
or `'
produced a literal backtick and ended the string, instead of producing a literal quote mark, if the continuation section was enclosed in quotes of the same type and lacked the `
option.Optimized the automatic escaping of quote marks and backtick in continuation sections.
151 |Fixed breakpoint_list (debugger) returning duplicates on lines containing fat arrow functions.
152 |Fixed +BackgroundDefault
failing to override the Gui's BackColor property.
Fixed MouseClickDrag to allow X1 and Y1 to be omitted.
156 |Fixed mouse AltTab hotkeys not suppressing execution of a prefix hotkey, such as 1::
for 1 & WheelDown::AltTab
. (Broken by v2.0.4)
Fixed hook hotkeys not recognizing modifiers which are pressed down by SendInput.
158 |Fixed A_AhkPath to not be reliant on the case/format of the command line used to launch the process.
159 |Fixed heap corruption during window searches involving groups. (Broken by v2.0.6)
160 |Launcher
161 |Fixed #Requires not being detected if followed by a comment other than ; prefer xxx
. (Broken by v2.0.6)
Fixed syntax detection misinterpreting multi-line auto-replace hotstrings.
163 |Window Spy
164 |Changed font to Segoe UI size 9, consistent with Dash.
165 | 166 |Fixed some ambiguity with COM calls, such as x.y
acting as x.y()
.
Fixed breakpoint on control flow statement being "hit" when a fat arrow function on the line below it returns.
169 |Fixed Default :
to not merge with the line below it. This prevented Default :
from being used at the end of a Switch block, and caused any subsequent line to take the line number of the Default.
Optimized ProcessGetPath, ProcessSetPriority and ProcessClose to not scan through all processes when given a valid PID, even if access to the process is denied.
171 |Fixed inability of LWin::Alt
to be used to activate some Alt key combos.
Fixed TypeError thrown by x is y
to say "Class" rather than "Object".
Fixed WinTitle to support criteria longer than 1023 characters.
174 |Fixed issues when &ref
is used on different aliases of the same variable.
Fixed optional parameter default expressions (other than simple literal values) preventing the use of assume-global/assume-static.
176 | 177 |Fixed a memory leak caused by incorrect reference counting when an object is enumerated via COM. [PR# 325]
179 |Fixed internal calls to __Enum to not call __Call.
180 |Fixed error messages referring to parameter #65535.
181 |Fixed incorrect IEnumVARIANT return count.
182 |Fixed Download throwing OSError(0) when error should be non-zero.
183 |Fixed LV.Add/Insert/Modify crashing when passed the minimum number of parameters.
184 |Fixed stack traces to exclude calls to __new for Error subclasses.
185 | 186 |Changed the Reload button on error/warning dialogs to explicitly close the dialog, even if the current script instance isn't terminated.
188 |Removed an optimization for return var
which caused the variable to appear blank when accessed within a finally
block.
Fixed Default (Switch) to allow space before the colon.
190 |Fixed Array.Prototype.RemoveAt to return the removed value when Length is "explicitly omitted" with unset
or var?
.
Fixed crashing when a ComObject is passed to a for-loop with only the second variable specified.
192 |Changes merged from v1.1.37.00 and v1.1.37.01:
193 |Changed COM method and property calls to pass large integers as VT_I8, not VT_R8 (floating-point), so the original type and precision is retained. Integers in the 32-bit range are still passed as VT_I4.
194 |Added support for multi-variable enumerators (for-loops) with IDispatch-wrapped AutoHotkey objects. Both the script invoking the object and the object itself must be running a supported AutoHotkey version.
195 |Fixed omitted parameters to receive their default values rather than the "optional argument marker" when an AutoHotkey method is called via IDispatch (COM). The reverse translation was already done when calling COM methods in previous versions.
196 |Fixed VerCompare(a, ">" b)
and reduced code size marginally.
Fixed AltTab-related load-time errors to be consistent with other errors.
198 |Fixed errors thrown by a ComObject wrapper not being propagated correctly if it is called via an object/COM.
199 |Fixed the Hotkey GUI control to allow setting the symbols ^
, !
and +
as hotkeys.
Fixed the Hotkey control to include modifiers when its value is set to a symbol.
201 |Fixed potential misbehaviour of InputHook.KeyOpt() with single chars.
202 |Fixed a bug with custom combos where a set of hotkeys like a & b::
, a::
and a up::
would fail to suppress the release of a if a::
alone is disabled with #HotIf.
Fixed a bug where a key-down event is correctly suppressed by a hotkey, but sending an additional key-down with SendLevel > 0 would prevent the subsequent key-up from being suppressed, even if the sent event is ignored due to #InputLevel.
208 |Fixed a & b up::
not suppressing b if a & b::
is present but disabled by #HotIf.
Fixed an issue with hotkeys not firing due to a race condition. If a modifier hotkey such as ~*RWin::
called Send or GetKeyState too soon, the OS could report that RWin isn't down, so the hook's modifier state would be "corrected" and hotkeys would wrongly fire or fail to fire. This was likely to occur only if another keyboard hook was installed more recently than the script's own hook, since in that case the OS would not update key state until the other hook's thread has resumed and returned.
Fixed hotstrings to use the Last Found Window set by #HotIf.
211 |Fixed an issue where any attempt to reinstall the keyboard or mouse hook would fail if the OS had automatically uninstalled the hook. It is still necessary to meet certain conditions before any such attempt can be made.
212 |Optimized allocation of cached COM property names for built-in IDispatch.
213 |Refactored code to support a build configuration for AutoHotkey as a DLL.
214 | 215 |Fixed Hotkey("a", "b")
to use the original function of "b", not "a". [PR #318]
Fixed FileSetAttribute crash when used in a File Reading Loop. [PR #323]
218 |Fixed duplicate Gui control name errors to correctly abort the thread.
219 |Fixed DateTime/MonthCal Range option not applying minimum value.
220 |Fixed s[x] => x
and other single-line properties starting with "s".
Fixed a bug with deleting a breakpoint on a static line containing =>
.
Fixed Button control not becoming default when clicked.
223 |Fixed PixelSearch to unset X when pixel is not found.
224 |Fixed hotstring with escape sequence causing next line to be skipped.
225 |Fixed WinTitle ignoring character 1 when "ahk_" is at character 2.
226 |Fixed remapping to utilize right-hand modifier already being down. For example, +x::+y
will no longer release RShift to press LShift.
Changed error message for a == b && c()
and similar cases to avoid alluding to legacy =
.
Improved error message for some cases of unintended line continuation.
229 |Fixed reserved words to be permitted as method names, as documented.
230 |Fixed duplicate OnMessage calls for some keyboard messages.
231 |Fixed inter-referenced closures being deleted prematurely.
232 |Fixed SetFont to permit leading spaces in the Options parameter.
233 |Fixed sending of {ASC nnnn}
.
Fixed a.base := a
to throw an error.
Fixed x.y := unset
causing crashes or undefined behaviour.
Fixed GuiControl.Move() to be relative to the GUI's client area even when the GUI is not its parent.
237 |Fixed Menu Add overwriting items which were appended by Menu Insert.
238 | Launcher 239 |Run Dash instead of showing the old Welcome page in the documentation, when run without parameters.
240 |Fixed version selection GUI raising an error if Enter is pressed without selecting a version. [PR UX/#4]
241 |Suppress errors when checking whether an absent version can be downloaded.
242 |Fixed absent version download prompt to not show the UAC shield if UAC is disabled.
243 |Fixed issues with #Requires interpretation.
244 |> >= < <= =
).Fixed the default installation directory for command-line use.
251 |Renamed the Start menu shortcut from "AutoHotkey" to "AutoHotkey Dash".
252 |Fixed EnableUIAccess when running as SYSTEM.
253 |Fixed EnableUIAccess to verify the private key when selecting a certificate.
254 | Dash 255 |Fixed Launch Config GUI to update the "Run as administrator" and "Run with UI access" options.
256 |Fixed Up/Down key handling in the Launch Config GUI.
257 | 258 |Fixed Short DllCall arg type and undefined behaviour for invalid types.
260 |Fixed (non-string) file version number for AutoHotkey binaries.
261 |Fixed parameter type errors to show the correct parameter number.
262 | 263 |Fixed Func.IsOptional(1) returning 0 in some cases where it shouldn't.
265 |Fixed Gui event handler functions to not drop the Gui parameter when the Gui is its own event sink.
266 |Fixed COM errors to not show "(null)" when no description is available.
267 |Fixed ToolTips intermittently appearing at the wrong position.
268 |Fixed __Enum(unset) to permit a second variable for Array, Match and Gui.
269 |Fixed #include <> error messages to show "Script library" rather than "Function library".
270 |Fixed new threads being unable to prevent a message check with Critical.
271 |Optimized conversion of DllCall type names.
272 |Made some trivial but effective code size optimizations.
273 | 274 |For a history of changes prior to the v2.0.0 release, refer to the following (but note some changes were superseded):
276 |This document contains some topics which are sometimes important when dealing with external libraries or sending messages to a control or window.
16 | 17 |Note: This section builds on topics covered in other parts of the documentation: Strings, String Encoding.
30 |Within a string (text value), the numeric character code and size (in bytes) of each character depends on the encoding of the string. These details are typically important for scripts which do any of the following:
31 |AutoHotkey v2 natively uses Unicode (UTF-16), but some external libraries or window messages might require ANSI strings.
38 |ANSI: Each character is one byte (8 bits). Character codes above 127 depend on your system's language settings (or the codepage chosen when the text was encoded, such as when it is written to a file).
39 |Unicode: Each character is two bytes (16 bits). Character codes are as defined by the UTF-16 format.
40 |Semantic note: Technically, some Unicode characters are represented by two 16-bit code units, collectively known as a "surrogate pair." Similarly, some ANSI code pages (commonly known as Double Byte Character Sets) contain some double-byte characters. However, for practical reasons these are almost always treated as two individual units (referred to as "characters" for simplicity).
41 | 42 |When allocating a Buffer, take care to calculate the correct number of bytes for whichever encoding is required. For example:
44 |ansi_buf := Buffer(capacity_in_chars) 45 | utf16_buf := Buffer(capacity_in_chars * 2)46 |
If an ANSI or UTF-8 string will be written into the buffer with StrPut, do not use StrLen to determine the buffer size, as the ANSI or UTF-8 length may differ from the native (UTF-16) length. Instead, use StrPut to calculate the required buffer size. For example:
47 |required_bytes := StrPut(source_string, "cp0") 48 | ansi_buf := Buffer(required_bytes) 49 | StrPut(source_string, ansi_buf)50 | 51 |
When the "Str" type is used, it means a string in the native format of the current build. Since some functions may require or return strings in a particular format, the following string types are available:
53 |Char Size | C / Win32 Types | Encoding | |
---|---|---|---|
WStr | 16-bit | wchar_t*, WCHAR*, LPWSTR, LPCWSTR | UTF-16 |
AStr | 8-bit | char*, CHAR*, LPSTR, LPCSTR | ANSI (the system default ANSI code page) |
Str | -- | TCHAR*, LPTSTR, LPCTSTR | Equivalent to WStr in AutoHotkey v2. |
If "Str" or "WStr" is used for a parameter, the address of the string is passed to the function. For "AStr", a temporary ANSI copy of the string is created and its address is passed instead. As a general rule, "AStr" should not be used for an output parameter since the buffer is only large enough to hold the input string.
60 |Note: "AStr" and "WStr" are equally valid for parameters and the function's return value.
61 |In general, if a script calls a function via DllCall which accepts a string as a parameter, one or more of the following approaches must be taken:
62 |DeleteFileA
and DeleteFileW
. Since DeleteFile
itself doesn't really exist, DllCall automatically tries DeleteFileW
:
64 | DllCall("DeleteFile", "Ptr", StrPtr(filename)) 65 | DllCall("DeleteFile", "Str", filename)66 |
In both cases, the address of the original unmodified string is passed to the function.
67 |In some cases this approach may backfire, as DllCall adds the W suffix only if no function could be found with the original name. For example, shell32.dll exports ExtractIconExW, ExtractIconExA and ExtractIconEx with no suffix, with the last two being equivalent. In that case, omitting the W suffix causes the ANSI version to be called.
DllCall("DeleteFileA", "AStr", filename) 70 | DllCall("DeleteFileW", "WStr", filename)
When NumPut or NumGet are used with strings, the offset and type must be correct for the given type of string. The following may be used as a guide:
76 |; 8-bit/ANSI strings: size_of_char=1 type_of_char="UChar" 77 | ; 16-bit/UTF-16 strings: size_of_char=2 type_of_char="UShort" 78 | nth_char := NumGet(buffer_or_address, (n-1)*size_of_char, type_of_char) 79 | NumPut(type_of_char, nth_char, buffer_or_address, (n-1)*size_of_char)80 |
For the first character, n should have the value 1.
81 | 82 |Pointers are 4 bytes in 32-bit builds and 8 bytes in 64-bit builds. Scripts using structures or DllCalls may need to account for this to run correctly on both platforms. Specific areas which are affected include:
84 |For size and offset calculations, use A_PtrSize. For DllCall, NumPut and NumGet, use the Ptr type where appropriate.
90 |Remember that the offset of a field is usually the total size of all fields preceding it. Also note that handles (including types like HWND and HBITMAP) are essentially pointer-types.
91 |/* 92 | typedef struct _PROCESS_INFORMATION { 93 | HANDLE hProcess; // Ptr 94 | HANDLE hThread; 95 | DWORD dwProcessId; // UInt (4 bytes) 96 | DWORD dwThreadId; 97 | } PROCESS_INFORMATION, *LPPROCESS_INFORMATION; 98 | */ 99 | pi := Buffer(A_PtrSize*2 + 8) ; Ptr + Ptr + UInt + UInt 100 | DllCall("CreateProcess", <omitted for brevity>, "Ptr", &pi, <omitted>) 101 | hProcess := NumGet(pi, 0) ; Defaults to "Ptr". 102 | hThread := NumGet(pi, A_PtrSize) ; 103 | dwProcessId := NumGet(pi, A_PtrSize*2, "UInt") 104 | dwProcessId := NumGet(pi, A_PtrSize*2 + 4, "UInt") 105 |106 | 107 | 108 |
This document covers some general concepts and conventions used by AutoHotkey, with focus on explanation rather than code. The reader is not assumed to have any prior knowledge of scripting or programming, but should be prepared to learn new terminology.
14 |For more specific details about syntax, see Scripting Language.
15 | 16 |A value is simply a piece of information within a program. For example, the name of a key to send or a program to run, the number of times a hotkey has been pressed, the title of a window to activate, or whatever else has some meaning within the program or script.
57 |AutoHotkey supports these types of values:
58 | 63 |The Type function can be used to determine the type of a value.
64 |Some other related concepts:
65 | 69 | 70 |A string is simply text. Each string is actually a sequence or string of characters, but can be treated as a single entity. The length of a string is the number of characters in the sequence, while the position of a character in the string is merely that character's sequential number. By convention in AutoHotkey, the first character is at position 1.
72 |Numeric strings: A string of digits (or any other supported number format) is automatically interpreted as a number when a math operation or comparison requires it.
73 |How literal text should be written within the script depends on the context. For instance, in an expression, strings must be enclosed in quotation marks. In directives (excluding #HotIf) and auto-replace hotstrings, quotation marks are not needed.
74 |For a more detailed explanation of how strings work, see String Encoding.
75 | 76 |AutoHotkey supports these number formats:
78 |123
, 00123
or -1
.0x7B
, 0x007B
or -0x1
.3.14159
.Hexadecimal numbers must use the 0x
or 0X
prefix, except where noted in the documentation. This prefix must be written after the +
or -
sign, if present, and before any leading zeroes. For example, 0x001
is valid, but 000x1
is not.
Numbers written with a decimal point are always considered to be floating-point, even if the fractional part is zero. For example, 42
and 42.0
are usually interchangeable, but not always. Scientific notation is also recognized (e.g. 1.0e4
and -2.1E-4
), but always produces a floating-point number even if no decimal point is present.
The decimal separator is always a dot, even if the user's regional settings specify a comma.
86 |When a number is converted to a string, it is formatted as decimal. Floating-point numbers are formatted with full precision (but discarding redundant trailing zeroes), which may in some cases reveal their inaccuracy. Use the Format function to produce a numeric string in a different format. Floating-point numbers can also be formatted by using the Round function.
87 |For details about the range and accuracy of numeric values, see Pure Numbers.
88 | 89 |A boolean value can be either true or false. Boolean values are used to represent anything that has exactly two possible states, such as the truth of an expression. For example, the expression (x <= y)
is true when x has lesser or equal value to y. A boolean value could also represent yes or no, on or off, down or up (such as for GetKeyState) and so on.
AutoHotkey does not have a specific boolean type, so it uses the integer value 0
to represent false and 1
to represent true. When a value is required to be either true or false, a blank or zero value is considered false and all other values are considered true. (Objects are always considered true.)
The words true
and false
are built-in variables containing 1 and 0. They can be used to make a script more readable.
AutoHotkey does not have a value which uniquely represents nothing, null, nil or undefined, as seen in other languages.
96 |Instead of producing a "null" or "undefined" value, any attempt to read a variable, property, array element or map item which has no value causes an UnsetError to be thrown. This allows errors to be identified more easily than if a null value was implicitly allowed to propagate through the code. See also: Uninitialized Variables.
97 |A function's optional parameters can be omitted when the function is called, in which case the function may change its behaviour or use a default value. Parameters are usually omitted by literally omitting them from the code, but can also be omitted explicitly or conditionally by using the unset
keyword. This special signal can only be propagated explicitly, with the maybe operator (var?). An unset parameter automatically receives its default value (if any) before the function executes.
Mainly for historical reasons, an empty string is sometimes used wherever a null or undefined value would be used in other languages, such as for functions which have no explicit return value.
99 |If a variable or parameter is said to be "empty" or "blank", that usually means an empty string (a string of zero length). This is not the same as omitting a parameter, although it may have the same effect in some cases.
100 | 101 |The object is AutoHotkey's composite or abstract data type. An object can be composed of any number of properties (which can be retrieved or set) and methods (which can be called). The name and effect of each property or method depends on the specific object or type of object.
103 |Objects have the following attributes:
104 |alpha := []
creates a new Array and stores a reference in alpha. bravo := alpha
copies the reference (not the object) to bravo
, so both refer to the same object. When an array or variable is said to contain an object, what it actually contains is a reference to the object.if obj
, !obj
or obj ? x : y
.MsgBox(myObject)
shows an empty MsgBox. In other cases, a TypeError may be thrown (and this should become the norm in future).Note: All objects which derive from Object have additional shared behaviour, properties and methods.
112 |Some ways that objects are used include:
113 |The proper use of objects (and in particular, classes) can result in code which is modular and reusable. Modular code is usually easier to test, understand and maintain. For instance, one can improve or modify one section of code without having to know the details of other sections, and without having to make corresponding changes to those sections. Reusable code saves time, by avoiding the need to write and test code for the same or similar tasks over and over.
120 | 121 |This section builds on these concepts which are covered in later sections: variables, functions
123 |Objects work through the principle of message passing. You don't know where an object's code or variables actually reside, so you must pass a message to the object, like "give me foo" or "go do bar", and rely on the object to respond to the message. Objects in AutoHotkey support the following basic messages:
124 |:=
.()
.A property is simply some aspect of the object that can be set and/or retrieved. For example, Array has a Length property which corresponds to the number of elements in the array. If you define a property, it can have whatever meaning you want. Generally a property acts like a variable, but its value might be calculated on demand and not actually stored anywhere.
130 |Each message contains the following, usually written where the property or method is called:
131 |For example:
136 |137 | myObj.methodName(arg1) 138 | value := myObj.propertyName[arg1] 139 |140 |
An object may also have a default property, which is invoked when square brackets are used without a property name. For example:
141 |value := myObj[arg1]142 |
Generally, Set has the same meaning as an assignment, so it uses the same operator:
143 |144 | myObj.name := value 145 | myObj.name[arg1, arg2, ..., argN] := value 146 | myObj[arg1, arg2, ..., argN] := value 147 |148 | 149 |
A variable allows you to use a name as a placeholder for a value. Which value that is could change repeatedly during the time your script is running. For example, a hotkey could use a variable press_count
to count the number of times it is pressed, and send a different key whenever press_count
is a multiple of 3 (every third press). Even a variable which is only assigned a value once can be useful. For example, a WebBrowserTitle
variable could be used to make your code easier to update when and if you were to change your preferred web browser, or if the title or window class changes due to a software update.
In AutoHotkey, variables are created simply by using them. Each variable is not permanently restricted to a single data type, but can instead hold a value of any type: string, number or object. Attempting to read a variable which has not been assigned a value is considered an error, so it is important to initialize variables.
152 |A variable has three main aspects:
153 |Certain restrictions apply to variable names - see Names for details. In short, it is safest to stick to names consisting of ASCII letters (which are case-insensitive), digits and underscore, and to avoid using names that start with a digit.
159 |A variable name has scope, which defines where in the code that name can be used to refer to that particular variable; in other words, where the variable is visible. If a variable is not visible within a given scope, the same name can refer to a different variable. Both variables might exist at the same time, but only one is visible to each part of the script. Global variables are visible in the "global scope" (that is, outside of functions), and can be read by functions by default, but must be declared if they are to be assigned a value inside a function. Local variables are visible only inside the function which created them.
160 |A variable can be thought of as a container or storage location for a value, so you'll often find the documentation refers to a variable's value as the contents of the variable. For a variable x := 42
, we can also say that the variable x has the number 42 as its value, or that the value of x is 42.
It is important to note that a variable and its value are not the same thing. For instance, we might say "myArray
is an array", but what we really mean is that myArray is a variable containing a reference to an array. We're taking a shortcut by using the name of the variable to refer to its value, but "myArray" is really just the name of the variable; the array object doesn't know that it has a name, and could be referred to by many different variables (and therefore many names).
To initialize a variable is to assign it a starting value. A variable which has not yet been assigned a value is uninitialized (or unset for short). Attempting to read an uninitialized variable is considered an error. This helps to detect errors such as mispelled names and forgotten assignments.
165 |IsSet can be used to determine whether a variable has been initialized, such as to initialize a global or static variable on first use.
166 |A variable can be un-set by combining a direct assignment (:=
) with the unset
keyword or the maybe (var?) operator. For example: Var := unset
, Var1 := (Var2?)
.
The or-maybe operator (??) can be used to provide a default value when a variable lacks a value. For example, MyVar ?? "Default"
is equivalent to IsSet(MyVar) ? MyVar : "Default"
.
A number of useful variables are built into the program and can be referenced by any script. Except where noted, these variables are read-only; that is, their contents cannot be directly altered by the script. By convention, most of these variables start with the prefix A_
, so it is best to avoid using this prefix for your own variables.
Some variables such as A_KeyDelay and A_TitleMatchMode represent settings that control the script's behavior, and retain separate values for each thread. This allows subroutines launched by new threads (such as for hotkeys, menus, timers and such) to change settings without affecting other threads.
172 |Some special variables are not updated periodically, but rather their value is retrieved or calculated whenever the script references the variable. For example, A_Clipboard retrieves the current contents of the clipboard as text, and A_TimeSinceThisHotkey calculates the number of milliseconds that have elapsed since the hotkey was pressed.
173 |Related: list of built-in variables.
174 | 175 |Environment variables are maintained by the operating system. You can see a list of them at the command prompt by typing SET then pressing Enter.
177 |A script may create a new environment variable or change the contents of an existing one with EnvSet. Such additions and changes are not seen by the rest of the system. However, any programs or scripts which the script launches by calling Run or RunWait usually inherit a copy of the parent script's environment variables.
178 |To retrieve an environment variable, use EnvGet. For example:
179 |Path := EnvGet("PATH")180 | 181 |
Within an expression, each variable reference is automatically resolved to its contents, unless it is the target of an assignment or the reference operator (&). In other words, calling myFunction(myVar)
would pass the value of myVar to myFunction, not the variable itself. The function would then have its own local variable (the parameter) with the same value as myVar, but would not be able to assign a new value to myVar. In short, the parameter is passed by value.
The reference operator (&) allows a variable to be handled like a value. &myVar
produces a VarRef, which can be used like any other value: assigned to another variable or property, inserted into an array, passed to or returned from a function, etc. A VarRef can be used to assign to the original target variable or retrieve its value by dereferencing it.
For convenience, a function parameter can be declared ByRef by prefixing the parameter name with ampersand (&). This requires the caller to pass a VarRef, and allows the function itself to "dereference" the VarRef by just referring to the parameter (without percent signs).
185 |class VarRef extends Any186 |
The VarRef class currently has no predefined methods or properties, but value is VarRef
can be used to test if a value is a VarRef.
When a VarRef is used as a parameter of a COM method, the object itself is not passed. Instead, its value is copied into a temporary VARIANT, which is passed using the variant type VT_BYREF|VT_VARIANT
. When the method returns, the new value is assigned to the VarRef.
Although a variable is typically thought of as holding a single value, and that value having a distinct type (string, number or object), AutoHotkey automatically converts between numbers and strings in cases like "Value is " myNumber
and MsgBox myNumber
. As these conversions can happen very frequently, whenever a variable containing a number is converted to a string, the result is cached in the variable.
Currently, AutoHotkey v2 caches a pure number only when assigning a pure number to a variable, not when reading it. This preserves the ability to differentiate between strings and pure numbers (such as with the Type function, or when passing values to COM objects).
192 | 193 |A function is the basic means by which a script does something.
201 |Functions can have many different purposes. Some functions might do no more than perform a simple calculation, while others have immediately visible effects, such as moving a window. One of AutoHotkey's strengths is the ease with which scripts can automate other programs and perform many other common tasks by simply calling a few functions. See the function list for examples.
202 |Throughout this documentation, some common words are used in ways that might not be obvious to someone without prior experience. Below are several such words/phrases which are used frequently in relation to functions:
203 |Calling a function causes the program to invoke, execute or evaluate it. In other words, a function call temporarily transfers control from the script to the function. When the function has completed its purpose, it returns control to the script. In other words, any code following the function call does not execute until after the function completes.
206 |However, sometimes a function completes before its effects can be seen by the user. For example, the Send function sends keystrokes, but may return before the keystrokes reach their destination and cause their intended effect.
Usually a function accepts parameters which tell it how to operate or what to operate on. Each parameter is a value, such as a string or number. For example, WinMove moves a window, so its parameters tell it which window to move and where to move it to. Parameters can also be called arguments. Common abbreviations include param and arg.
Parameters are passed to a function, meaning that a value is specified for each parameter of the function when it is called. For example, one can pass the name of a key to GetKeyState to determine whether that key is being held down.
Functions return a value, so the result of the function is often called a return value. For example, StrLen returns the number of characters in a string. Functions may also store results in variables, such as when there is more than one result (see Returning Values).
A function call is sometimes called a command, such as if it commands the program to take a specific action. (For historical reasons, command may refer to a particular style of calling a function, where the parentheses are omitted and the return value is discarded. However, this is technically a function call statement.)
Functions usually expect parameters to be written in a specific order, so the meaning of each parameter value depends on its position in the comma-delimited list of parameters. Some parameters can be omitted, in which case the parameter can be left blank, but the comma following it can only be omitted if all remaining parameters are also omitted. For example, the syntax for ControlSend is:
217 |ControlSend Keys , Control, WinTitle, WinText, ExcludeTitle, ExcludeText 218 |219 |
Square brackets signify that the enclosed parameters are optional (the brackets themselves should not appear in the actual code). However, usually one must also specify the target window. For example:
220 |221 | ControlSend "^{Home}", "Edit1", "A" ; Correct. Control is specified. 222 | ControlSend "^{Home}", "A" ; Incorrect: Parameters are mismatched. 223 | ControlSend "^{Home}",, "A" ; Correct. Control is omitted. 224 |225 | 226 |
A method is a function associated with a specific object or type of object. To call a method, one must specify an object and a method name. The method name does not uniquely identify the function; instead, what happens when the method call is attempted depends on the object. For example, x.Show()
might show a menu, show a GUI, raise an error or do something else, depending on what x
is. In other words, a method call simply passes a message to the object, instructing it to do something. For details, see Object Protocol and Operators for Objects.
Control flow is the order in which individual statements are executed. Normally statements are executed sequentially from top to bottom, but a control flow statement can override this, such as by specifying that statements should be executed repeatedly, or only if a certain condition is met.
231 |A statement is simply the smallest standalone element of the language that expresses some action to be carried out. In AutoHotkey, statements include assignments, function calls and other expressions. However, directives, double-colon hotkey and hotstring tags, and declarations without assignments are not statements; they are processed when the program first starts up, before the script executes.
Carry out, perform, evaluate, put into effect, etc. Execute basically has the same meaning as in non-programming speak.
The body of a control flow statement is the statement or group of statements to which it applies. For example, the body of an if statement is executed only if a specific condition is met.
For example, consider this simple set of instructions:
240 |We take one step at a time, and when that step is finished, we move on to the next step. In the same way, control in a program or script usually flows from one statement to the next statement. But what if we want to type into an existing Notepad window? Consider this revised set of instructions:
246 |So we either open Notepad or activate Notepad depending on whether it is already running. #1 is a conditional statement, also known as an if statement; that is, we execute its body (#1.1 - #1.2) only if a condition is met. #2 is an else statement; we execute its body (#2.1) only if the condition of a previous if statement (#1) is not met. Depending on the condition, control flows one of two ways: #1 (if true) → #1.1 → #1.2 → #3; or #1 (if false) → #2 (else) → #2.1 → #3.
261 |The instructions above can be translated into the code below:
262 |if (not WinExist("ahk_class Notepad")) 263 | { 264 | Run "Notepad" 265 | WinWait "ahk_class Notepad" 266 | } 267 | else 268 | WinActivate "ahk_class Notepad" 269 | Send "Hello, world{!}" 270 |271 |
In our written instructions, we used indentation and numbering to group the statements. Scripts work a little differently. Although indentation makes code easier to read, in AutoHotkey it does not affect the grouping of statements. Instead, statements are grouped by enclosing them in braces, as shown above. This is called a block.
272 |For details about syntax - that is, how to write or recognise control flow statements in AutoHotkey - see Control Flow.
273 | 274 |Each character in the string is represented by a number, called its ordinal number, or character code. For example, the value "Abc" would be represented as follows:
278 |A | b | c | |
65 | 98 | 99 | 0 |
Encoding: The encoding of a string defines how symbols are mapped to ordinal numbers, and ordinal numbers to bytes. There are many different encodings, but as all of those supported by AutoHotkey include ASCII as a subset, character codes 0 to 127 always have the same meaning. For example, 'A' always has the character code 65.
283 |Null-termination: Each string is terminated with a "null character", or in other words, a character with ordinal value of zero marks the end of the string. The length of the string can be inferred by the position of the null-terminator, but AutoHotkey also stores the length, for performance and to permit null characters within the string's length.
284 |Note: Due to reliance on null-termination, many built-in functions and most expression operators do not support strings with embedded null characters, and instead read only up to the first null character. However, basic manipulation of such strings is supported; e.g. concatenation, ==
, !==
, Chr(0)
, StrLen, SubStr, assignments, parameter values and return.
Native encoding: Although AutoHotkey provides ways to work with text in various encodings, the built-in functions--and to some degree the language itself--all assume string values to be in one particular encoding. This is referred to as the native encoding. The native encoding depends on the version of AutoHotkey:
286 |Unicode versions of AutoHotkey use UTF-16. The smallest element in a UTF-16 string is two bytes (16 bits). Unicode characters in the range 0 to 65535 (U+FFFF) are represented by a single 16-bit code unit of the same value, while characters in the range 65536 (U+10000) to 1114111 (U+10FFFF) are represented by a surrogate pair; that is, exactly two 16-bit code units between 0xD800 and 0xDFFF. (For further explanation of surrogate pairs and methods of encoding or decoding them, search the Internet.)
289 |ANSI versions of AutoHotkey use the system default ANSI code page, which depends on the system locale or "language for non-Unicode programs" system setting. The smallest element of an ANSI string is one byte. However, some code pages contain characters which are represented by sequences of multiple bytes (these are always non-ASCII characters).
292 |Note: AutoHotkey v2 natively uses Unicode and does not have an ANSI version.
295 |Character: Generally, other parts of this documentation use the term "character" to mean a string's smallest unit; bytes for ANSI strings and 16-bit code units for Unicode (UTF-16) strings. For practical reasons, the length of a string and positions within a string are measured by counting these fixed-size units, even though they may not be complete Unicode characters.
296 |FileRead, FileAppend, FileOpen and the File object provide ways of reading and writing text in files with a specific encoding.
297 |The functions StrGet and StrPut can be used to convert strings between the native encoding and some other specified encoding. However, these are usually only useful in combination with data structures and the DllCall function. Strings which are passed directly to or from DllCall can be converted to ANSI or UTF-16 by using the AStr
or WStr
parameter types.
Techniques for dealing with the differences between ANSI and Unicode versions of AutoHotkey can be found under Unicode vs ANSI.
299 | 300 |A pure or binary number is one which is stored in memory in a format that the computer's CPU can directly work with, such as to perform math. In most cases, AutoHotkey automatically converts between numeric strings and pure numbers as needed, and rarely differentiates between the two types. AutoHotkey primarily uses two data types for pure numbers:
302 |These data types affect the range and precision of pure numeric values for variables, properties, array/map elements and indices, function parameters and return values, and temporary results of operators in an expression. Mathematical operators and functions perform 64-bit integer or floating-point operations. Bitwise operators perform 64-bit integer operations.
307 |In other words, scripts are affected by the following limitations:
308 |Integers must be within the signed 64-bit range; that is, -9223372036854775808 (-0x8000000000000000, or -263) to 9223372036854775807 (0x7FFFFFFFFFFFFFFF, or 263-1). If an integer constant in an expression is outside this range, only the low 64 bits are used (the value is truncated). Although larger values can be contained within a string, any attempt to convert the string to a number (such as by using it in a math operation) will cause it to be similarly truncated.
311 |Floating-point numbers generally support 15 digits of precision.
314 |Note: There are some decimal fractions which the binary floating-point format cannot precisely represent, so a number is rounded to the closest representable number. This may lead to unexpected results. For example:
317 |318 | MsgBox 0.1 + 0 ; 0.10000000000000001 319 | MsgBox 0.1 + 0.2 ; 0.30000000000000004 320 | MsgBox 0.3 + 0 ; 0.29999999999999999 321 | MsgBox 0.1 + 0.2 = 0.3 ; 0 (not equal) 322 |323 |
One strategy for dealing with this is to avoid direct comparison, instead comparing the difference. For example:
324 |MsgBox Abs((0.1 + 0.2) - (0.3)) < 0.0000000000000001 325 |326 |
Another strategy is to explicitly apply rounding before comparison, such as by converting to a string. There are generally two ways to do this while specifying the precision, and both are shown below:
327 |MsgBox Round(0.1 + 0.2, 15) = Format("{:.15f}", 0.3) 328 |329 | 330 |
AutoHotkey uses the same set of rules for naming various things, including variables, functions, window groups, classes, properties and methods. The rules are as follows.
332 |Case sensitivity: None for ASCII characters. For example, CurrentDate
is the same as currentdate
. However, uppercase non-ASCII characters such as 'Ä' are not considered equal to their lowercase counterparts, regardless of the current user's locale. This helps the script to behave consistently across multiple locales.
Maximum length: 253 characters.
334 |Allowed characters: Letters, digits, underscore and non-ASCII characters; however, only property names can begin with a digit.
335 |Reserved words: as
, and
, contains
, false
, in
, is
, IsSet
, not
, or
, super
, true
, unset
. These words are reserved for future use or other specific purposes.
Declaration keywords and names of control flow statements are also reserved, primarily to detect mistakes. This includes: Break
, Case
, Catch
, Continue
, Else
, Finally
, For
, Global
, Goto
, If
, Local
, Loop
, Return
, Static
, Switch
, Throw
, Try
, Until
, While
Names of properties, methods and window groups are permitted to be reserved words.
338 | 339 |Scripts interact with an object only indirectly, through a reference to the object. When you create an object, the object is created at some location you don't control, and you're given a reference. Passing this reference to a function or storing it in a variable or another object creates a new reference to the same object.
341 |For example, if myObj contains a reference to an object, yourObj := myObj
creates a new reference to the same object. A change such as myObj.ans := 42
would be reflected by both myObj.ans
and yourObj.ans
, since they both refer to the same object. However, myObj := Object()
only affects the variable myObj, not the variable yourObj, which still refers to the original object.
A reference is released by simply using an assignment to replace it with any other value. An object is deleted only after all references have been released; you cannot delete an object explicitly, and should not try. (However, you can delete an object's properties, content or associated resources, such as an Array's elements, the window associated with a Gui, the items of a Menu object, and so on.)
343 |ref1 := Object() ; Create an object and store first reference 344 | ref2 := ref1 ; Create a new reference to the same object 345 | ref1 := "" ; Release the first reference 346 | ref2 := "" ; Release the second reference; object is deleted 347 |348 |
If that's difficult to understand, try thinking of an object as a rental unit. When you rent a unit, you're given a key which you can use to access the unit. You can get more keys and use them to access the same unit, but when you're finished with the unit, you must hand all keys back to the rental agent. Usually a unit wouldn't be deleted, but maybe the agent will have any junk you left behind removed; just as any values you stored in an object are freed when the object is deleted.
349 | 350 | 351 | 352 | -------------------------------------------------------------------------------- /docs/FAQ.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |Hotkeys, Hotstrings, and Remapping
50 |If AutoHotkey cannot be installed the normal way, see How to Install AutoHotkey for more help.
67 | 68 |Normally if AutoHotkey is installed, right-clicking an AutoHotkey script (.ahk) file should give the following options:
70 |Note: On Windows 11, some of these options are usually relegated to a submenu that can be accessed by selecting "Show more options".
78 |Sometimes these options are overridden by settings in the current user's profile, such as if Open With has been used to change the default program for opening .ahk files. This can be fixed by deleting the following registry key:
79 |HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.ahk\UserChoice80 |
This can be done by applying this registry patch or by running UX\reset-assoc.ahk
from the AutoHotkey installation directory.
It may also be necessary to repair the default registry values, either by reinstalling AutoHotkey or by running UX\install.ahk
from the AutoHotkey installation directory.
There are many variations of this problem, such as:
85 |If you've switched operating systems, it is likely that something else has also changed and may be affecting your script. For instance, if you've got a new computer, it might have different drivers or other software installed. If you've also updated to a newer version of AutoHotkey, find out which version you had before and then check the changelog and compatibility notes.
91 |Also refer to the following question:
92 | 93 |By default, User Account Control (UAC) protects "elevated" programs (that is, programs which are running as admin) from being automated by non-elevated programs, since that would allow them to bypass security restrictions. Hotkeys are also blocked, so for instance, a non-elevated program cannot spy on input intended for an elevated program.
95 |UAC may also prevent SendPlay and BlockInput from working.
96 |Common workarounds are as follows:
97 |Run '*UIAccess "Your script.ahk"'
."AutoHotkey32_UIA.exe" "Your script.ahk"
(but include full paths where necessary).You need to fix the error in your script before you can get your tray icon back. This will require locating the script and opening it in an editor by some other means than the tray icon.
112 |If you are running an AutoHotkey executable file directly, the name of the script depends on the executable. For example, if you are running AutoHotkey32.exe, look for AutoHotkey32.ahk in the same directory. Note that depending on your system settings the ".ahk" part may be hidden, but the file should have an icon like
113 |You can usually edit a script file by right clicking it and selecting Edit Script. If that doesn't work, you can open the file in Notepad or another editor.
114 |Normally, you should create a script file (something.ahk) anywhere you like, and run that script file instead of running AutoHotkey.
115 |See also Command Line Parameter "Script Filename" and Portability of AutoHotkey.exe.
116 |For simple scripts, see Debugging a Script. To show contents of a variable, use MsgBox or ToolTip. For complex scripts, see Interactive Debugging.
118 |Some programs need to be started in their own directories (when in doubt, it is usually best to do so). For example:
120 |Run A_ProgramFiles "\Some Application\App.exe", A_ProgramFiles "\Some Application"121 |
If the program you are trying to start is in A_WinDir "\System32"
and you are using AutoHotkey 32-bit on a 64-bit system, the File System Redirector may be interfering. To work around this, use A_WinDir "\SysNative"
instead; this is a virtual directory only visible to 32-bit programs running on 64-bit systems.
Short answer: Save the script as UTF-8, preferably with BOM.
125 |Non-ASCII characters are represented by different binary values depending on the chosen encoding. In order for such characters to be interpreted correctly, your text editor and AutoHotkey must be on the same codepage, so to speak. AutoHotkey v2 defaults to UTF-8 for all script files, although this can be overridden with the /CP command line switch.
126 |It is recommended to save the script as UTF-8 with BOM (byte order mark) to ensure that editors (and maybe other applications) can determine with certainty that the file is indeed UTF-8. Without BOM, the editor has to guess the encoding of the file, which can sometimes be wrong.
127 |To save as UTF-8 in Notepad, select UTF-8 or UTF-8 with BOM from the Encoding drop-down in the Save As dialog. Note that Notepad in Windows 10 v1903 and later defaults to UTF-8 (without BOM).
128 |To read other UTF-8 files which lack a byte order mark (BOM), use FileEncoding "UTF-8-RAW"
, the *P65001
option with FileRead, or "UTF-8-RAW"
for the third parameter of FileOpen. The -RAW
suffix can be omitted, but in that case any newly created files will have a BOM.
Note that INI files accessed with the standard INI functions do not support UTF-8; they must be saved as ANSI or UTF-16.
130 | 131 |Not all games allow AHK to send keys and clicks or receive pixel colors.
133 |But there are some alternatives, try all the solutions mentioned below. If all these fail, it may not be possible for AHK to work with your game. Sometimes games have a hack and cheat prevention measure, such as GameGuard and Hackshield. If they do, there is a high chance that AutoHotkey will not work with that game.
134 |Use SendPlay via the SendPlay function, SendMode Play and/or the hotstring option SP.
137 |SendPlay "abc"138 |
SendMode "Play" 139 | Send "abc"140 |
:SP:btw::by the way 141 | 142 | ; or 143 | 144 | #Hotstring SP 145 | ::btw::by the way146 |
Deprecated: SendPlay may have no effect at all on Windows 11 and later, or if User Account Control (UAC) is enabled, even if the script is running as an administrator.
147 |Increase SetKeyDelay. For example:
150 |SetKeyDelay 0, 50 151 | SetKeyDelay 0, 50, "Play"152 |
Try ControlSend, which might work in cases where the other Send modes fail:
155 |ControlSend "abc",, GameTitle156 |
Try the down and up event of a key with the various send methods:
159 |Send "{KEY Down}{KEY Up}"160 |
Try the down and up event of a key with a Sleep between them:
163 |Send "{KEY down}" 164 | Sleep 10 ; Try various milliseconds. 165 | Send "{KEY up}"166 |
If a script's Hotkeys, Clicks, or Sends are noticeably slower than normal while the CPU is under heavy load, raising the script's process-priority may help. To do this, include the following line near the top of the script:
170 |ProcessSetPriority "High"171 |
Although it is certainly possible that the file has been infected, most often these alerts are false positives, meaning that the antivirus program is mistaken. One common suggestion is to upload the file to an online service such as virustotal or Jotti and see what other antivirus programs have to say. If in doubt, you could send the file to the vendor of your antivirus software for confirmation. This might also help us and other AutoHotkey users, as the vendor may confirm it is a false positive and fix their product to play nice with AutoHotkey.
173 |False positives might be more common for compiled scripts which have been compressed, such as with UPX (default for AutoHotkey 1.0 but not 1.1) or MPRESS (optional for AutoHotkey 1.1). As the default AutoHotkey installation does not include a compressor, compiled scripts are not compressed by default.
174 | 175 |See download page of AutoHotkey.
179 |See Portability of AutoHotkey.exe.
181 |Testing shows that due to file caching, a temporary file can be very fast for relatively small outputs. In fact, if the file is deleted immediately after use, it often does not actually get written to disk. For example:
183 |RunWait A_ComSpec ' /c dir > C:\My Temp File.txt' 184 | VarToContainContents := FileRead("C:\My Temp File.txt") 185 | FileDelete "C:\My Temp File.txt"186 |
To avoid using a temporary file (especially if the output is large), consider using the Shell.Exec() method as shown in the examples for the Run function.
187 |First, here is an example that closes another script:
189 |DetectHiddenWindows True ; Allows a script's hidden main window to be detected. 190 | SetTitleMatchMode 2 ; Avoids the need to specify the full path of the file below. 191 | WinClose "ScriptFileName.ahk - AutoHotkey" ; Update this to reflect the script's name (case-sensitive).192 |
To suspend, pause or reload another script, replace the last line above with one of these:
193 |PostMessage 0x0111, 65305,,, "ScriptFileName.ahk - AutoHotkey" ; Suspend. 194 | PostMessage 0x0111, 65306,,, "ScriptFileName.ahk - AutoHotkey" ; Pause. 195 | PostMessage 0x0111, 65303,,, "ScriptFileName.ahk - AutoHotkey" ; Reload.196 |
To pause or resume the entire script at the press of a key, assign a hotkey to the Pause function as in this example:
198 |^!p::Pause ; Press Ctrl+Alt+P to pause. Press it again to resume.199 |
To stop an action that is repeating inside a Loop, consider the following working example, which is a hotkey that both starts and stops its own repeating action. In other words, pressing the hotkey once will start the loop. Pressing the same hotkey again will stop it.
200 |#MaxThreadsPerHotkey 3 201 | #z:: ; Win+Z hotkey (change this hotkey to suit your preferences). 202 | { 203 | static KeepWinZRunning := false 204 | if KeepWinZRunning ; This means an underlying thread is already running the loop below. 205 | { 206 | KeepWinZRunning := false ; Signal that thread's loop to stop. 207 | return ; End this thread so that the one underneath will resume and see the change made by the line above. 208 | } 209 | ; Otherwise: 210 | KeepWinZRunning := true 211 | Loop 212 | { 213 | ; The next four lines are the action you want to repeat (update them to suit your preferences): 214 | ToolTip "Press Win-Z again to stop this from flashing." 215 | Sleep 1000 216 | ToolTip 217 | Sleep 1000 218 | ; But leave the rest below unchanged. 219 | if not KeepWinZRunning ; The user signaled the loop to stop by pressing Win-Z again. 220 | break ; Break out of this loop. 221 | } 222 | KeepWinZRunning := false ; Reset in preparation for the next press of this hotkey. 223 | } 224 | #MaxThreadsPerHotkey 1225 |
Rajat created this script.
227 |With Internet Explorer, perhaps the most reliable method is to use DllCall and COM as demonstrated at this archived forum thread. On a related note, the contents of the address bar and status bar can be retrieved as demonstrated at this archived forum thread.
229 |Older, less reliable method: The technique in the following example will work with MS Internet Explorer for most pages. A similar technique might work in other browsers:
230 |Run "www.yahoo.com" 231 | MouseMove 0, 0 ; Prevents the status bar from showing a mouse-hover link instead of "Done". 232 | WinWait "Yahoo! - " 233 | WinActivate 234 | if StatusBarWait("Done", 30) 235 | MsgBox "The page is done loading." 236 | else 237 | MsgBox "The wait timed out or the window was closed." 238 |239 |
The DateAdd function can add or subtract a quantity of days, hours, minutes, or seconds to a time-string that is in the YYYYMMDDHH24MISS format. The following example subtracts 7 days from the specified time:
241 |Result := DateAdd(VarContainingTimestamp, -7, "days")242 |
To determine the amount of time between two dates or times, see DateDiff, which gives an example. Also, the built-in variable A_Now contains the current local time. Finally, there are several built-in date/time variables, as well as the FormatTime function to create a custom date/time string.
243 |Use FormatTime or built-in variables for date and time.
245 |Use ControlSend.
247 |See Automating Winamp.
249 |Here is an example.
251 |In the example section of Edit you will find a script that allows you to change the default editor.
253 |Use Gui.Submit. For Example:
255 |MyGui := Gui() 256 | MyGui.Add("Text",, "Enter some Text and press Submit:") 257 | MyGui.Add("Edit", "vMyEdit") 258 | MyGui.Add("Button",, "Submit").OnEvent("Click", Submit) 259 | MyGui.Show() 260 | 261 | Submit(*) 262 | { 263 | Saved := MyGui.Submit(false) 264 | MsgBox "Content of the edit control: " Saved.MyEdit 265 | }266 |
See GDI+ standard library by tic. It's also possible with some rudimentary methods using Gui, but in a limited way.
268 |Use WinWait, WinWaitClose or WinWait[Not]Active.
270 |There are also user-created solutions such as OnWin.ahk and [How to] Hook on to Shell to receive its messages on the archived forum.
271 |There are several ways to make a script (or any program) launch automatically every time you start your PC. The easiest is to place a shortcut to the script in the Startup folder:
274 |shell:startup
and click OK or Enter. This will open the Startup folder for the current user. To instead open the folder for all users, enter shell:common startup
(however, in that case you must be an administrator to proceed).The left and right mouse buttons should be assignable normally (for example, #LButton::
is the Win+LeftButton hotkey). Similarly, the middle button and the turning of the mouse wheel should be assignable normally except on mice whose drivers directly control those buttons.
The fourth button (XButton1) and the fifth button (XButton2) might be assignable if your mouse driver allows their clicks to be seen by the system. If they cannot be seen -- or if your mouse has more than five buttons that you want to use -- you can try configuring the software that came with the mouse (sometimes accessible in the Control Panel or Start Menu) to send a keystroke whenever you press one of these buttons. Such a keystroke can then be defined as a hotkey in a script. For example, if you configure the fourth button to send Ctrl+F1, you can then indirectly configure that button as a hotkey by using ^F1::
in a script.
If you have a five-button mouse whose fourth and fifth buttons cannot be seen, you can try changing your mouse driver to the default driver included with the OS. This assumes there is such a driver for your particular mouse and that you can live without the features provided by your mouse's custom software.
283 |Use the names of the keys (Tab and Space) rather than their characters. For example, #Space
is Win+Space and ^!Tab
is Ctrl+Alt+Tab.
This is described on the remapping page.
287 |Use built-in variables for hotkeys as follows:
289 |~Ctrl:: 290 | { 291 | if (ThisHotkey = A_PriorHotkey && A_TimeSincePriorHotkey < 200) 292 | MsgBox "double-press" 293 | }294 |
The preferred method is #HotIf. For example:
296 |#HotIf WinActive("ahk_class Notepad") 297 | ^a::MsgBox "You pressed Control-A while Notepad is active." 298 |299 |
Consider the following example, which makes Numpad0 into a prefix key:
301 |Numpad0 & Numpad1::MsgBox "You pressed Numpad1 while holding down Numpad0."302 |
Now, to make Numpad0 send a real Numpad0 keystroke whenever it wasn't used to launch a hotkey such as the above, add the following hotkey:
303 |$Numpad0::Send "{Numpad0}"304 |
The $ prefix is needed to prevent a warning dialog about an infinite loop (since the hotkey "sends itself"). In addition, the above action occurs at the time the key is released.
305 |Here are some examples.
307 |Use the script by polyethene (examples are included).
309 |See Special Keys.
311 |You can. This example script makes 000 into an equals key. You can change the action by replacing the Send "="
line with line(s) of your choice.
A function is a reusable block of code that can be executed by calling it. A function can optionally accept parameters (inputs) and return a value (output). Consider the following simple function that accepts two numbers and returns their sum:
54 |Add(x, y) 55 | { 56 | return x + y 57 | }58 |
The above is known as a function definition because it creates a function named "Add" (not case-sensitive) and establishes that anyone who calls it must provide exactly two parameters (x and y). To call the function, assign its result to a variable with the :=
operator. For example:
Var := Add(2, 3) ; The number 5 will be stored in Var.60 |
Also, a function may be called without storing its return value:
61 |Add(2, 3) 62 | Add 2, 3 ; Parentheses can be omitted if used at the start of a line.63 |
But in this case, any value returned by the function is discarded; so unless the function produces some effect other than its return value, the call would serve no purpose.
64 |Within an expression, a function call "evaluates to" the return value of the function. The return value can be assigned to a variable as shown above, or it can be used directly as shown below:
65 |if InStr(MyVar, "fox") 66 | MsgBox "The variable MyVar contains the word fox."67 | 68 |
When a function is defined, its parameters are listed in parentheses next to its name (there must be no spaces between its name and the open-parenthesis). If a function does not accept any parameters, leave the parentheses empty; for example: GetCurrentTimestamp()
.
Known limitation:
71 |Var
or ++Var
or Var*=2
), other parameters to its left or right can alter that variable before it is passed to the function. For example, MyFunc(Var, Var++)
would unexpectedly pass 1 and 0 when Var is initially 0, because the first Var is not dereferenced until the function call is executed. Since this behavior is counterintuitive, it might change in a future release.From the function's point of view, parameters are essentially the same as local variables unless they are marked as ByRef as in this example:
77 |a := 1, b := 2 78 | Swap(&a, &b) 79 | MsgBox a ',' b 80 | 81 | Swap(&Left, &Right) 82 | { 83 | temp := Left 84 | Left := Right 85 | Right := temp 86 | }87 |
In the example above, the use of &
requires the caller to pass a VarRef, which usually corresponds to one of the caller's variables. Each parameter becomes an alias for the variable represented by the VarRef. In other words, the parameter and the caller's variable both refer to the same contents in memory. This allows the Swap function to alter the caller's variables by moving Left's contents into Right and vice versa.
By contrast, if ByRef were not used in the example above, Left and Right would be copies of the caller's variables and thus the Swap function would have no external effect. However, the function could instead be changed to explicitly dereference each VarRef. For example:
89 |Swap(Left, Right) 90 | { 91 | temp := %Left% 92 | %Left% := %Right% 93 | %Right% := temp 94 | }95 |
Since return can send back only one value to a function's caller, VarRefs can be used to send back extra results. This is achieved by having the caller pass in a reference to a variable (usually empty) in which the function stores a value.
96 |When passing large strings to a function, ByRef enhances performance and conserves memory by avoiding the need to make a copy of the string. Similarly, using ByRef to send a long string back to the caller usually performs better than something like Return HugeString
. However, what the function receives is not a reference to the string, but a reference to the variable. Future improvements might supersede the use of ByRef for these purposes.
Known limitations:
98 |foo.bar
), A_Clipboard or any other built-in variable, so those cannot be passed ByRef.&
operator).When defining a function, one or more of its parameters can be marked as optional.
105 |Append :=
followed by a literal number, quoted/literal string such as "fox" or "", or an expression that should be evaluated each time the parameter needs to be initialized with its default value. For example, X:=[]
would create a new Array each time.
Append ?
or := unset
to define a parameter which is unset by default.
The following function has its Z parameter marked optional:
108 |Add(X, Y, Z := 0) { 109 | return X + Y + Z 110 | }111 |
When the caller passes three parameters to the function above, Z's default value is ignored. But when the caller passes only two parameters, Z automatically receives the value 0.
112 |It is not possible to have optional parameters isolated in the middle of the parameter list. In other words, all parameters that lie to the right of the first optional parameter must also be marked optional. However, optional parameters may be omitted from the middle of the parameter list when calling the function, as shown below:
113 |MyFunc(1,, 3) 114 | MyFunc(X, Y:=2, Z:=0) { ; Note that Z must still be optional in this case. 115 | MsgBox X ", " Y ", " Z 116 | }117 |
ByRef parameters also support default values; for example: MyFunc(&p1 := "") {
. Whenever the caller omits such a parameter, the function creates a local variable to contain the default value; in other words, the function behaves as though the symbol "&" is absent.
To mark a parameter as optional without supplying a default value, use the keyword unset
or the ?
suffix. In that case, whenever the parameter is omitted, the corresponding variable will have no value. Use IsSet to determine whether the parameter has been given a value, as shown below:
122 | MyFunc(p?) { ; Equivalent to MyFunc(p := unset) 123 | if IsSet(p) 124 | MsgBox "Caller passed " p 125 | else 126 | MsgBox "Caller did not pass anything" 127 | } 128 | 129 | MyFunc(42) 130 | MyFunc 131 |132 |
Attempting to read the parameter's value when it has none is considered an error, the same as for any uninitialized variable. To pass an optional parameter through to another function even when the parameter has no value, use the maybe operator (var?). For example:
133 |134 | Greet(title?) { 135 | MsgBox("Hello!", title?) 136 | } 137 | 138 | Greet "Greeting" ; Title is "Greeting" 139 | Greet ; Title is A_ScriptName 140 |141 | 142 |
As described in introduction, a function may optionally return a value to its caller.
144 |145 | MsgBox returnTest() 146 | 147 | returnTest() { 148 | return 123 149 | } 150 |151 |
If you want to return extra results from a function, you may also use ByRef (&):
152 |153 | returnByRef(&A,&B,&C) 154 | MsgBox A "," B "," C 155 | 156 | returnByRef(&val1, &val2, val3) 157 | { 158 | val1 := "A" 159 | val2 := 100 160 | %val3% := 1.1 ; % is used because & was omitted. 161 | return 162 | } 163 |164 |
Objects and Arrays can be used to return multiple values or even named values:
165 |166 | Test1 := returnArray1() 167 | MsgBox Test1[1] "," Test1[2] 168 | 169 | Test2 := returnArray2() 170 | MsgBox Test2[1] "," Test2[2] 171 | 172 | Test3 := returnObject() 173 | MsgBox Test3.id "," Test3.val 174 | 175 | returnArray1() { 176 | Test := [123,"ABC"] 177 | return Test 178 | } 179 | 180 | returnArray2() { 181 | x := 456 182 | y := "EFG" 183 | return [x, y] 184 | } 185 | 186 | returnObject() { 187 | Test := {id: 789, val: "HIJ"} 188 | return Test 189 | } 190 |191 |
When defining a function, write an asterisk after the final parameter to mark the function as variadic, allowing it to receive a variable number of parameters:
193 |Join(sep, params*) { 194 | for index,param in params 195 | str .= param . sep 196 | return SubStr(str, 1, -StrLen(sep)) 197 | } 198 | MsgBox Join("`n", "one", "two", "three")199 |
When a variadic function is called, surplus parameters can be accessed via an object which is stored in the function's final parameter. The first surplus parameter is at params[1]
, the second at params[2]
and so on. As it is an array, params.Length
can be used to determine the number of parameters.
Attempting to call a non-variadic function with more parameters than it accepts is considered an error. To permit a function to accept any number of parameters without creating an array to store the surplus parameters, write *
as the final parameter (without a parameter name).
Note: The "variadic" parameter can only appear at the end of the formal parameter list.
202 | 203 |While variadic functions can accept a variable number of parameters, an array of parameters can be passed to any function by applying the same syntax to a function-call:
205 |substrings := ["one", "two", "three"] 206 | MsgBox Join("`n", substrings*)207 |
Notes:
208 |[,2]
) are equivalent to omitting the parameter; that is, the parameter's default value is used if it is optional, otherwise an exception is thrown.Object.Property[Params*]
.Known limitations:
214 |MyFunc(x, y*)
is supported but MyFunc(x*, y)
is not.*
) and the symbol which ends the parameter list.Local variables are specific to a single function and are visible only inside that function. Consequently, a local variable may have the same name as a global variable but have separate contents. Separate functions may also safely use the same variable names.
222 |All local variables which are not static are automatically freed (made empty) when the function returns, with the exception of variables which are bound to a closure or VarRef (such variables are freed at the same time as the closure or VarRef).
223 |Built-in variables such as A_Clipboard and A_TimeIdle are never local (they can be accessed from anywhere), and cannot be redeclared. (This does not apply to built-in classes such as Object; they are predefined as global variables.)
224 |Functions are assume-local by default. Variables accessed or created inside an assume-local function are local by default, with the following exceptions:
225 |The default may also be overridden by declaring the variable using the local
keyword, or by changing the mode of the function (as shown below).
Any variable reference in an assume-local function may resolve to a global variable if it is only read. However, if a variable is used in an assignment or with the reference operator (&), it is automatically local by default. This allows functions to read global variables or call global or built-in functions without declaring them inside the function, while protecting the script from unintended side-effects when the name of a local variable being assigned coincides with a global variable. For example:
233 |LogToFile(TextToLog) 234 | { 235 | ; LogFileName was previously given a value somewhere outside this function. 236 | ; FileAppend is a predefined global variable containing a built-in function. 237 | FileAppend TextToLog "`n", LogFileName 238 | }239 |
Otherwise, to refer to an existing global variable inside a function (or create a new one), declare the variable as global prior to using it. For example:
240 |SetDataDir(Dir) 241 | { 242 | global LogFileName 243 | LogFileName := Dir . "\My.log" 244 | global DataDir := Dir ; Declaration combined with assignment, described below. 245 | } 246 |247 |
Assume-global mode: If a function needs to access or create a large number of global variables, it can be defined to assume that all its variables are global (except its parameters) by making its first line the word "global". For example:
248 |SetDefaults() 249 | { 250 | global 251 | MyGlobal := 33 ; Assigns 33 to a global variable, first creating the variable if necessary. 252 | local x, y:=0, z ; Local variables must be declared in this mode, otherwise they would be assumed global. 253 | }254 | 255 |
Static variables are always implicitly local, but differ from locals because their values are remembered between calls. For example:
257 |LogToFile(TextToLog) 258 | { 259 | static LoggedLines := 0 260 | LoggedLines += 1 ; Maintain a tally locally (its value is remembered between calls). 261 | global LogFileName 262 | FileAppend LoggedLines ": " TextToLog "`n", LogFileName 263 | }264 |
A static variable may be initialized on the same line as its declaration by following it with :=
and any expression. For example: static X:=0, Y:="fox"
. Static declarations are evaluated the same as local declarations, except that after a static initializer (or group of combined initializers) is successfully evaluated, it is effectively removed from the flow of control and will not execute a second time.
Nested functions can be declared static to prevent them from capturing non-static local variables of the outer function.
266 |Assume-static mode: A function may be defined to assume that all its undeclared local variables are static (except its parameters) by making its first line the word "static". For example:
267 |GetFromStaticArray(WhichItemNumber) 268 | { 269 | static 270 | static FirstCallToUs := true ; Each static declaration's initializer still runs only once. 271 | if FirstCallToUs ; Create a static array during the first call, but not on subsequent calls. 272 | { 273 | FirstCallToUs := false 274 | StaticArray := [] 275 | Loop 10 276 | StaticArray.Push("Value #" . A_Index) 277 | } 278 | return StaticArray[WhichItemNumber] 279 | }280 |
In assume-static mode, any variable that should not be static must be declared as local or global (with the same exceptions as for assume-local mode).
281 | 282 |Multiple variables may be declared on the same line by separating them with commas as in these examples:
284 |global LogFileName, MaxRetries := 5 285 | static TotalAttempts := 0, PrevResult286 |
A variable may be initialized on the same line as its declaration by following it with an assignment. Unlike static initializers, the initializers of locals and globals execute every time the function is called. In other words, a line like local x := 0
has the same effect as writing two separate lines: local x
followed by x := 0
. Any assignment operator can be used, but a compound assignment such as global HitCount += 1
would require that the variable has previously been assigned a value.
Because the words local, global, and static are processed immediately when the script launches, a variable cannot be conditionally declared by means of an IF statement. In other words, a declaration inside an IF's or ELSE's block takes effect unconditionally for the entire function (but any initializers included in the declaration are still conditional). A dynamic declaration such as global Array%i%
is not possible, since all non-dynamic references to variables such as Array1
or Array99
would have already been resolved to addresses.
Although a function call expression usually begins with a literal function name, the target of the call can be any expression which produces a function object. In the expression GetKeyState("Shift")
, GetKeyState is actually a variable reference, although it usually refers to a read-only variable containing a built-in function.
A function call is said to be dynamic if the target of the call is determined while the script is running, instead of before the script starts. The same syntax is used as for normal function calls; the only apparent difference is that certain error-checking is performed at load time for non-dynamic calls but only at run time for dynamic calls.
292 |For example, MyFunc()
would call the function object contained by MyFunc, which could be either the actual name of a function, or just a variable which has been assigned a function.
Other expressions can be used as the target of a function call, including double-derefs. For example, MyArray[1]()
would call the function contained by the first element of MyArray, while %MyVar%()
would call the function contained by the variable whose name is contained by MyVar. In other words, the expression preceding the parameter list is first evaluated to get a function object, then that object is called.
If the target value cannot be called due to one of the reasons below, an Error is thrown:
295 |HasMethod(value, "Call")
or HasMethod(value)
can be used to avoid this error.HasMethod(value,, N)
, where N is the number of parameters that will be passed to the function.The caller of a function should generally know what each parameter means and how many there are before calling the function. However, for dynamic calls, the function is often written to suit the function call, and in such cases failure might be caused by a mistake in the function definition rather than incorrect parameter values.
301 | 302 |When AND, OR, and the ternary operator are used within an expression, they short-circuit to enhance performance (regardless of whether any function calls are present). Short-circuiting operates by refusing to evaluate parts of an expression that cannot possibly affect its final result. To illustrate the concept, consider this example:
304 |if (ColorName != "" AND not FindColor(ColorName)) 305 | MsgBox ColorName " could not be found."306 |
In the example above, the FindColor() function never gets called if the ColorName variable is empty. This is because the left side of the AND would be false, and thus its right side would be incapable of making the final outcome true.
307 |Because of this behavior, it's important to realize that any side-effects produced by a function (such as altering a global variable's contents) might never occur if that function is called on the right side of an AND or OR.
308 |It should also be noted that short-circuit evaluation cascades into nested ANDs and ORs. For example, in the following expression, only the leftmost comparison occurs whenever ColorName is blank. This is because the left side would then be enough to determine the final answer with certainty:
309 |if (ColorName = "" OR FindColor(ColorName, Region1) OR FindColor(ColorName, Region2)) 310 | break ; Nothing to search for, or a match was found.311 |
As shown by the examples above, any expensive (time-consuming) functions should generally be called on the right side of an AND or OR to enhance performance. This technique can also be used to prevent a function from being called when one of its parameters would be passed a value it considers inappropriate, such as an empty string.
312 |The ternary conditional operator (?:) also short-circuits by not evaluating the losing branch.
313 | 314 |A nested function is one defined inside another function. For example:
316 |317 | outer(x) { 318 | inner(y) { 319 | MsgBox(y, x) 320 | } 321 | inner("one") 322 | inner("two") 323 | } 324 | outer("title") 325 |326 |
A nested function is not accessible by name outside of the function which immediately encloses it, but is accessible anywhere inside that function, including inside other nested functions (with exceptions).
327 |By default, a nested function may access any static variable of any function which encloses it, even dynamically. However, a non-dynamic assignment inside a nested function typically resolves to a local variable if the outer function has neither a declaration nor a non-dynamic assignment for that variable.
328 |By default, a nested function automatically "captures" a non-static local variable of an outer function when the following requirements are met:
329 |local
, or as a parameter or nested function.A nested function which has captured variables is known as a closure.
339 |Non-static local variables of the outer function cannot be accessed dynamically unless they have been captured.
340 |Explicit declarations always take precedence over local variables of the function which encloses them. For example, local x
declares a variable local to the current function, independent of any x
in the outer function. Global declarations in the outer function also affect nested functions, except where overridden by an explicit declaration.
If a function is declared assume-global, any local or static variables created outside that function are not directly accessible to the function itself or any of its nested functions. By contrast, a nested function which is assume-static can still refer to variables from the outer function, unless the function itself is declared static.
342 |Functions are assume-local by default, and this is true even for nested functions, even those inside an assume-static function. However, if the outer function is assume-global, nested functions behave as though assume-global by default, except that they can refer to local and static variables of the outer function.
343 |Each function definition creates a read-only variable containing the function itself; that is, a Func or Closure object. See below for examples of how this might be used.
344 | 345 |Any nested function which does not capture variables is automatically static; that is, every call to the outer function references the same Func. The keyword static
can be used to explicitly declare a nested function as static, in which case any non-static local variables of the outer function are ignored. For example:
outer() { 348 | x := "outer value" 349 | static inner() { 350 | x := "inner value" ; Creates a variable local to inner 351 | MsgBox type(inner) ; Displays "Func" 352 | } 353 | inner() 354 | MsgBox x ; Displays "outer value" 355 | } 356 | outer()357 |
A static function cannot refer to other nested functions outside its own body unless they are explicitly declared static. Note that even if the function is assume-static, a non-static nested function may become a closure if it references a function parameter.
358 | 359 |A closure is a nested function bound to a set of free variables. Free variables are local variables of the outer function which are also used by nested functions. Closures allow one or more nested functions to share variables with the outer function even after the outer function returns.
361 |To create a closure, simply define a nested function which refers to variables of the outer function. For example:
362 |363 | make_greeter(f) 364 | { 365 | greet(subject) ; This will be a closure due to f. 366 | { 367 | MsgBox Format(f, subject) 368 | } 369 | return greet ; Return the closure. 370 | } 371 | 372 | g := make_greeter("Hello, {}!") 373 | g(A_UserName) 374 | g("World") 375 |376 |
Closures may also be used with built-in functions, such as SetTimer or Hotkey. For example:
377 |378 | app_hotkey(keyname, app_title, app_path) 379 | { 380 | activate(keyname) ; This will be a closure due to app_title and app_path. 381 | { 382 | if WinExist(app_title) 383 | WinActivate 384 | else 385 | Run app_path 386 | } 387 | Hotkey keyname, activate 388 | } 389 | ; Win+N activates or launches Notepad. 390 | app_hotkey "#n", "ahk_class Notepad", "notepad.exe" 391 | ; Win+W activates or launches WordPad. 392 | app_hotkey "#w", "ahk_class WordPadClass", "wordpad.exe" 393 |394 |
A nested function is automatically a closure if it captures any non-static local variables of the outer function. The variable corresponding to the closure itself (such as activate
) is also a non-static local variable, so any nested functions which refer to a closure are automatically closures.
Each call to the outer function creates new closures, distinct from any previous calls.
396 |It is best not to store a reference to a closure in any of the outer function's free variables, since that creates a reference cycle which must be broken (such as by clearing the variable) before the closure can be freed. However, a closure may safely refer to itself and other closures by their original variables without creating a problematic reference cycle. For example:
397 |398 | timertest() { 399 | x := "tock!" 400 | tick() { 401 | MsgBox x ; x causes this to become a closure. 402 | SetTimer tick, 0 ; Using the closure's original var is safe. 403 | ; SetTimer t, 0 ; Capturing t would create a reference cycle. 404 | } 405 | t := tick ; This is okay because t isn't captured above. 406 | SetTimer t, 1000 407 | } 408 | timertest() 409 |410 |
Each time the outer function is called, all of its free variables are allocated as a set. This one set of free variables is linked to all of the function's closures. If the closure's original variable (tick
in the example above) is captured by another closure within the same function, its lifetime is bound to the set. The set is deleted only when no references exist to any of its closures, except those in the original variables. This allows closures to refer to each other without causing a problematic reference cycle.
Closures which are not captured by other closures can be deleted before the set. All of the free variables within the set, including captured closures, cannot be deleted while such a closure exists.
412 | 413 |If the flow of execution within a function reaches the function's closing brace prior to encountering a Return, the function ends and returns a blank value (empty string) to its caller. A blank value is also returned whenever the function explicitly omits Return's parameter.
415 |When a function uses Exit to terminate the current thread, its caller does not receive a return value at all. For example, the statement Var := Add(2, 3)
would leave Var
unchanged if Add()
exits. The same thing happens if the function is exited because of Throw or a runtime error (such as running a nonexistent file).
To call a function with one or more blank values (empty strings), use an empty pair of quotes as in this example: FindColor(ColorName, "")
.
Since calling a function does not start a new thread, any changes made by a function to settings such as SendMode and SetTitleMatchMode will go into effect for its caller too.
418 |When used inside a function, ListVars displays a function's local variables along with their contents. This can help debug a script.
419 |You might find that complex functions are more readable and maintainable if their special variables are given a distinct prefix. For example, naming each parameter in a function's parameter list with a leading "p" or "p_" makes their special nature easy to discern at a glance, especially when a function has several dozen local variables competing for your attention. Similarly, the prefix "r" or "r_" could be used for ByRef parameters, and "s" or "s_" could be used for static variables.
421 |The One True Brace (OTB) style may optionally be used to define functions. For example:
422 |Add(x, y) { 423 | return x + y 424 | }425 | 426 |
The #Include directive may be used to load functions from an external file.
428 | 429 |A built-in function is overridden if the script defines its own function of the same name. For example, a script could have its own custom WinExist function that is called instead of the standard one. However, the script would then have no way to call the original function.
431 |External functions that reside in DLL files may be called with DllCall.
432 |To get a list of all built-in functions, see Alphabetical Function Index.
433 | 434 | 435 | -------------------------------------------------------------------------------- /docs/HotkeyFeatures.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Some of the easiest keys to reach on the keyboard are also the least frequently used. Make these keys do something useful! For example, if you rarely use the right Alt, make it perform the action you do most often:
44 |RAlt::MsgBox "You pressed the right ALT key."45 |
You can even do the above without losing the native function of the right Alt by assigning the right Alt to be a "prefix" for at least one other hotkey. In the below example, the right Alt has become a prefix, which automatically allows it to modify all other keys as it normally would. But if you press and release the right Alt without having used it to modify another key, its hotkey action (above) will take effect immediately:
46 |RAlt & j::AltTab47 | 48 |
Don't be limited to using only Ctrl, Alt, Shift, and Win as modifiers; you can combine any two keys or mouse buttons to form a custom hotkey. For example: Hold down Numpad0 and press Numpad1 to launch a hotkey (Numpad0 & Numpad1::
); hold down CapsLock and press another key, or click a mouse button (CapsLock & RButton::
). In this case, CapsLock's state (on or off) is not changed when it is used to launch the hotkey. For details, see custom combinations of keys.
Convert the mouse wheel (or any other keys of your choice) into a complete substitute for Alt-Tab. Click the wheel to show or hide the menu, and turn it to navigate through the menu. The wheel will still function normally whenever the Alt-Tab menu isn't visible. Syntax:
53 |MButton::AltTabMenu 54 | WheelDown::AltTab 55 | WheelUp::ShiftAltTab56 | 57 |
Make a keyboard key become a mouse button, or have an action repeated continuously while you're holding down a key or mouse button. See the remapping page for examples.
59 | 60 |Have your easiest-to-reach hotkeys perform an action appropriate to the type of window you're working with. In the following example, the right Ctrl performs a different action depending on whether Notepad or Calculator is the active window:
62 |#HotIf WinActive("ahk_class Notepad") 63 | RControl::Send "^s" ; Save the current file in Notepad. 64 | 65 | #HotIf WinActive("Calculator") 66 | RControl::Send "^c!{tab}^v" ; Copy the Calculator's result into the previously active window.67 |
See #HotIf for details.
68 | 69 |Also known as hotstrings. No special training or scripting experience is needed. For example, a script containing the following lines would expand ceo, cfo, and btw wherever you type them:
71 |::ceo::Chief Executive Officer 72 | ::cfo::Chief Financial Officer 73 | ::btw::by the way74 | 75 |
Reduce wear and tear on your fingers by using virtually any key as a hotkey, including single letters, arrow keys, Numpad keys, and even the modifier keys themselves (Ctrl, Alt, Win, and Shift).
79 | 80 |Create mouse hotkeys, including the mouse wheel button (MButton) and the turning of the wheel up/down or left/right (WheelUp, WheelDown, WheelLeft, and WheelRight). You can also combine a keyboard key with a mouse button. For example, control-right-button would be expressed as ^RButton::
.
For example, the left mouse button can trigger a hotkey action even while the click itself is being sent into the game normally (syntax: ~LButton::
).
Use functions such as PixelSearch, PixelGetColor, and ImageSearch to automate game actions.
88 | 89 |Have the option of using the keyboard hook to implement hotkeys, which might be more responsive than other hotkey methods while the CPU is under load in a game. The hook might also be able to override any restrictions a game may have about which keys can be "mapped" to game actions.
91 | 92 |Hotkeys are sometimes referred to as shortcut keys because of their ability to easily trigger an action (such as launching a program or keyboard macro). In the following example, the hotkey Win+N is configured to launch Notepad. The pound sign [#] stands for Win, which is known as a modifier key:
32 |#n:: 33 | { 34 | Run "notepad" 35 | }36 |
In the above, the braces serve to define a function body for the hotkey. The opening brace may also be specified on the same line as the double-colon to support the OTB (One True Brace) style. However, if a hotkey needs to execute only a single line, that line can be listed to the right of the double-colon. In other words, the braces are implicit:
37 |#n::Run "notepad"38 |
When a hotkey is triggered, the name of the hotkey is passed as its first parameter named ThisHotkey
(which excludes the trailing colons). For example:
#n::MsgBox ThisHotkey ; Reports #n40 |
With few exceptions, this is similar to the built-in variable A_ThisHotkey. The parameter name can be changed by using a named function.
41 |To use more than one modifier with a hotkey, list them consecutively (the order does not matter). The following example uses ^!s
to indicate Ctrl+Alt+S:
^!s:: 43 | { 44 | Send "Sincerely,{enter}John Smith" ; This line sends keystrokes to the active (foremost) window. 45 | }46 |
You can use the following modifier symbols to define hotkeys:
48 |Symbol | 51 |Description | 52 |
---|---|
# | 55 |
56 | Win (Windows logo key). 57 |Hotkeys that include Win (e.g. #a) will wait for Win to be released before sending any text containing an L keystroke. This prevents usages of Send within such a hotkey from locking the PC. This behavior applies to all sending modes except SendPlay (which doesn't need it), blind mode and text mode. 58 |Note: Pressing a hotkey which includes Win may result in extra simulated keystrokes (Ctrl by default). See A_MenuMaskKey. 59 | |
60 |
! | 63 |
64 | Alt 65 |Note: Pressing a hotkey which includes Alt may result in extra simulated keystrokes (Ctrl by default). See A_MenuMaskKey. 66 | |
67 |
^ | 70 |Ctrl | 71 |
+ | 74 |Shift | 75 |
& | 78 |An ampersand may be used between any two keys or mouse buttons to combine them into a custom hotkey. See below for details. | 79 |
< | 82 |Use the left key of the pair. e.g. <!a is the same as !a except that only the left Alt will trigger it. | 83 |
> | 86 |Use the right key of the pair. | 87 |
<^>! | 90 |AltGr (alternate graph, or alternate graphic). If your keyboard layout has AltGr instead of a right Alt key, this series of symbols can usually be used to stand for AltGr. For example: 91 |<^>!m::MsgBox "You pressed AltGr+m." 92 | <^<!m::MsgBox "You pressed LeftControl+LeftAlt+m."93 | Alternatively, to make AltGr itself into a hotkey, use the following hotkey (without any hotkeys like the above present): 94 |LControl & RAlt::MsgBox "You pressed AltGr itself." |
95 |
* | 98 |Wildcard: Fire the hotkey even if extra modifiers are being held down. This is often used in conjunction with remapping keys or buttons. For example: 99 |*#c::Run "calc.exe" ; Win+C, Shift+Win+C, Ctrl+Win+C, etc. will all trigger this hotkey. 100 | *ScrollLock::Run "notepad" ; Pressing ScrollLock will trigger this hotkey even when modifier key(s) are down.101 | Wildcard hotkeys always use the keyboard hook, as do any hotkeys eclipsed by a wildcard hotkey. For example, the presence of |
102 |
~ | 105 |When the hotkey fires, its key's native function will not be blocked (hidden from the system). In both of the below examples, the user's click of the mouse button will be sent to the active window: 106 |~RButton::MsgBox "You clicked the right mouse button." 107 | ~RButton & C::MsgBox "You pressed C while holding down the right mouse button."108 | Unlike the other prefix symbols, the tilde prefix is allowed to be present on some of a hotkey's variants but absent on others. However, if a tilde is applied to the prefix key of any custom combination which has not been turned off or suspended, it affects the behavior of that prefix key for all combinations. 109 |Special hotkeys that are substitutes for alt-tab always ignore the tilde prefix. 110 |If the tilde prefix is applied to a custom modifier key (prefix key) which is also used as its own hotkey, that hotkey will fire when the key is pressed instead of being delayed until the key is released. For example, the ~RButton hotkey above is fired as soon as the button is pressed. 111 |If the tilde prefix is applied only to the custom combination and not the non-combination hotkey, the key's native function will still be blocked. For example, in the script below, holding Menu will show the tooltip and will not trigger a context menu: 112 |AppsKey::ToolTip "Press < or > to cycle through windows." 113 | AppsKey Up::ToolTip 114 | ~AppsKey & <::Send "!+{Esc}" 115 | ~AppsKey & >::Send "!{Esc}"116 | If at least one variant of a keyboard hotkey has the tilde modifier, that hotkey always uses the keyboard hook. 117 | |
118 |
$ | 121 |
122 | This is usually only necessary if the script uses the Send function to send the keys that comprise the hotkey itself, which might otherwise cause it to trigger itself. The $ prefix forces the keyboard hook to be used to implement this hotkey, which as a side-effect prevents the Send function from triggering it. The $ prefix is equivalent to having specified The $ prefix has no effect for mouse hotkeys, since they always use the mouse hook. It also has no effect for hotkeys which already require the keyboard hook, including any keyboard hotkeys with the tilde (~) or wildcard (*) modifiers, key-up hotkeys and custom combinations. To determine whether a particular hotkey uses the keyboard hook, use ListHotkeys. 124 |#InputLevel and SendLevel provide additional control over which hotkeys and hotstrings are triggered by the Send function. 125 | |
126 |
UP | 129 |The word UP may follow the name of a hotkey to cause the hotkey to fire upon release of the key rather than when the key is pressed down. The following example remaps the left Win to become the left Ctrl: 130 |*LWin::Send "{LControl down}" 131 | *LWin Up::Send "{LControl up}" 132 |133 | "Up" can also be used with normal hotkeys as in this example: Limitations: 1) "Up" does not work with controller buttons; and 2) An "Up" hotkey without a normal/down counterpart hotkey will completely take over that key to prevent it from getting stuck down. One way to prevent this is to add a tilde prefix (e.g. "Up" hotkeys and their key-down counterparts (if any) always use the keyboard hook. 136 |On a related note, a technique similar to the above is to make a hotkey into a prefix key. The advantage is that although the hotkey will fire upon release, it will do so only if you did not press any other key while it was held down. For example: 137 |LControl & F1::return ; Make left-control a prefix by using it in front of "&" at least once. 138 | LControl::MsgBox "You released LControl without having used it to modify any other key." |
139 |
Note: See the Key List for a complete list of keyboard keys and mouse/controller buttons.
142 |Multiple hotkeys can be stacked vertically to have them perform the same action. For example:
143 |^Numpad0:: 144 | ^Numpad1:: 145 | { 146 | MsgBox "Pressing either Ctrl+Numpad0 or Ctrl+Numpad1 will display this." 147 | } 148 |149 |
A key or key-combination can be disabled for the entire system by having it do nothing. The following example disables the right-side Win:
150 |RWin::return151 | 152 |
The #HotIf directive can be used to make a hotkey perform a different action (or none at all) depending on a specific condition. For example:
154 |#HotIf WinActive("ahk_class Notepad") 155 | ^a::MsgBox "You pressed Ctrl-A while Notepad is active. Pressing Ctrl-A in any other window will pass the Ctrl-A keystroke to that window." 156 | #c::MsgBox "You pressed Win-C while Notepad is active." 157 | 158 | #HotIf 159 | #c::MsgBox "You pressed Win-C while any window except Notepad is active." 160 | 161 | #HotIf MouseIsOver("ahk_class Shell_TrayWnd") ; For MouseIsOver, see #HotIf example 1. 162 | WheelUp::Send "{Volume_Up}" ; Wheel over taskbar: increase/decrease volume. 163 | WheelDown::Send "{Volume_Down}" ; 164 |165 | 166 |
Normally shortcut key combinations consist of optional prefix/modifier keys (Ctrl, Alt, Shift and LWin/RWin) and a single suffix key. The standard modifier keys are designed to be used in this manner, so normally have no immediate effect when pressed down.
168 |A custom combination of two keys (including mouse but not controller buttons) can be defined by using " & " between them. Because they are intended for use with prefix keys that are not normally used as such, custom combinations have the following special behavior:
169 |Note: For combinations with standard modifier keys, it is usually better to use the standard syntax. For example, use <+s::
rather than LShift & s::
.
In the below example, you would hold down Numpad0 then press the second key to trigger the hotkey:
175 |Numpad0 & Numpad1::MsgBox "You pressed Numpad1 while holding down Numpad0." 176 | Numpad0 & Numpad2::Run "Notepad"177 |
The prefix key loses its native function: In the above example, Numpad0 becomes a prefix key; but this also causes Numpad0 to lose its original/native function when it is pressed by itself. To avoid this, a script may configure Numpad0 to perform a new action such as one of the following:
178 |Numpad0::WinMaximize "A" ; Maximize the active/foreground window. 179 | Numpad0::Send "{Numpad0}" ; Make the release of Numpad0 produce a Numpad0 keystroke. See comment below.180 |
Fire on release: The presence of one of the above custom combination hotkeys causes the release of Numpad0 to perform the indicated action, but only if you did not press any other keys while Numpad0 was being held down. This behaviour can be avoided by applying the tilde prefix to either hotkey.
181 |Modifiers: Unlike a normal hotkey, custom combinations act as though they have the wildcard (*) modifier by default. For example, 1 & 2::
will activate even if Ctrl or Alt is held down when 1 and 2 are pressed, whereas ^1::
would be activated only by Ctrl+1 and not Ctrl+Alt+1.
Combinations of three or more keys are not supported. Combinations which your keyboard hardware supports can usually be detected by using #HotIf and GetKeyState, but the results may be inconsistent. For example:
183 |; Press AppsKey and Alt in any order, then slash (/). 184 | #HotIf GetKeyState("AppsKey", "P") 185 | Alt & /::MsgBox "Hotkey activated." 186 | 187 | ; If the keys are swapped, Alt must be pressed first (use one at a time): 188 | #HotIf GetKeyState("Alt", "P") 189 | AppsKey & /::MsgBox "Hotkey activated." 190 | 191 | ; [ & ] & \:: 192 | #HotIf GetKeyState("[") && GetKeyState("]") 193 | \::MsgBox194 |
Keyboard hook: Custom combinations involving keyboard keys always use the keyboard hook, as do any hotkeys which use the prefix key as a suffix. For example, a & b::
causes ^a::
to always use the hook.
NumLock, CapsLock, and ScrollLock: These keys may be forced to be "AlwaysOn" or "AlwaysOff". For example: SetNumLockState "AlwaysOn"
.
Overriding Explorer's hotkeys: Windows' built-in hotkeys such as Win+E (#e) and Win+R (#r) can be individually overridden simply by assigning them to an action in the script. See the override page for details.
199 |Substitutes for Alt-Tab: Hotkeys can provide an alternate means of alt-tabbing. For example, the following two hotkeys allow you to alt-tab with your right hand:
200 |RControl & RShift::AltTab ; Hold down right-control then press right-shift repeatedly to move forward. 201 | RControl & Enter::ShiftAltTab ; Without even having to release right-control, press Enter to reverse direction.202 |
For more details, see Alt-Tab.
203 | 204 |Hotkeys that fire upon turning the mouse wheel are supported via the key names WheelDown and WheelUp. Here are some examples of mouse wheel hotkeys:
206 |MButton & WheelDown::MsgBox "You turned the mouse wheel down while holding down the middle button." 207 | ^!WheelUp::MsgBox "You rotated the wheel up while holding down Control+Alt."208 |
If the mouse supports it, horizontal scrolling can be detected via the key names WheelLeft and WheelRight. Some mice have a single wheel which can be scrolled up and down or tilted left and right. Generally in those cases, WheelLeft or WheelRight signals are sent repeatedly while the wheel is held to one side, to simulate continuous scrolling. This typically causes the hotkeys to execute repeatedly.
209 |The built-in variable A_EventInfo contains the amount by which the wheel was turned, which is typically 120. However, A_EventInfo can be greater or less than 120 under the following circumstances:
210 |~WheelDown::ToolTip A_EventInfo
Some of the most useful hotkeys for the mouse wheel involve alternate modes of scrolling a window's text. For example, the following pair of hotkeys scrolls horizontally instead of vertically when you turn the wheel while holding down the left Ctrl:
215 |~LControl & WheelUp:: ; Scroll left. 216 | { 217 | Loop 2 ; <-- Increase this value to scroll faster. 218 | SendMessage 0x0114, 0, 0, ControlGetFocus("A") ; 0x0114 is WM_HSCROLL and the 0 after it is SB_LINELEFT. 219 | } 220 | 221 | ~LControl & WheelDown:: ; Scroll right. 222 | { 223 | Loop 2 ; <-- Increase this value to scroll faster. 224 | SendMessage 0x0114, 1, 0, ControlGetFocus("A") ; 0x0114 is WM_HSCROLL and the 1 after it is SB_LINERIGHT. 225 | }226 |
Finally, since mouse wheel hotkeys generate only down-events (never up-events), they cannot be used as key-up hotkeys.
227 | 228 |Each numpad key can be made to launch two different hotkey subroutines depending on the state of NumLock. Alternatively, a numpad key can be made to launch the same subroutine regardless of the state. For example:
230 |NumpadEnd:: 231 | Numpad1:: 232 | { 233 | MsgBox "This hotkey is launched regardless of whether NumLock is on." 234 | } 235 |236 |
If the tilde (~) symbol is used with a prefix key even once, it changes the behavior of that prefix key for all combinations. For example, in both of the below hotkeys, the active window will receive all right-clicks even though only one of the definitions contains a tilde:
237 |~RButton & LButton::MsgBox "You pressed the left mouse button while holding down the right." 238 | RButton & WheelUp::MsgBox "You turned the mouse wheel up while holding down the right button."239 |
The Suspend function can temporarily disable all hotkeys except for ones you make exempt. For greater selectivity, use #HotIf.
240 |By means of the Hotkey function, hotkeys can be created dynamically while the script is running. The Hotkey function can also modify, disable, or enable the script's existing hotkeys individually.
241 |Controller hotkeys do not currently support modifier prefixes such as ^ (Ctrl) and # (Win). However, you can use GetKeyState to mimic this effect as shown in the following example:
242 |Joy2:: 243 | { 244 | if not GetKeyState("Control") ; Neither the left nor right Control key is down. 245 | return ; i.e. Do nothing. 246 | MsgBox "You pressed the first controller's second button while holding down the Control key." 247 | }248 |
There may be times when a hotkey should wait for its own modifier keys to be released before continuing. Consider the following example:
249 |^!s::Send "{Delete}"250 |
Pressing Ctrl+Alt+S would cause the system to behave as though you pressed Ctrl+Alt+Del (due to the system's aggressive detection of this hotkey). To work around this, use KeyWait to wait for the keys to be released; for example:
251 |^!s:: 252 | { 253 | KeyWait "Control" 254 | KeyWait "Alt" 255 | Send "{Delete}" 256 | } 257 |258 |
If a hotkey like #z::
produces an error like "Invalid Hotkey", your system's keyboard layout/language might not have the specified character ("Z" in this case). Try using a different character that you know exists in your keyboard layout.
A hotkey's function can be called explicitly by the script only if the function has been named. See Named Function Hotkeys.
260 |One common use for hotkeys is to start and stop a repeating action, such as a series of keystrokes or mouse clicks. For an example of this, see this FAQ topic.
261 |Finally, each script is quasi multi-threaded, which allows a new hotkey to be launched even when a previous hotkey subroutine is still running. For example, new hotkeys can be launched even while a message box is being displayed by the current hotkey.
262 | 263 |Alt-Tab hotkeys simplify the mapping of new key combinations to the system's Alt-Tab hotkeys, which are used to invoke a menu for switching tasks (activating windows).
265 |Each Alt-Tab hotkey must be either a single key or a combination of two keys, which is typically achieved via the ampersand symbol (&). In the following example, you would hold down the right Alt and press J or K to navigate the alt-tab menu:
266 |RAlt & j::AltTab 267 | RAlt & k::ShiftAltTab268 |
AltTab and ShiftAltTab are two of the special commands that are only recognized when used on the same line as a hotkey. Here is the complete list:
269 |AltTab: If the alt-tab menu is visible, move forward in it. Otherwise, display the menu (only if the hotkey is a combination of two keys; otherwise, it does nothing).
270 |ShiftAltTab: Same as above except move backward in the menu.
271 |AltTabMenu: Show or hide the alt-tab menu.
272 |AltTabAndMenu: If the alt-tab menu is visible, move forward in it. Otherwise, display the menu.
273 |AltTabMenuDismiss: Close the Alt-tab menu.
274 |To illustrate the above, the mouse wheel can be made into an entire substitute for Alt-tab. With the following hotkeys in effect, clicking the middle button displays the menu and turning the wheel navigates through it:
275 |MButton::AltTabMenu 276 | WheelDown::AltTab 277 | WheelUp::ShiftAltTab278 |
To cancel the Alt-Tab menu without activating the selected window, press or send Esc. In the following example, you would hold the left Ctrl and press CapsLock to display the menu and advance forward in it. Then you would release the left Ctrl to activate the selected window, or press the mouse wheel to cancel. Define the AltTabWindow window group as shown below before running this example.
279 |LCtrl & CapsLock::AltTab 280 | #HotIf WinExist("ahk_group AltTabWindow") ; Indicates that the alt-tab menu is present on the screen. 281 | *MButton::Send "{Blind}{Escape}" ; The * prefix allows it to fire whether or not Alt is held down. 282 | #HotIf283 |
If the script sent {Alt Down}
(such as to invoke the Alt-Tab menu), it might also be necessary to send {Alt Up}
as shown in the example further below.
Currently, all special Alt-tab actions must be assigned directly to a hotkey as in the examples above (i.e. they cannot be used as though they were functions). They are not affected by #HotIf.
287 |An alt-tab action may take effect on key-down and/or key-up regardless of whether the up
keyword is used, and cannot be combined with another action on the same key. For example, using both F1::AltTabMenu
and F1 up::OtherAction()
is unsupported.
Custom alt-tab actions can also be created via hotkeys. As the identity of the alt-tab menu differs between OS versions, it may be helpful to use a window group as shown below. For the examples above and below which use ahk_group AltTabWindow
, this window group is expected to be defined during script startup. Alternatively, ahk_group AltTabWindow
can be replaced with the appropriate ahk_class
for your system.
GroupAdd "AltTabWindow", "ahk_class MultitaskingViewFrame" ; Windows 10 290 | GroupAdd "AltTabWindow", "ahk_class TaskSwitcherWnd" ; Windows Vista, 7, 8.1 291 | GroupAdd "AltTabWindow", "ahk_class #32771" ; Older, or with classic alt-tab enabled292 |
In the following example, you would press F1 to display the menu and advance forward in it. Then you would press F2 to activate the selected window, or press Esc to cancel:
293 |*F1::Send "{Alt down}{tab}" ; Asterisk is required in this case. 294 | !F2::Send "{Alt up}" ; Release the Alt key, which activates the selected window. 295 | #HotIf WinExist("ahk_group AltTabWindow") 296 | ~*Esc::Send "{Alt up}" ; When the menu is cancelled, release the Alt key automatically. 297 | ;*Esc::Send "{Esc}{Alt up}" ; Without tilde (~), Escape would need to be sent. 298 | #HotIf299 | 300 |
If the function of a hotkey is ever needed to be called without triggering the hotkey itself, one or more hotkeys can be assigned a named function by simply defining it immediately after the hotkey's double-colon as in this example:
302 |; Ctrl+Shift+O to open containing folder in Explorer. 303 | ; Ctrl+Shift+E to open folder with current file selected. 304 | ; Supports SciTE and Notepad++ (may require title bar setting changes). 305 | ^+o:: 306 | ^+e:: 307 | editor_open_folder(hk) 308 | { 309 | path := WinGetTitle("A") 310 | if RegExMatch(path, "\*?\K(.*)\\[^\\]+(?= [-*] )", &path) 311 | if (FileExist(path[0]) && hk = "^+e") 312 | Run Format('explorer.exe /select,"{1}"', path[0]) 313 | else 314 | Run Format('explorer.exe "{1}"', path[1]) 315 | }316 |
If the function editor_open_folder is ever called explicitly by the script, the first parameter (hk) must be passed a value.
317 |Hotstrings can also be defined this way. Multiple hotkeys or hotstrings can be stacked together to call the same function.
318 |There must only be whitespace or comments between the hotkey and the function name.
319 |Naming the function also encourages self-documenting hotkeys, like in the code above where the function name describes the hotkey.
320 |The Hotkey function can also be used to assign a function or function object to a hotkey.
321 | 322 | 323 | 324 | -------------------------------------------------------------------------------- /docs/Hotstrings.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Although hotstrings are mainly used to expand abbreviations as you type them (auto-replace), they can also be used to launch any scripted action. In this respect, they are similar to hotkeys except that they are typically composed of more than one character (that is, a string).
31 |To define a hotstring, enclose the triggering abbreviation between pairs of colons as in this example:
32 |::btw::by the way33 |
In the above example, the abbreviation btw will be automatically replaced with "by the way" whenever you type it (however, by default you must type an ending character after typing btw, such as Space, ., or Enter).
34 |The "by the way" example above is known as an auto-replace hotstring because the typed text is automatically erased and replaced by the string specified after the second pair of colons. By contrast, a hotstring may also be defined to perform any custom action as in the following examples. Note that the statements must appear beneath the abbreviation within the hotstring's function body:
35 |::btw:: 36 | { 37 | MsgBox 'You typed "btw".' 38 | } 39 | 40 | :*:]d:: ; This hotstring replaces "]d" with the current date and time via the statement below. 41 | { 42 | Send FormatTime(, "M/d/yyyy h:mm tt") ; It will look like 9/1/2005 3:53 PM 43 | }44 |
In the above, the braces serve to define a function body for each hotstring. The opening brace may also be specified on the same line as the double-colon to support the OTB (One True Brace) style.
45 |Even though the two examples above are not auto-replace hotstrings, the abbreviation you type is erased by default. This is done via automatic backspacing, which can be disabled via the b0 option.
46 |When a hotstring is triggered, the name of the hotstring is passed as its first parameter named ThisHotkey
(which excludes the trailing colons). For example:
:X:btw::MsgBox ThisHotkey ; Reports :X:btw48 |
With few exceptions, this is similar to the built-in variable A_ThisHotkey. The parameter name can be changed by using a named function.
49 | 50 |Unless the asterisk option is in effect, you must type an ending character after a hotstring's abbreviation to trigger it. Ending characters initially consist of the following: -()[]{}':;"/\,.?!`n`s`t (note that `n is Enter, `s is Space, and `t is Tab). This set of characters can be changed by editing the following example, which sets the new ending characters for all hotstrings, not just the ones beneath it:
52 |#Hotstring EndChars -()[]{}:;'"/\,.?!`n`s`t53 |
The ending characters can be changed while the script is running by calling the Hotstring function as demonstrated below:
54 |Hotstring("EndChars", "-()[]{}:;")55 | 56 |
A hotstring's default behavior can be changed in two possible ways:
58 |#Hotstring c r
.:c*:j@::john@somedomain.com
.The list below describes each option. When specifying more than one option using the methods above, spaces optionally may be included between them.
63 |* (asterisk): An ending character (e.g. Space, ., or Enter) is not required to trigger the hotstring. For example:
64 |:*:j@::jsmith@somedomain.com65 |
The example above would send its replacement the moment you type the @ character. When using the #Hotstring directive, use *0 to turn this option back off.
66 |? (question mark): The hotstring will be triggered even when it is inside another word; that is, when the character typed immediately before it is alphanumeric. For example, if :?:al::airline
is a hotstring, typing "practical " would produce "practicairline ". Use ?0 to turn this option back off.
B0 (B followed by a zero): Automatic backspacing is not done to erase the abbreviation you type. Use a plain B to turn backspacing back on after it was previously turned off. A script may also do its own backspacing via {bs 5}, which sends Backspace five times. Similarly, it may send ← five times via {left 5}. For example, the following hotstring produces "<em></em>" and moves the caret 5 places to the left (so that it's between the tags):
68 |:*b0:<em>::</em>{left 5}69 |
C: Case-sensitive: When you type an abbreviation, it must exactly match the case defined in the script. Use C0 to turn case sensitivity back off.
70 |C1: Do not conform to typed case. Use this option to make auto-replace hotstrings case-insensitive and prevent them from conforming to the case of the characters you actually type. Case-conforming hotstrings (which are the default) produce their replacement text in all caps if you type the abbreviation in all caps. If you type the first letter in caps, the first letter of the replacement will also be capitalized (if it is a letter). If you type the case in any other way, the replacement is sent exactly as defined. When using the #Hotstring directive, C0 can be used to turn this option back off, which makes hotstrings conform again.
71 |Kn: Key-delay: This rarely-used option sets the delay between keystrokes produced by auto-backspacing or auto-replacement. Specify the new delay for n; for example, specify k10 to have a 10 ms delay and k-1 to have no delay. The exact behavior of this option depends on which sending mode is in effect:
72 |ProcessSetPriority "High"
.O: Omit the ending character of auto-replace hotstrings when the replacement is produced. This is useful when you want a hotstring to be kept unambiguous by still requiring an ending character, but don't actually want the ending character to be shown on the screen. For example, if :o:ar::aristocrat
is a hotstring, typing "ar" followed by the spacebar will produce "aristocrat" with no trailing space, which allows you to make the word plural or possessive without having to press Backspace. Use O0 (the letter O followed by a zero) to turn this option back off.
Pn: The priority of the hotstring (e.g. P1). This rarely-used option has no effect on auto-replace hotstrings.
79 |R: Send the replacement text raw; that is, without translating {Enter} to Enter, ^c to Ctrl+C, etc. Use R0 to turn this option back off, or override it with T.
80 |Note: Text mode may be more reliable. The R and T options are mutually exclusive.
81 |S or S0: Specify the letter S to make the hotstring exempt from Suspend. Specify S0 (S with the number 0) to remove the exemption, allowing the hotstring to be suspended. When applied as a default option, either S
or #SuspendExempt
will make the hotstring exempt; that is, to override the directive, S0
must be used explicitly in the hotstring.
SI or SP or SE: Sets the method by which auto-replace hotstrings send their keystrokes. These options are mutually exclusive: only one can be in effect at a time. The following describes each option:
83 |If none of the above options are used, the default mode is SendInput. However, unlike the SI option, SendEvent is used instead of SendPlay when SendInput is unavailable.
89 |T: Send the replacement text using Text mode. That is, send each character by character code, without translating {Enter} to Enter, ^c to Ctrl+C, etc. and without translating each character to a keystroke. This option is put into effect automatically for hotstrings that have a continuation section. Use T0 or R0 to turn this option back off, or override it with R.
90 |X: Execute. Instead of replacement text, the hotstring accepts a function call or expression to execute. For example, :X:~mb::MsgBox
would cause a message box to be displayed when the user types "~mb" instead of auto-replacing it with the word "MsgBox". This is most useful when defining a large number of hotstrings which call functions, as it would otherwise require three lines per hotstring.
This option should not be used with the Hotstring function. To make a hotstring call a function when triggered, pass the function by reference.
92 |Z: This rarely-used option resets the hotstring recognizer after each triggering of the hotstring. In other words, the script will begin waiting for an entirely new hotstring, eliminating from consideration anything you previously typed. This can prevent unwanted triggerings of hotstrings. To illustrate, consider the following hotstring:
93 |:b0*?:11:: 94 | { 95 | Send "xx" 96 | }97 |
Since the above lacks the Z option, typing 111 (three consecutive 1's) would trigger the hotstring twice because the middle 1 is the last character of the first triggering but also the first character of the second triggering. By adding the letter Z in front of b0, you would have to type four 1's instead of three to trigger the hotstring twice. Use Z0 to turn this option back off.
98 |Hotstrings that produce a large amount of replacement text can be made more readable and maintainable by using a continuation section. For example:
100 |::text1:: 101 | ( 102 | Any text between the top and bottom parentheses is treated literally. 103 | By default, the hard carriage return (Enter) between the previous line and this one is also preserved. 104 | By default, the indentation (tab) to the left of this line is preserved. 105 | )106 |
See continuation section for how to change these default behaviors. The presence of a continuation section also causes the hotstring to default to Text mode. The only way to override this special default is to specify an opposing option in each hotstring that has a continuation section (e.g. :t0:text1::
or :r:text2::
).
The #HotIf directive can be used to make selected hotstrings context sensitive. Such hotstrings send a different replacement, perform a different action, or do nothing at all depending on any condition, such as the type of window that is active. For example:
109 |#HotIf WinActive("ahk_class Notepad") 110 | ::btw::This replacement text will appear only in Notepad. 111 | #HotIf 112 | ::btw::This replacement text appears in windows other than Notepad.113 | 114 |
The following script uses hotstrings to correct about 4700 common English misspellings on-the-fly. It also includes a Win+H hotkey to make it easy to add more misspellings:
116 |Download: AutoCorrect.ahk (127 KB)
117 |Author: Jim Biancolo and Wikipedia's Lists of Common Misspellings
118 | 119 |Expressions are not currently supported within the replacement text. To work around this, don't make such hotstrings auto-replace. Instead, use the Send function in the body of the hotstring or in combination with the X (execute) option.
121 |To send an extra space or tab after a replacement, include the escape sequence `s
or `t
at the end of the replacement, e.g. :*:btw::by the way`s
.
For an auto-replace hotstring which doesn't use the Text or Raw mode, sending a {
alone, or one preceded only by white-space, requires it being enclosed in a pair of brackets, for example :*:brace::{{}
and :*:space_brace:: {{}
. Otherwise it is interpreted as the opening brace for the hotstring's function to support the OTB (One True Brace) style.
By default, any click of the left or right mouse button will reset the hotstring recognizer. In other words, the script will begin waiting for an entirely new hotstring, eliminating from consideration anything you previously typed (if this is undesirable, specify the line #Hotstring NoMouse
anywhere in the script). This "reset upon mouse click" behavior is the default because each click typically moves the text insertion point (caret) or sets keyboard focus to a new control/field. In such cases, it is usually desirable to: 1) fire a hotstring even if it lacks the question mark option; 2) prevent a firing when something you type after clicking the mouse accidentally forms a valid abbreviation with what you typed before.
The hotstring recognizer checks the active window each time a character is typed, and resets if a different window is active than before. If the active window changes but reverts before any characters are typed, the change is not detected (but the hotstring recognizer may be reset for some other reason). The hotstring recognizer can also be reset by calling Hotstring "Reset"
.
The built-in variable A_EndChar contains the ending character that you typed to trigger the most recent non-auto-replace hotstring. If no ending character was required (due to the * option), this variable will be blank. A_EndChar is useful when making hotstrings that use the Send function or whose behavior should vary depending on which ending character you typed. To send the ending character itself, use SendText A_EndChar
(SendText is used because characters such as !{} would not be sent correctly by the normal Send function).
Although single-colons within hotstring definitions do not need to be escaped unless they precede the double-colon delimiter, backticks and those semicolons having a space or tab to their left must always be escaped. See Escape Sequences for a complete list.
127 |Although the Send function's special characters such as {Enter} are supported in auto-replacement text (unless the raw option is used), the hotstring abbreviations themselves do not use this. Instead, specify `n for Enter and `t (or a literal tab) for Tab (see Escape Sequences for a complete list). For example, the hotstring :*:ab`t::
would be triggered when you type "ab" followed by a tab.
Spaces and tabs are treated literally within hotstring definitions. For example, the following would produce two different results: ::btw::by the way
and ::btw:: by the way
.
Each hotstring abbreviation can be no more than 40 characters long. The program will warn you if this length is exceeded. By contrast, the length of hotstring's replacement text is limited to about 5000 characters when the sending mode is at its default of SendInput. That limit can be removed by switching to one of the other sending modes, or by using SendPlay or SendEvent in the body of the hotstring or in combination with the X (execute) option.
130 |The order in which hotstrings are defined determines their precedence with respect to each other. In other words, if more than one hotstring matches something you type, only the one listed first in the script will take effect. Related topic: context-sensitive hotstrings.
131 |Any backspacing you do is taken into account for the purpose of detecting hotstrings. However, the use of ↑, →, ↓, ←, PgUp, PgDn, Home, and End to navigate within an editor will cause the hotstring recognition process to reset. In other words, it will begin waiting for an entirely new hotstring.
132 |A hotstring may be typed even when the active window is ignoring your keystrokes. In other words, the hotstring will still fire even though the triggering abbreviation is never visible. In addition, you may still press Backspace to undo the most recently typed keystroke (even though you can't see the effect).
133 |A hotstring's function can be called explicitly by the script only if the function has been named. See Named Function Hotstrings.
134 |Hotstrings are not monitored and will not be triggered while input is blocked by an invisible Input hook.
135 |By default, hotstrings are never triggered by keystrokes produced by any AutoHotkey script. This avoids the possibility of an infinite loop where hotstrings trigger each other over and over. This behaviour can be controlled with #InputLevel and SendLevel. However, auto-replace hotstrings always use send level 0 and therefore never trigger hook hotkeys or hotstrings.
136 |The Suspend function can temporarily disable all hotstrings except for ones you make exempt. For greater selectivity, use #HotIf.
137 |Hotstrings can be created dynamically by means of the Hotstring function, which can also modify, disable, or enable the script's existing hotstrings individually.
138 |The InputHook function is more flexible than hotstrings for certain purposes. For example, it allows your keystrokes to be invisible in the active window (such as a game). It also supports non-character ending keys such as Esc.
139 |The keyboard hook is automatically used by any script that contains hotstrings.
140 |Hotstrings behave identically to hotkeys in the following ways:
141 |Known limitation: On some systems in Java applications, hotstrings might interfere with the user's ability to type diacritical letters (via dead keys). To work around this, Suspend can be turned on temporarily (which disables all hotstrings).
148 | 149 |If the function of a hotstring is ever needed to be called without triggering the hotstring itself, one or more hotstrings can be assigned a named function by simply defining it immediately after the hotstring's double-colon, as in this example:
151 |; This example also demonstrates one way to implement case conformity in a script. 152 | :C:BTW:: ; Typed in all-caps. 153 | :C:Btw:: ; Typed with only the first letter upper-case. 154 | : :btw:: ; Typed in any other combination. 155 | case_conform_btw(hs) ; hs will hold the name of the hotstring which triggered the function. 156 | { 157 | if (hs == ":C:BTW") 158 | Send "BY THE WAY" 159 | else if (hs == ":C:Btw") 160 | Send "By the way" 161 | else 162 | Send "by the way" 163 | } 164 |165 |
If the function case_conform_btw is ever called explicitly by the script, the first parameter (hs) must be passed a value.
166 |Hotkeys can also be defined this way. Multiple hotkeys or hotstrings can be stacked together to call the same function.
167 |There must only be whitespace or comments between the hotstring and the function name.
168 |Naming the function also encourages self-documenting hotstrings, like in the code above where the function name describes the hotstring.
169 |The Hotstring function can also be used to assign a function or function object to a hotstring.
170 | 171 |Take a look at the first example in the example section of the Hotstring function's page, which might be useful if you are a heavy user of hotstrings. By pressing Win+H (or another hotkey of your choice), the currently selected text can be turned into a hotstring. For example, if you have "by the way" selected in a word processor, pressing Win+H will prompt you for its abbreviation (e.g. btw), add the new hotstring to the script and activate it.
173 | 174 | 175 | -------------------------------------------------------------------------------- /docs/KeyList.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Name | 45 |Description | 46 |
---|---|
LButton | 49 |Primary mouse button. Which physical button this corresponds to depends on system settings; by default it is the left button. | 50 |
RButton | 53 |Secondary mouse button. Which physical button this corresponds to depends on system settings; by default it is the right button. | 54 |
MButton | 57 |Middle or wheel mouse button | 58 |
Name | 64 |Description | 65 |
---|---|
XButton1 | 68 |4th mouse button. Typically performs the same function as Browser_Back. | 69 |
XButton2 | 72 |5th mouse button. Typically performs the same function as Browser_Forward. | 73 |
Name | 79 |Description | 80 |
---|---|
WheelDown | 83 |Turn the wheel downward (toward you). | 84 |
WheelUp | 87 |Turn the wheel upward (away from you). | 88 |
WheelLeft WheelRight |
91 | Scroll to the left or right. 92 |These can be used as hotkeys with some (but not all) mice which have a second wheel or support tilting the wheel to either side. In some cases, software bundled with the mouse must instead be used to control this feature. Regardless of the particular mouse, Send and Click can be used to scroll horizontally in programs which support it. |
93 |
Note: The names of the letter and number keys are the same as that single letter or digit. For example: b is B and 5 is 5.
97 |Although any single character can be used as a key name, its meaning (scan code or virtual keycode) depends on the current keyboard layout. Additionally, some special characters may need to be escaped or enclosed in braces, depending on the context. The letters a-z or A-Z can be used to refer to the corresponding virtual keycodes (usually vk41-vk5A) even if they are not included in the current keyboard layout.
98 |Name | 102 |Description | 103 |
---|---|
CapsLock | 106 |CapsLock (caps lock key)
107 | Note: Windows IME may interfere with the detection and functionality of CapsLock; see CapsLock and IME for details. 108 | |
109 |
Space | 112 |Space (space bar) | 113 |
Tab | 116 |Tab (tabulator key) | 117 |
Enter | 120 |Enter | 121 |
Escape (or Esc) | 124 |Esc | 125 |
Backspace (or BS) | 128 |Backspace | 129 |
Name | 135 |Description | 136 |
---|---|
ScrollLock | 139 |ScrollLock (scroll lock key). While Ctrl is held down, ScrollLock produces the key code of CtrlBreak , but can be differentiated from Pause by scan code. |
140 |
Delete (or Del) | 143 |Del | 144 |
Insert (or Ins) | 147 |Ins | 148 |
Home | 151 |Home | 152 |
End | 155 |End | 156 |
PgUp | 159 |PgUp (page up key) | 160 |
PgDn | 163 |PgDn (page down key) | 164 |
Up | 167 |↑ (up arrow key) | 168 |
Down | 171 |↓ (down arrow key) | 172 |
Left | 175 |← (left arrow key) | 176 |
Right | 179 |→ (right arrow key) | 180 |
Due to system behavior, the following keys separated by a slash are identified differently depending on whether NumLock is ON or OFF. If NumLock is OFF but Shift is pressed, the system temporarily releases Shift and acts as though NumLock is ON.
184 |Name | 187 |Description | 188 |
---|---|
Numpad0 / NumpadIns | 0 / Ins | 191 |
Numpad1 / NumpadEnd | 1 / End | 194 |
Numpad2 / NumpadDown | 2 / ↓ | 197 |
Numpad3 / NumpadPgDn | 3 / PgDn | 200 |
Numpad4 / NumpadLeft | 4 / ← | 203 |
Numpad5 / NumpadClear | 5 / typically does nothing | 206 |
Numpad6 / NumpadRight | 6 / → | 209 |
Numpad7 / NumpadHome | 7 / Home | 212 |
Numpad8 / NumpadUp | 8 / ↑ | 215 |
Numpad9 / NumpadPgUp | 9 / PgUp | 218 |
NumpadDot / NumpadDel | . / Del | 221 |
NumLock | 224 |NumLock (number lock key). While Ctrl is held down, NumLock produces the key code of Pause , so use ^Pause in hotkeys instead of ^NumLock . |
225 |
NumpadDiv | 228 |/ (division) | 229 |
NumpadMult | 232 |* (multiplication) | 233 |
NumpadAdd | 236 |+ (addition) | 237 |
NumpadSub | 240 |- (subtraction) | 241 |
NumpadEnter | 244 |Enter | 245 |
Name | 251 |Description | 252 |
---|---|
F1 - F24 | 255 |The 12 or more function keys at the top of most keyboards. | 256 |
Name | 262 |Description | 263 |
---|---|
LWin | 266 |Left Win. Corresponds to the <# hotkey prefix. |
267 |
RWin | 270 |
271 | Right Win. Corresponds to the Note: Unlike Ctrl/Alt/Shift, there is no generic/neutral "Win" key because the OS does not support it. However, hotkeys with the |
274 |
Control (or Ctrl) | 277 |Ctrl. As a hotkey (Control:: ) it fires upon release unless it has the tilde prefix. Corresponds to the ^ hotkey prefix. |
278 |
Alt | 281 |Alt. As a hotkey (Alt:: ) it fires upon release unless it has the tilde prefix. Corresponds to the ! hotkey prefix. |
282 |
Shift | 285 |Shift. As a hotkey (Shift:: ) it fires upon release unless it has the tilde prefix. Corresponds to the + hotkey prefix. |
286 |
LControl (or LCtrl) | 289 |Left Ctrl. Corresponds to the <^ hotkey prefix. |
290 |
RControl (or RCtrl) | 293 |Right Ctrl. Corresponds to the >^ hotkey prefix. |
294 |
LShift | 297 |Left Shift. Corresponds to the <+ hotkey prefix. |
298 |
RShift | 301 |Right Shift. Corresponds to the >+ hotkey prefix. |
302 |
LAlt | 305 |Left Alt. Corresponds to the <! hotkey prefix. |
306 |
RAlt | 309 |
310 | Right Alt. Corresponds to the Note: If your keyboard layout has AltGr instead of RAlt, you can probably use it as a hotkey prefix via |
313 |
The function assigned to each of the keys listed below can be overridden by modifying the Windows registry. This table shows the default function of each key on most versions of Windows.
317 |Name | 320 |Description | 321 |
---|---|
Browser_Back | 324 |Back | 325 |
Browser_Forward | 328 |Forward | 329 |
Browser_Refresh | 332 |Refresh | 333 |
Browser_Stop | 336 |Stop | 337 |
Browser_Search | 340 |Search | 341 |
Browser_Favorites | 344 |Favorites | 345 |
Browser_Home | 348 |Homepage | 349 |
Volume_Mute | 352 |Mute the volume | 353 |
Volume_Down | 356 |Lower the volume | 357 |
Volume_Up | 360 |Increase the volume | 361 |
Media_Next | 364 |Next Track | 365 |
Media_Prev | 368 |Previous Track | 369 |
Media_Stop | 372 |Stop | 373 |
Media_Play_Pause | 376 |Play/Pause | 377 |
Launch_Mail | 380 |Launch default e-mail program | 381 |
Launch_Media | 384 |Launch default media player | 385 |
Launch_App1 | 388 |Launch This PC (formerly My Computer or Computer) | 389 |
Launch_App2 | 392 |Launch Calculator | 393 |
Name | 399 |Description | 400 |
---|---|
AppsKey | 403 |Menu. This is the key that invokes the right-click context menu. | 404 |
PrintScreen | 407 |PrtSc (print screen key) | 408 |
CtrlBreak | 411 |Ctrl+Pause or Ctrl+ScrollLock | 412 |
Pause | 415 |Pause or Ctrl+NumLock. While Ctrl is held down, Pause produces the key code of CtrlBreak and NumLock produces Pause , so use ^CtrlBreak in hotkeys instead of ^Pause . |
416 |
Help | 419 |Help. This probably doesn't exist on most keyboards. It's usually not the same as F1. | 420 |
Sleep | 423 |Sleep. Note that the sleep key on some keyboards might not work with this. | 424 |
SCnnn | 427 |Specify for nnn the scan code of a key. Recognizes unusual keys not mentioned above. See Special Keys for details. | 428 |
VKnn | 431 |Specify for nn the hexadecimal virtual key code of a key. This rarely-used method also prevents certain types of hotkeys from requiring the keyboard hook. For example, the following hotkey does not use the keyboard hook, but as a side-effect it is triggered by pressing either Home or NumpadHome: 432 |^VK24::MsgBox "You pressed Home or NumpadHome while holding down Control." 433 |434 | Known limitation: VK hotkeys that are forced to use the keyboard hook, such as Warning: Only Send, GetKeyName, GetKeyVK, GetKeySC and A_MenuMaskKey support combining VKnn and SCnnn. If combined in any other case (or if any other invalid suffix is present), the key is not recognized. For example, |
437 |
Note: For historical reasons, the following button and control names begin with Joy
, which stands for joystick. However, they usually also work for other game controllers such as gamepads or steering wheels.
Joy1 through Joy32: The buttons of the controller. To help determine the button numbers for your controller, use this test script. Note that hotkey prefix symbols such as ^ (control) and + (shift) are not supported (though GetKeyState can be used as a substitute). Also note that the pressing of controller buttons always "passes through" to the active window if that window is designed to detect the pressing of controller buttons.
442 |Although the following control names cannot be used as hotkeys, they can be used with GetKeyState:
443 |For example, when using Xbox Wireless/360 controllers, JoyX/JoyY is the left stick, JoyR/JoyU the right stick, JoyZ the left and right triggers, and JoyPOV the directional pad (D-pad).
454 |Multiple controllers: If the computer has more than one controller and you want to use one beyond the first, include the controller number (max 16) in front of the control name. For example, 2joy1 is the second controller's first button.
455 |Note: If you have trouble getting a script to recognize your controller, specify a controller number other than 1 even though only a single controller is present. It is unclear how this situation arises or whether it is normal, but experimenting with the controller number in the controller test script can help determine if this applies to your system.
456 |See Also:
457 |Respond to signals from hand-held remote controls via the WinLIRC client script.
464 |If your keyboard or mouse has a key not listed above, you might still be able to make it a hotkey by using the following steps:
466 |475 | SC159::MsgBox ThisHotkey " was pressed." ; Replace 159 with your key's value. 476 |Also see ThisHotkey.
Reverse direction: To remap some other key to become a "mystery key", follow this example:
479 |; Replace 159 with the value discovered above. Replace FF (if needed) with the 480 | ; key's virtual key, which can be discovered in the first column of the Key History screen. 481 | #c::Send "{vkFFsc159}" ; See Send {vkXXscYYY} for more details.482 |
Alternate solutions: If your key or mouse button is not detectable by the Key History screen, one of the following might help:
483 |Reconfigure the software that came with your mouse or keyboard (sometimes accessible in the Control Panel or Start Menu) to have the "mystery key" send some other keystroke. Such a keystroke can then be defined as a hotkey in a script. For example, if you configure a mystery key to send Ctrl+F1, you can then indirectly make that key as a hotkey by using ^F1::
in a script.
Try AHKHID from the archived forum. You can also try searching the forum for a keywords like RawInput*
, USB HID
or AHKHID
.
The following is a last resort and generally should be attempted only in desperation. This is because the chance of success is low and it may cause unwanted side-effects that are difficult to undo:
492 | Disable or remove any extra software that came with your keyboard or mouse or change its driver to a more standard one such as the one built into the OS. This assumes there is such a driver for your particular keyboard or mouse and that you can live without the features provided by its custom driver and software.
Some configurations of Windows IME (such as Japanese input with English keyboard) use CapsLock to toggle between modes. In such cases, CapsLock is suppressed by the IME and cannot be detected by AutoHotkey. However, the Alt+CapsLock, Ctrl+CapsLock and Shift+CapsLock shortcuts can be disabled with a workaround. Specifically, send a key-up to modify the state of the IME, but prevent any other effects by signalling the keyboard hook to suppress the event. The following function can be used for this purpose:
498 |499 | ; The keyboard hook must be installed. 500 | InstallKeybdHook 501 | SendSuppressedKeyUp(key) { 502 | DllCall("keybd_event" 503 | , "char", GetKeyVK(key) 504 | , "char", GetKeySC(key) 505 | , "uint", KEYEVENTF_KEYUP := 0x2 506 | , "uptr", KEY_BLOCK_THIS := 0xFFC3D450) 507 | } 508 |509 |
After copying the function into a script or saving it as SendSuppressedKeyUp.ahk in a Lib folder and adding #Include <SendSuppressedKeyUp>
to the script, it can be used as follows:
511 | ; Disable Alt+key shortcuts for the IME. 512 | ~LAlt::SendSuppressedKeyUp "LAlt" 513 | 514 | ; Test hotkey: 515 | !CapsLock::MsgBox A_ThisHotkey 516 | 517 | ; Remap CapsLock to LCtrl in a way compatible with IME. 518 | *CapsLock:: 519 | { 520 | Send "{Blind}{LCtrl DownR}" 521 | SendSuppressedKeyUp "LCtrl" 522 | } 523 | *CapsLock up:: 524 | { 525 | Send "{Blind}{LCtrl Up}" 526 | } 527 |528 | 529 | 530 | 531 | -------------------------------------------------------------------------------- /docs/Language.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |
An AutoHotkey script is basically a set of instructions for the program to follow, written in a custom language exclusive to AutoHotkey. This language bears some similarities to several other scripting languages, but also has its own unique strengths and pitfalls. This document describes the language and also tries to point out common pitfalls.
14 |See Concepts and Conventions for more general explanation of various concepts utilised by AutoHotkey.
15 | 16 |Names: Variable and function names are not case-sensitive (for example, CurrentDate
is the same as currentdate
). For details such as maximum length and usable characters, see Names.
No typed variables: Variables have no explicitly defined type; instead, a value of any type can be stored in any variable (excluding constants and built-in variables). Numbers may be automatically converted to strings (text) and vice versa, depending on the situation.
65 |Declarations are optional: Except where noted on the functions page, variables do not need to be declared. However, attempting to read a variable before it is given a value is considered an error.
66 |Spaces are mostly ignored: Indentation (leading space) is important for writing readable code, but is not required by the program and is generally ignored. Spaces and tabs are generally ignored at the end of a line and within an expression (except between quotes). However, spaces are significant in some cases, including:
67 |(
.Line breaks are meaningful: Line breaks generally act as a statement separator, terminating the previous function call or other statement. (A statement is simply the smallest standalone element of the language that expresses some action to be carried out.) The exception to this is line continuation (see below).
74 |Line continuation: Long lines can be divided up into a collection of smaller ones to improve readability and maintainability. This is achieved by preprocessing, so is not part of the language as such. There are three methods:
75 |(
and ends with )
(both symbols must appear at the beginning of a line, excluding whitespace).Comments are portions of text within the script which are ignored by the program. They are typically used to add explanation or disable parts of the code.
84 |Scripts can be commented by using a semicolon at the beginning of a line. For example:
85 |; This entire line is a comment.86 |
Comments may also be added at the end of a line, in which case the semicolon must have at least one space or tab to its left. For example:
87 |Run "Notepad" ; This is a comment on the same line as a function call.88 |
In addition, the /*
and */
symbols can be used to comment out an entire section, as in this example:
/* 90 | MsgBox "This line is commented out (disabled)." 91 | MsgBox "Common mistake:" */ " this does not end the comment." 92 | MsgBox "This line is commented out." 93 | */ 94 | MsgBox "This line is not commented out." 95 | /* This is also valid, but no other code can share the line. */ 96 | MsgBox "This line is not commented out." 97 |98 |
Excluding tabs and spaces, /*
must appear at the start of the line, while */
can appear only at the start or end of a line. It is also valid to omit */
, in which case the remainder of the file is commented out.
Since comments are filtered out when the script is read from file, they do not impact performance or memory utilization.
100 | 101 |Expressions are combinations of one or more values, variables, operators and function calls. For example, 10
, 1+1
and MyVar
are valid expressions. Usually, an expression takes one or more values as input, performs one or more operations, and produces a value as the result. The process of finding out the value of an expression is called evaluation. For example, the expression 1+1
evaluates to the number 2.
Simple expressions can be pieced together to form increasingly more complex expressions. For example, if Discount/100
converts a discount percentage to a fraction, 1 - Discount/100
calculates a fraction representing the remaining amount, and Price * (1 - Discount/100)
applies it to produce the net price.
Values are numbers, objects or strings. A literal value is one written physically in the script; one that you can see when you look at the code.
105 | 106 |For a more general explanation of strings, see Strings.
108 |A string, or string of characters, is just a text value. In an expression, literal text must be enclosed in single or double quotation marks to differentiate it from a variable name or some other expression. This is often referred to as a quoted literal string, or just quoted string. For example, "this is a quoted string"
and 'so is this'
.
To include an actual quote character inside a quoted string, use the `"
or `'
escape sequence or enclose the character in the opposite type of quote mark. For example: 'She said, "An apple a day."'
.
Quoted strings can contain other escape sequences such as `t
(tab), `n
(linefeed), and `r
(carriage return).
For a basic explanation and general details about variables, see Variables.
114 |Variables can be used in an expression simply by writing the variable's name. For example, A_ScreenWidth/2
. However, variables cannot be used inside a quoted string. Instead, variables and other values can be combined with text through a process called concatenation. There are two ways to concatenate values in an expression:
"The value is " MyVar
"The value is " . MyVar
Implicit concatenation is also known as auto-concat. In both cases, the spaces preceding the variable and dot are mandatory.
120 |The Format function can also be used for this purpose. For example:
121 |MsgBox Format("You are using AutoHotkey v{1} {2}-bit.", A_AhkVersion, A_PtrSize*8)122 |
To assign a value to a variable, use the :=
assignment operator, as in MyVar := "Some text"
.
Percent signs within an expression are used to create dynamic variable references, but these are rarely needed.
124 | 125 |A constant is simply an unchangeable value, given a symbolic name. AutoHotkey currently has the following constants:
127 |Name | Value | Type | Description |
---|---|---|---|
False | 0 | Integer | Boolean false, sometimes meaning "off", "no", etc. |
True | 1 | Integer | Boolean true, sometimes meaning "on", "yes", etc. |
Unlike the read-only built-in variables, these cannot be returned by a dynamic reference.
133 | 134 |Operators take the form of a symbol or group of symbols such as +
or :=
, or one of the words and
, or
, not
, is
, in
or contains
. They take one, two or three values as input and return a value as the result. A value or sub-expression used as input for an operator is called an operand.
-x
or not keyIsDown
.1+1
or 2 * 5
.condition ? valueIfTrue : valueIfFalse
.Some unary and binary operators share the same symbols, in which case the meaning of the operator depends on whether it is written before, after or in between two values. For example, x-y
performs subtraction while -x
inverts the sign of x
(producing a positive value from a negative value and vice versa).
Operators of equal precedence such as multiply (*
) and divide (/
) are evaluated in left-to-right order unless otherwise specified in the operator table. By contrast, an operator of lower precedence such as add (+
) is evaluated after a higher one such as multiply (*
). For example, 3 + 2 * 2
is evaluated as 3 + (2 * 2)
. Parentheses may be used to override precedence as in this example: (3 + 2) * 2
For a general explanation of functions and related terminology, see Functions.
146 |Functions take a varying number of inputs, perform some action or calculation, and then return a result. The inputs of a function are called parameters or arguments. A function is called simply by writing the target function followed by parameters enclosed in parentheses. For example, GetKeyState("Shift")
returns (evaluates to) 1 if Shift is being held down or 0 otherwise.
Note: There must not be any space between the function and open parenthesis.
148 |For those new to programming, the requirement for parentheses may seem cryptic or verbose at first, but they are what allows a function call to be combined with other operations. For example, the expression GetKeyState("Shift", "P") and GetKeyState("Ctrl", "P")
returns 1 only if both keys are being physically held down.
Although a function call expression usually begins with a literal function name, the target of the call can be any expression which produces a function object. In the expression GetKeyState("Shift")
, GetKeyState is actually a variable reference, although it usually refers to a read-only variable containing a built-in function.
If the return value of the function is not needed and the function name is written at the start of the line (or in other contexts which allow a statement, such as following else
or a hotkey), the parentheses can be omitted. In this case, the remainder of the line is taken as the function's parameter list. For example:
result := MsgBox("This one requires parentheses.",, "OKCancel") 154 | MsgBox "This one doesn't. The result was " result "."155 |
Parentheses can also be omitted when calling a method in this same context, but only when the target object is either a variable or a directly named property, such as myVar.myMethod
or myVar.myProp.myMethod
.
As with function call expressions, the target of a function call statement does not have to be a predefined function; it can instead be a variable containing a function object.
157 |A function call statement can span multiple lines.
158 |Function call statements have the following limitations:
159 |Optional parameters can simply be left blank, but the delimiting comma is still required unless all subsequent parameters are also omitted. For example, the Run function can accept between one and four parameters. All of the following are valid:
168 |169 | Run "notepad.exe", "C:\" 170 | Run "notepad.exe",, "Min" 171 | Run("notepad.exe", , , ¬epadPID) 172 |173 |
Within a function call, array literal or object literal, the keyword unset
can be used to explicitly omit the parameter or value. An unset expression has one of the following effects:
[var?]
, the element is included in the array's length but is given no value.{x: y?}
, the property is not assigned.The unset
keyword can also be used in a function definition to indicate that a parameter is optional but has no default value. When the function executes, the local variable corresponding to that parameter will have no value if the parameter was omitted.
The maybe operator (var?) can be used to pass or omit a variable depending on whether it has a value. For example, Array(MyVar?)
is equivalent to Array(IsSet(MyVar) ? MyVar : unset)
.
There are other symbols used in expressions which don't quite fit into any of the categories defined above, or that affect the meaning of other parts of the expression, as described below. These all relate to objects in some way. Providing a full explanation of what each construct does would require introducing more concepts which are outside the scope of this section.
185 |Alpha.Beta
is often called member access. Alpha is an ordinary variable, and could be replaced with a function call or some other sub-expression which returns an object. When evaluated, the object is sent a request "give me the value of property Beta", "store this value in property Beta" or "call the method named Beta". In other words, Beta is a name which has meaning to the object; it is not a local or global variable.
Alpha.Beta()
is a method call, as described above. The parentheses can be omitted in specific cases; see Function Call Statements.
Alpha.Beta[Param]
is a specialised form of member access which includes additional parameters in the request. While Beta is a simple name, Param is an ordinary variable or sub-expression, or a list of sub-expressions separated by commas (the same as in a function's parameter list). Variadic calls are permitted.
Alpha.%vBeta%
, Alpha.%vBeta%[Param]
and Alpha.%vBeta%()
are also member access, but vBeta is a variable or sub-expression. This allows the name of the property or method to be determined while the script is running. Parentheses are required when calling a method this way.
Alpha[Index]
accesses the default property of Alpha
, giving Index
as a parameter. Both Alpha and Index are variables in this case, and could be replaced with virtually any sub-expression. This syntax is usually used to retrieve an element of an Array or Map.
[A, B, C]
creates an Array with the initial contents A, B and C (all variables in this case), where A is element 1.
{Prop1: Value1, Prop2: Value2}
creates an Object with properties literally named Prop1 and Prop2. A value can later be retrieved by using the member access syntax described above. To evaluate a property name as an expression, enclose it in percent signs. For example: {%NameVar%: ValueVar}
.
MyFunc(Params*)
is a variadic function call. The asterisk must immediately precede the closing parenthesis at the end of the function's parameter list. Params must be a variable or sub-expression which returns an Array or other enumerable object. Although it isn't valid to use Params*
just anywhere, it can be used in an array literal ([A, B, C, ArrayToAppend*]
) or property parameter list (Alpha.Beta[Params*]
or Alpha[Params*]
).
Not all expressions can be used alone on a line. For example, a line consisting of just 21*2
or "Some text"
wouldn't make any sense. An expression statement is an expression used on its own, typically for its side-effects. Most expressions with side-effects can be used this way, so it is generally not necessary to memorise the details of this section.
The following types of expressions can be used as statements:
197 |Assignments, as in x := y
, compound assignments such as x += y
, and increment/decrement operators such as ++x
and x--
.
Known limitation: For x++
and x--
, there currently cannot be a space between the variable name and operator.
Function calls such as MyFunc(Params)
. However, a standalone function call cannot be followed by an open brace {
(at the end of the line or on the next line), because it would be confused with a function declaration.
Method calls such as MyObj.MyMethod()
.
Member access using square brackets, such as MyObj[Index]
, which can have side-effects like a function call.
Ternary expressions such as x ? CallIfTrue() : CallIfFalse()
. However, it is safer to utilize the rule below; that is, always enclose the expression (or just the condition) in parentheses.
Known limitation: Due to ambiguity with function call statements, conditions beginning with a variable name and space (but also containing other operators) should be enclosed in parentheses. For example, (x + 1) ? y : z
and x+1 ? y : z
are expression statements but x + 1 ? y : z
is a function call statement.
Note: The condition cannot begin with !
or any other expression operator, as it would be interpreted as a continuation line.
Expressions starting with (
. However, there usually must be a matching )
on the same line, otherwise the line would be interpreted as the start of a continuation section.
Expressions starting with a double-deref, such as %varname% := 1
. This is primarily due to implementation complexity.
Expressions that start with any of those described above (but not those described below) are also allowed, for simplicity. For example, MyFunc()+1
is currently allowed, although the +1
has no effect and its result is discarded. Such expressions might become invalid in the future due to enhanced error-checking.
Function call statements are similar to expression statements, but are technically not pure expressions. For example, MsgBox "Hello, world!"
, myGui.Show
or x.y.z "my parameter"
.
For a general explanation of control flow, see Control Flow.
212 |Statements are grouped together into a block by enclosing them in braces {}
, as in C, JavaScript and similar languages, but usually the braces must appear at the start of a line. Control flow statements can be applied to an entire block or just a single statement.
The body of a control flow statement is always a single group of statements. A block counts as a single group of statements, as does a control flow statement and its body. The following related statements are also grouped with each other, along with their bodies: If
with Else
; Loop
/For
with Until
or Else
; Try
with Catch
and/or Else
and/or Finally
. In other words, when a group of these statements is used as a whole, it does not always need to be enclosed in braces (however, some coding styles always include the braces, for clarity).
Control flow statements which have a body and therefore must always be followed by a related statement or group of statements: If
, Else
, Loop
, While
, For
, Try
, Catch
and Finally
.
The following control flow statements exist:
216 |Control flow statements differ from function call statements in several ways:
240 |if(expression)
.There are several types of loop statements:
249 |Break exits (terminates) a loop, effectively jumping to the next line after the loop's body.
259 |Continue skips the rest of the current loop iteration and begins a new one.
260 |Until causes a loop to terminate when an expression evaluates to true. The expression is evaluated after each iteration.
261 |A label can be used to "name" a loop for Continue and Break. This allows the script to easily continue or break out of any number of nested loops without using Goto.
262 |The built-in variable A_Index contains the number of the current loop iteration. It contains 1 the first time the loop's body is executed. For the second time, it contains 2; and so on. If an inner loop is enclosed by an outer loop, the inner loop takes precedence. A_Index works inside all types of loops, but contains 0 outside of a loop.
263 |For some loop types, other built-in variables return information about the current loop item (registry key/value, file, substring or line of text). These variables have names beginning with A_Loop, such as A_LoopFileName and A_LoopReadLine. Their values always correspond to the most recently started (but not yet stopped) loop of the appropriate type. For example, A_LoopField returns the current substring in the innermost parsing loop, even if it is used inside a file or registry loop.
264 |t := "column 1`tcolumn 2`nvalue 1`tvalue 2" 265 | Loop Parse t, "`n" 266 | { 267 | rowtext := A_LoopField 268 | rownum := A_Index ; Save this for use in the second loop, below. 269 | Loop Parse rowtext, "`t" 270 | { 271 | MsgBox rownum ":" A_Index " = " A_LoopField 272 | } 273 | } 274 |275 |
Loop variables can also be used outside the body of a loop, such as in a function which is called from within a loop.
276 | 277 |As directives, labels, double-colon hotkey and hotstring tags, and declarations without assignments are processed when the script is loaded from file, they are not subject to control flow. In other words, they take effect unconditionally, before the script ever executes any control flow statements. Similarly, the #HotIf directive cannot affect control flow; it merely sets the criteria for any hotkeys and hotstrings specified in the code. A hotkey's criteria is evaluated each time it is pressed, not when the #HotIf directive is encountered in the code.
279 | 280 |After the script has been loaded, the auto-execute thread begins executing at the script's top line, and continues until instructed to stop, such as by Return, ExitApp or Exit. The physical end of the script also acts as Exit.
284 |Global code, or code in the global scope, is any executable code that is not inside a function or class definition. Any variable references there are said to be global, since they can be accessed by any function (with the proper declaration). Such code is often used to configure settings which apply to every newly launched thread, or to initialize global variables used by hotkeys and other functions.
285 |Code to be executed at startup (immediately when the script starts) is often placed at the top of the file. However, such code can be placed throughout the file, in between (but not inside) function and class definitions. This is because the body of each function or class definition is skipped whenever it is encountered during execution. In some cases, the entire purpose of the script may be carried out with global code.
286 |Related: Script Startup (the Auto-execute Thread)
287 | 288 |A subroutine (also sub or procedure) is a reusable block of code which can be executed on demand. A subroutine is created by defining a function (see below). These terms are generally interchangeable for AutoHotkey v2, where functions are the only type of subroutine.
290 | 291 |Related: Functions (all about defining functions)
293 |Aside from calling the many useful predefined functions, a script can define its own functions. These functions can generally be used two ways:
294 |There are multiple ways to define a function:
299 |SayHello() ; Define the SayHello function. 302 | { 303 | MsgBox "Hello!" 304 | } 305 | 306 | SayHello ; Call the SayHello function.307 |
#w::Run "wordpad" ; Press Win-W to run Wordpad. 310 | #n:: ; Press Win-N to run Notepad. 311 | { 312 | Run "notepad" 313 | }314 |
SetTimer () => MsgBox("Hello!"), -1000 ; Says hello after 1 second.317 |
SayHello() => MsgBox("Hello!")320 |
Variables in functions are local to that function by default, except in the following cases:
323 |&var
).A function can optionally accept parameters. Parameters are defined by listing them inside the parentheses. For example:
329 |MyFunction(FirstParameter, Second, &Third, Fourth:="") 330 | { 331 | ;... 332 | return "a value" 333 | } 334 |335 |
As with function calls, there must be no space between the function name and open-parenthesis.
336 |The line break between the close-parenthesis and open-brace is optional. There can be any amount of whitespace or comments between the two.
337 |The ByRef marker (&) indicates that the caller must pass a variable reference. Inside the function, any reference to the parameter will actually access the caller's variable. This is similar to omitting &
and explicitly dereferencing the parameter inside the function (e.g. %Third%
), but in this case the percent signs are omitted. If the parameter is optional and the caller omits it, the parameter acts as a normal local variable.
Optional parameters are specified by following the parameter name with :=
and a default value, which must be a literal quoted string, a number, true
, false
or unset
.
The function can return a value. If it does not, the default return value is an empty string.
340 |A function definition does not need to precede calls to that function.
341 |See Functions for much more detail.
342 | 343 |The #Include directive causes the script to behave as though the specified file's contents are present at this exact position. This is often used to organise code into separate files, or to make use of script libraries written by other users.
345 |An #Include file can contain global code to be executed during script startup, but as with code in the main script file, such code will be executed only if the auto-execute thread is not terminated (such as with an unconditional Return
) prior to the #Include directive. A warning is displayed by default if any code cannot be executed due to a prior Return
.
Unlike in C/C++, #Include does nothing if the file has already been included by a previous directive. To include the contents of the same file multiple times, use #IncludeAgain.
347 |To facilitate sharing scripts, #Include can search a few standard locations for a library script. For details, see Script Library Folders.
348 | 349 |A dynamic variable reference takes a text value and interprets it as the name of a variable.
353 |Note: A variable cannot be created by a dynamic reference, but existing variables can be assigned. This includes all variables which the script contains non-dynamic references to, even if they have not been assigned values.
354 |The most common form of dynamic variable reference is called a double reference or double-deref. Before performing a double reference, the name of the target variable is stored in a second variable. This second variable can then be used to assign a value to the target variable indirectly, using a double reference. For example:
355 |target := 42 356 | second := "target" 357 | MsgBox second ; Normal (single) variable reference => target 358 | MsgBox %second% ; Double-deref => 42 359 |360 |
Currently, second
must always contain a variable name in the second case; arbitrary expressions are not supported.
A dynamic variable reference can also take one or more pieces of literal text and the content of one or more variables, and join them together to form a single variable name. This is done simply by writing the pieces of the name and percent-enclosed variables in sequence, without any spaces. For example, MyArray%A_Index%
or MyGrid%X%_%Y%
. This is used to access pseudo-arrays, described below.
These techniques can also be applied to properties and methods of objects. For example:
363 |clr := {} 364 | for n, component in ["red", "green", "blue"] 365 | clr.%component% := Random(0, 255) 366 | MsgBox clr.red "," clr.green "," clr.blue367 | 368 |
A pseudo-array is actually just a bunch of discrete variables, but with a naming pattern which allows them to be used like elements of an array. For example:
370 |371 | MyArray1 := "A" 372 | MyArray2 := "B" 373 | MyArray3 := "C" 374 | Loop 3 375 | MsgBox MyArray%A_Index% ; Shows A, then B, then C. 376 |377 |
The "index" used to form the final variable name does not have to be numeric; it could instead be a letter or keyword.
378 |For these reasons, it is generally recommended to use an Array or Map instead of a pseudo-array:
379 |A label identifies a line of code, and can be used as a Goto target or to specify a loop to break out of or continue. A label consist of a name followed by a colon:
389 |this_is_a_label:390 |
Aside from whitespace and comments, no other code can be written on the same line as a label. For more details, see Labels.
391 | 392 | 393 | -------------------------------------------------------------------------------- /docs/ObjList.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |An object combines a number of properties and methods.
20 |Related topics:
21 |IsObject can be used to determine if a value is an object:
28 |Result := IsObject(expression)29 | 30 |
See Built-in Classes for a list of standard object types. There are two fundamental types:
31 |Create an Array:
81 |MyArray := [Item1, Item2, ..., ItemN] 82 | MyArray := Array(Item1, Item2, ..., ItemN)83 |
Retrieve an item (or array element):
84 |Value := MyArray[Index]85 |
Change the value of an item (Index
must be between 1 and Length, or an equivalent reverse index):
MyArray[Index] := Value87 |
Insert one or more items at a given index using the InsertAt method:
88 |MyArray.InsertAt(Index, Value, Value2, ...)89 |
Append one or more items using the Push method:
90 |MyArray.Push(Value, Value2, ...)91 |
Remove an item using the RemoveAt method:
92 |RemovedValue := MyArray.RemoveAt(Index)93 |
Remove the last item using the Pop method:
94 |RemovedValue := MyArray.Pop()95 |
Length returns the number of items in the array. Looping through an array's contents can be done either by index or with a For-loop. For example:
96 |MyArray := ["one", "two", "three"] 97 | 98 | ; Iterate from 1 to the end of the array: 99 | Loop MyArray.Length 100 | MsgBox MyArray[A_Index] 101 | 102 | ; Enumerate the array's contents: 103 | For index, value in MyArray 104 | MsgBox "Item " index " is '" value "'" 105 | 106 | ; Same thing again: 107 | For value in MyArray 108 | MsgBox "Item " A_Index " is '" value "'" 109 |110 | 111 |
A Map or associative array is an object which contains a collection of unique keys and a collection of values, where each key is associated with one value. Keys can be strings, integers or objects, while values can be of any type. An associative array can be created as follows:
113 |MyMap := Map("KeyA", ValueA, "KeyB", ValueB, ..., "KeyZ", ValueZ)114 |
Retrieve an item, where Key
is a variable or expression:
Value := MyMap[Key]116 |
Assign an item:
117 |MyMap[Key] := Value118 |
Remove an item using the Delete method:
119 |RemovedValue := MyMap.Delete(Key)120 |
Enumerating items:
121 |MyMap := Map("ten", 10, "twenty", 20, "thirty", 30) 122 | For key, value in MyMap 123 | MsgBox key ' = ' value124 | 125 |
An object can have properties and items (such as array elements). Items are accessed using []
as shown in the previous sections. Properties are usually accessed by writing a dot followed by an identifier (just a name). Methods are properties which can be called.
Examples:
128 |Retrieve or set a property literally named Property:
129 |Value := MyObject.Property130 |
MyObject.Property := Value131 |
Retrieve or set a property where the name is determined by evaluating an expression or variable:
132 |Value := MyObject.%Expression%133 |
MyObject.%Expression% := Value134 |
Call a property/method literally named Method:
135 |ReturnValue := MyObject.Method(Parameters)136 |
Call a property/method where the name is determined by evaluating an expression or variable:
137 |ReturnValue := MyObject.%Expression%(Parameters)138 |
Sometimes parameters are accepted when retrieving or assigning properties:
139 |Value := MyObject.Property[Parameters] 140 | MyObject.Property[Parameters] := Value141 |
An object may also support indexing: MyArray[Index]
actually invokes the __Item property of MyArray
, passing Index
as a parameter.
An object literal can be used within an expression to create an improvised object. An object literal consists of a pair of braces ({}
) enclosing a list of comma-delimited name-value pairs. Each pair consists of a literal (unquoted) property name and a value (sub-expression) separated by a colon (:
). For example:
Coord := {X: 13, Y: 240}146 |
This is equivalent:
147 |Coord := Object() 148 | Coord.X := 13 149 | Coord.Y := 240150 |
Each name-value pair causes a value property to be defined, with the exception that Base can be set (with the same restrictions as a normal assignment).
151 |Name substitution allows a property name to be determined by evaluating an expression or variable. For example:
152 |parts := StrSplit("key = value", "=", " ") 153 | pair := {%parts[1]%: parts[2]} 154 | MsgBox pair.key155 | 156 |
Scripts do not free objects explicitly. When the last reference to an object is released, the object is freed automatically. A reference stored in a variable is released automatically when that variable is assigned some other value. For example:
158 |obj := {} ; Creates an object. 159 | obj := "" ; Releases the last reference, and therefore frees the object.160 |
Similarly, a reference stored in a property or array element is released when that property or array element is assigned some other value or removed from the object.
161 |arr := [{}] ; Creates an array containing an object. 162 | arr[1] := {} ; Creates a second object, implicitly freeing the first object. 163 | arr.RemoveAt(1) ; Removes and frees the second object.164 |
Because all references to an object must be released before the object can be freed, objects containing circular references aren't freed automatically. For instance, if x.child
refers to y
and y.parent
refers to x
, clearing x
and y
is not sufficient since the parent object still contains a reference to the child and vice versa. To resolve this situation, remove the circular reference.
166 | x := {}, y := {} ; Create two objects. 167 | x.child := y, y.parent := x ; Create a circular reference. 168 | 169 | y.parent := "" ; The circular reference must be removed before the objects can be freed. 170 | x := "", y := "" ; Without the above line, this would not free the objects. 171 |172 |
For more advanced usage and details, see Reference Counting.
173 | 174 |Although "multi-dimensional" arrays are not supported, a script can combine multiple arrays or maps. For example:
178 |179 | grid := [[1,2,3], 180 | [4,5,6], 181 | [7,8,9]] 182 | MsgBox grid[1][3] ; 3 183 | MsgBox grid[3][2] ; 8 184 |185 |
A custom object can implement multi-dimensional support by defining an __Item property. For example:
186 |187 | class Array2D extends Array { 188 | __new(x, y) { 189 | this.Length := x * y 190 | this.Width := x 191 | this.Height := y 192 | } 193 | __Item[x, y] { 194 | get => super.Has(this.i[x, y]) ? super[this.i[x, y]] : false 195 | set => super[this.i[x, y]] := value 196 | } 197 | i[x, y] => this.Width * (y-1) + x 198 | } 199 | 200 | grid := Array2D(4, 3) 201 | grid[4, 1] := "#" 202 | grid[3, 2] := "#" 203 | grid[2, 2] := "#" 204 | grid[1, 3] := "#" 205 | gridtext := "" 206 | Loop grid.Height { 207 | y := A_Index 208 | Loop grid.Width { 209 | x := A_Index 210 | gridtext .= grid[x, y] || "-" 211 | } 212 | gridtext .= "`n" 213 | } 214 | MsgBox gridtext 215 |216 |
A real script should perform error-checking and override other methods, such as __Enum to support enumeration.
217 | 218 |There are two general ways to create custom objects:
220 |Meta-functions can be used to further control how an object behaves.
225 |Note: Within this section, an object is any instance of the Object class. This section does not apply to COM objects.
226 | 227 |Properties and methods (callable properties) can generally be added to new objects at any time. For example, an object with one property and one method might be constructed like this:
229 |; Create an object. 230 | thing := {} 231 | ; Store a value. 232 | thing.foo := "bar" 233 | ; Define a method. 234 | thing.test := thing_test 235 | ; Call the method. 236 | thing.test() 237 | 238 | thing_test(this) { 239 | MsgBox this.foo 240 | }241 |
You could similarly create the above object with thing := {foo: "bar"}
. When using the {property:value} notation, quote marks must not be used for properties.
When thing.test()
is called, thing is automatically inserted at the beginning of the parameter list. By convention, the function is named by combining the "type" of object and the method name, but this is not a requirement.
In the example above, test could be assigned some other function or value after it is defined, in which case the original function is lost and cannot be called via this property. An alternative is to define a read-only method, as shown below:
244 |thing.DefineProp('test', {call: thing_test})245 |
See also: DefineProp
246 | 247 |Objects are prototype-based. That is, any properties not defined in the object itself can instead be defined in the object's base. This is known as inheritance by delegation or differential inheritance, because an object can implement only the parts that make it different, while delegating the rest to its base.
249 |Although a base object is also generally known as a prototype, we use "a class's Prototype" to mean the object upon which every instance of the class is based, and "base" to mean the object upon which an instance is based.
250 |AutoHotkey's object design was influenced primarily by JavaScript and Lua, with a little C#. We use obj.base
in place of JavaScript's obj.__proto__
and cls.Prototype
in place of JavaScript's func.prototype
. (Class objects are used in place of constructor functions.)
An object's base is also used to identify its type or class. For example, x := []
creates an object based on Array.Prototype
, which means that the expressions x is Array
and x.HasBase(Array.Prototype)
are true, and type(x)
returns "Array". Each class's Prototype is based on the Prototype of its base class, so x.HasBase(Object.Prototype)
is also true.
Any instance of Object or a derived class can be a base object, but an object can only be assigned as the base of an object with the same native type. This is to ensure that built-in methods can always identify the native type of an object, and operate only on objects that have the correct binary structure.
254 |Base objects can be defined two different ways:
255 |A base object can be assigned to the base property of another object, but typically an object's base is set implicitly when it is created.
260 | 261 |Any object can be used as the base of any other object which has the same native type. The following example builds on the previous example under Ad Hoc (combine the two before running it):
263 |other := {} 264 | other.base := thing 265 | other.test()266 |
In this case, other inherits foo and test from thing. This inheritance is dynamic, so if thing.foo
is modified, the change will be reflected by other.foo
. If the script assigns to other.foo
, the value is stored in other and any further changes to thing.foo
will have no effect on other.foo
. When other.test()
is called, its this parameter contains a reference to other instead of thing.
In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods). 270 | Wikipedia271 |
In more general terms, a class is a set or category of things having some property or attribute in common. In AutoHotkey, a class
defines properties to be shared by instances of the class (and methods, which are callable properties). An instance is just an object which inherits properties from the class, and can typically also be identified as belonging to that class (such as with the expression instance is ClassName
). Instances are typically created by calling ClassName().
Since Objects are dynamic and prototype-based, each class consists of two parts:
273 |static
keyword.static
keyword, and all nested classes. These do not apply to a specific instance, and can be used by referring to the class itself by name.The following shows most of the elements of a class definition:
278 |class ClassName extends BaseClassName 279 | { 280 | InstanceVar := Expression 281 | 282 | static ClassVar := Expression 283 | 284 | class NestedClass 285 | { 286 | ... 287 | } 288 | 289 | Method() 290 | { 291 | ... 292 | } 293 | 294 | static Method() 295 | { 296 | ... 297 | } 298 | 299 | Property[Parameters] ; Use brackets only when parameters are present. 300 | { 301 | get { 302 | return value of property 303 | } 304 | set { 305 | Store or otherwise handle value 306 | } 307 | } 308 | 309 | ShortProperty 310 | { 311 | get => Expression which calculates property value 312 | set => Expression which stores or otherwise handles value 313 | } 314 | 315 | ShorterProperty => Expression which calculates property value 316 | } 317 |318 |
When the script is loaded, this constructs a Class object and stores it in a global constant (read-only variable) with the name ClassName. If extends BaseClassName
is present, BaseClassName must be the full name of another class. The full name of each class is stored in ClassName.Prototype.__Class
.
Because the class itself is accessed through a variable, the class name cannot be used to both reference the class and create a separate variable (such as to hold an instance of the class) in the same context. For example, box := Box()
will not work, because box
and Box
both resolve to the same thing. Attempting to reassign a top-level (not nested) class in this manner results in a load time error.
Within this documentation, the word "class" on its own usually means a class object constructed with the class
keyword.
Class definitions can contain variable declarations, method definitions and nested class definitions.
322 | 323 |An instance variable is one that each instance of the class has its own copy of. They are declared and behave like normal assignments, but the this.
prefix is omitted (only directly within the class body):
InstanceVar := Expression326 |
These declarations are evaluated each time a new instance of the class is created with ClassName(), after all base-class declarations are evaluated but before __New is called. This is achieved by automatically creating a method named __Init containing a call to super.__Init()
and inserting each declaration into it. Therefore, a single class definition must not contain both an __Init method and an instance variable declaration.
Expression can access other instance variables and methods via this
. Global variables may be read, but not assigned. An additional assignment (or use of the reference operator) within the expression will generally create a variable local to the __Init method. For example, x := y := 1
would set this.x
and a local variable y
(which would be freed once all initializers have been evaluated).
To access an instance variable (even within a method), always specify the target object; for example, this.InstanceVar
.
Declarations like x.y := z
are also supported, provided that x
was previously defined in this class. For example, x := {}, x.y := 42
declares x
and also initializes this.x.y
.
Static/class variables belong to the class itself, but their values can be inherited by subclasses. They are declared like instance variables, but using the static keyword:
333 |static ClassVar := Expression334 |
These declarations are evaluated only once, when the class is initialized. A static method named __Init is automatically defined for this purpose.
335 |Each declaration acts as a normal property assignment, with the class object as the target. Expression has the same interpretation as for instance variables, except that this
refers to the class itself.
To assign to a class variable anywhere else, always specify the class object; for example, ClassName.ClassVar := Value
. If a subclass does not own a property by that name, Subclass.ClassVar
can also be used to retrieve the value; so if the value is a reference to an object, subclasses will share that object by default. However, Subclass.ClassVar := y
would store the value in Subclass, not in ClassName.
Declarations like static x.y := z
are also supported, provided that x
was previously defined in this class. For example, static x := {}, x.y := 42
declares x
and also initializes ClassName.x.y
. Because Prototype is implicitly defined in each class, static Prototype.sharedValue := 1
can be used to set values which are dynamically inherited by all instances of the class (until shadowed by a property on the instance itself).
Nested class definitions allow a class object to be associated with a static/class variable of the outer class instead of a separate global variable. In the example above, class NestedClass
constructs a Class object and stores it in ClassName.NestedClass
. Subclasses could inherit NestedClass or override it with their own nested class (in which case WhichClass.NestedClass()
could be used to instantiate whichever class is appropriate).
342 | class NestedClass 343 | { 344 | ... 345 | } 346 |347 |
Nesting a class does not imply any particular relationship to the outer class. The nested class is not instantiated automatically, nor do instances of the nested class have any connection with an instance of the outer class, unless the script explicitly makes that connection.
348 |Each nested class definition produces a dynamic property with get and call accessor functions instead of a simple value property. This is to support the following behaviour (where class X contains the nested class Y):
349 |X.Y()
does not pass X to X.Y.Call
and ultimately __New
, which would otherwise happen because this is the normal behaviour for function objects called as methods (which is how the nested class is being used here).X.Y := 1
is an error by default (the property is read-only).Method definitions look identical to function definitions. Each method definition creates a Func with a hidden first parameter named this
, and defines a property which is used to call the method or retrieve its function object.
There are two types of methods:
358 |this
refers to an instance of the class.static
. These are attached to the class object itself, but are also inherited by subclasses, so this
refers to either the class itself or a subclass.The method definition below creates a property of the same type as target.DefineProp('Method', {call: funcObj})
. By default, target.Method
returns funcObj and attempting to assign to target.Method
throws an error. These defaults can be overridden by defining a property or calling DefineProp.
364 | Method() 365 | { 366 | ... 367 | } 368 |369 | 370 |
Fat arrow syntax can be used to define a single-line method which returns an expression:
371 |Method() => Expression372 | 373 |
Inside a method or a property getter/setter, the keyword super
can be used in place of this
to access the superclass versions of methods or properties which are overridden in a derived class. For example, super.Method()
in the class defined above would typically call the version of Method which was defined within BaseClassName. Note:
super.Method()
always invokes the base of the class or prototype object associated with the current method's original definition, even if this
is derived from a subclass of that class or some other class entirely.super.Method()
implicitly passes this
as the first (hidden) parameter.super.Method()
is mostly equivalent to (ClassName.Prototype.base.Method)(this)
(but without Prototype when Method is static). However, ClassName.Prototype
is resolved at load time.The keyword super
must be followed by one of the following symbols: .[(
super()
is equivalent to super.call()
.
A property definition creates a dynamic property, which calls a method instead of simply storing or returning a value.
386 |Property[Parameters] 387 | { 388 | get { 389 | return property value 390 | } 391 | set { 392 | Store or otherwise handle value 393 | } 394 | } 395 |396 |
Property is simply the name of the property, which will be used to invoke it. For example, obj.Property
would call get while obj.Property := value
would call set. Within get or set, this
refers to the object being invoked. Within set, value
contains the value being assigned.
Parameters can be defined by enclosing them in square brackets to the right of the property name, and are passed the same way - but they should be omitted when parameters are not present (see below). Aside from using square brackets, parameters of properties are defined the same way as parameters of methods - optional, ByRef and variadic parameters are supported.
398 |If a property is invoked with parameters but has none defined, parameters are automatically forwarded to the __Item property of the object returned by get. For example, this.Property[x]
would have the same effect as (this.Property)[x]
or y := this.Property, y[x]
. Empty brackets (this.Property[]
) always cause the __Item property of Property's value to be invoked, but a variadic call such as this.Property[args*]
has this effect only if the number of parameters is non-zero.
Static properties can be defined by preceding the property name with the separate keyword static
. In that case, this
refers to the class itself or a subclass.
The return value of set is ignored. For example, val := obj.Property := 42
always assigns val := 42
regardless of what the property does, unless it throws an exception or exits the thread.
Each class can define one or both halves of a property. If a class overrides a property, it can use super.Property
to access the property defined by its base class. If Get or Set is not defined, it can be inherited from a base object. If Get is undefined, the property can return a value inherited from a base. If Set is undefined in this and all base objects (or is obscured by an inherited value property), attempting to set the property causes an exception to be thrown.
A property definition with both get and set actually creates two separate functions, which do not share local or static variables or nested functions. As with methods, each function has a hidden parameter named this
, and set has a second hidden parameter named value
. Any explicitly defined parameters come after those.
While a property definition defines the get and set accessor functions for a property in the same way as DefineProp, a method definition defines the call accessor function. Any class may contain a property definition and a method definition with the same name. If a property without a call accessor function (a method) is called, get is invoked with no parameters and the result is then called as a method.
404 | 405 |Fat arrow syntax can be used to define a property getter or setter which returns an expression:
407 |ShortProperty[Parameters] 408 | { 409 | get => Expression which calculates property value 410 | set => Expression which stores or otherwise handles value 411 | }412 |
When defining only a getter, the braces and get
can be omitted:
ShorterProperty[Parameters] => Expression which calculates property value414 |
In both cases, the square brackets must be omitted unless parameters are defined.
415 | 416 |__Enum(NumberOfVars)418 |
The __Enum method is called when the object is passed to a for-loop. This method should return an enumerator which will return items contained by the object, such as array elements. If left undefined, the object cannot be passed directly to a for-loop unless it has an enumerator-compatible Call method.
419 |NumberOfVars contains the number of variables passed to the for-loop. If NumberOfVars is 2, the enumerator is expected to assign the key or index of an item to the first parameter and the value to the second parameter. Each key or index should be accepted as a parameter of the __Item property. This enables DBGp-based debuggers to get or set a specific item after listing them by invoking the enumerator.
420 | 421 |The __Item property is invoked when the indexing operator (array syntax) is used with the object. In the following example, the property is declared as static so that the indexing operator can be used on the Env class itself. For another example, see Array2D.
423 |class Env { 424 | static __Item[name] { 425 | get => EnvGet(name) 426 | set => EnvSet(name, value) 427 | } 428 | } 429 | 430 | Env["PATH"] .= ";" A_ScriptDir ; Only affects this script and child processes. 431 | MsgBox Env["PATH"]432 |
__Item
is effectively a default property name (if such a property has been defined):
object[params]
is equivalent to object.__Item[params]
when there are parameters.object[]
is equivalent to object.__Item
.For example:
438 |439 | obj := {} 440 | obj[] := Map() ; Equivalent to obj.__Item := Map() 441 | obj["base"] := 10 442 | MsgBox obj.base = Object.prototype ; True 443 | MsgBox obj["base"] ; 10 444 |445 |
Note: When an explicit property name is combined with empty brackets, as in obj.prop[]
, it is handled as two separate operations: first retrieve obj.prop
, then invoke the default property of the result. This is part of the language syntax, so is not dependent on the object.
Whenever an object is created by the default implementation of ClassName(), the new object's __New
method is called in order to allow custom initialization. Any parameters passed to ClassName()
are forwarded to __New
, so can affect the object's initial content or how it is constructed. When an object is destroyed, __Delete
is called. For example:
m1 := GMem(0, 10) 450 | m2 := {base: GMem.Prototype}, m2.__New(0, 30) 451 | 452 | ; Note: For general memory allocations, use Buffer() instead. 453 | class GMem 454 | { 455 | __New(aFlags, aSize) 456 | { 457 | this.ptr := DllCall("GlobalAlloc", "UInt", aFlags, "Ptr", aSize, "Ptr") 458 | if !this.ptr 459 | throw MemoryError() 460 | MsgBox "New GMem of " aSize " bytes at address " this.ptr "." 461 | } 462 | 463 | __Delete() 464 | { 465 | MsgBox "Delete GMem at address " this.ptr "." 466 | DllCall("GlobalFree", "Ptr", this.ptr) 467 | } 468 | }469 |
__Delete is not called for any object which owns a property named "__Class". Prototype objects have this property by default.
470 |If an exception or runtime error is thrown while __Delete is executing and is not handled within __Delete, it acts as though __Delete was called from a new thread. That is, an error dialog is displayed and __Delete returns, but the thread does not exit (unless it was already exiting).
471 |If the script is directly terminated by any means, including the tray menu or ExitApp, any functions which have yet to return do not get the chance to do so. Therefore, any objects referenced by local variables of those functions are not released, so __Delete is not called. Temporary references on the expression evaluation stack are also not released under such circumstances.
472 |When the script exits, objects contained by global and static variables are released automatically in an arbitrary, implementation-defined order. When __Delete is called during this process, some global or static variables may have already been released, but any references contained by the object itself are still valid. It is therefore best for __Delete to be entirely self-contained, and not rely on any global or static variables.
473 | 474 |Each class is initialized automatically when a reference to the class is evaluated for the first time. For example, if MyClass has not yet been initialized, MyClass.MyProp
would cause the class to be initialized before the property is retrieved. Initialization consists of calling two static methods: __Init and __New.
static __Init
is defined automatically for every class, and always begins with a reference to the base class if one was specified, to ensure it is initialized. Static/class variables and nested classes are initialized in the order that they were defined, except when a nested class is referenced during initialization of a previous variable or class.
If the class defines or inherits a static __New
method, it is called immediately after __Init. It is important to note that __New may be called once for the class in which it is defined and once for each subclass which does not define its own (or which calls super.__New()
). This can be used to perform common initialization tasks for each subclass, or modify subclasses in some way before they are used.
If static __New
is not intended to act on derived classes, that can be avoided by checking the value of this
. In some cases it may be sufficient for the method to delete itself, such as with this.DeleteProp('__New')
; however, the first execution of __New might be for a subclass if one is nested in the base class or referenced during initialization of a static/class variable.
A class definition also has the effect of referencing the class. In other words, when execution reaches a class definition during script startup, __Init and __New are called automatically, unless the class was already referenced by the script. However, if execution is prevented from reaching the class definition, such as by return
or an infinite loop, the class is initialized only if it is referenced.
Once automatic initialization begins, it will not occur again for the same class. This is generally not a problem unless multiple classes refer to each other. For example, consider the two classes below. When A
is initialized first, evaluating B.SharedArray
(A1) causes B
to be initialized before retrieving and returning the value, but A.SharedValue
(A3) is undefined and does not cause initialization of A
because it is already in progress. In other words, if A
is accessed or initialized first, the order is A1 to A3; otherwise it is B1 to B4:
MsgBox A.SharedArray.Length 482 | MsgBox B.SharedValue 483 | 484 | class A { 485 | static SharedArray := B.SharedArray ; A1 ; B3 486 | static SharedValue := 42 ; B4 487 | } 488 | 489 | class B { 490 | static SharedArray := StrSplit("XYZ") ; A2 ; B1 491 | static SharedValue := A.SharedValue ; A3 (Error) ; B2 492 | }493 | 494 |
496 | class ClassName { 497 | __Get(Name, Params) 498 | __Set(Name, Params, Value) 499 | __Call(Name, Params) 500 | } 501 |502 |
The name of the property or method.
An Array of parameters. This includes only the parameters between ()
or []
, so may be empty. The meta-function is expected to handle cases such as x.y[z]
where x.y
is undefined.
The value being assigned.
Meta-functions define what happens when an undefined property or method is invoked. For example, if obj.unk
has not been assigned a value, it invokes the __Get meta-function. Similarly, obj.unk := value
invokes __Set and obj.unk()
invokes __Call.
Properties and methods can be defined in the object itself or any of its base objects. In general, for a meta-function to be called for every property, one must avoid defining any properties. Built-in properties such as Base can be overridden with a property definition or DefineProp.
512 |If a meta-function is defined, it must perform whatever default action is required. For example, the following might be expected:
513 |Any callable object can be used as a meta-function by assigning it to the relevant property.
520 |Meta-functions are not called in the following cases:
521 |x[y]
: Using square brackets without a property name only invokes the __Item property.x()
: Calling the object itself only invokes the Call
method. This includes internal calls made by built-in functions such as SetTimer and Hotkey.__Call
.Property syntax and DefineProp can be used to define properties which compute a value each time they are evaluated, but each property must be defined in advance. By contrast, __Get and __Set can be used to implement properties which are known only at the moment they are invoked.
529 |For example, a "proxy" object could be created which sends requests for properties over the network (or through some other channel). A remote server would send back a response containing the value of the property, and the proxy would return the value to its caller. Even if the name of each property was known in advance, it would not be logical to define each property individually in the proxy class since every property does the same thing (send a network request). Meta-functions receive the property name as a parameter, so are a good solution to this problem.
530 | 531 |Primitive values, such as strings and numbers, cannot have their own properties and methods. However, primitive values support the same kind of delegation as objects. That is, any property or method call on a primitive value is delegated to a predefined prototype object, which is also accessible via the Prototype property of the corresponding class. The following classes relate to primitive values:
533 |Although checking the Type string is generally faster, the type of a value can be tested by checking whether it has a given base. For example, n.HasBase(Number.Prototype)
or n is Number
is true if n is a pure Integer or Float, but not if n is a numeric string, since String does not derive from Number. By contrast, IsNumber(n)
is true if n is a number or a numeric string.
ObjGetBase and the Base property return one of the predefined prototype objects when appropriate.
544 |Note that x is Any
would ordinarily be true for any value within AutoHotkey's type hierarchy, but false for COM objects.
Properties and methods can be added for all values of a given type by modifying that type's prototype object. However, since a primitive value is not an Object and cannot have its own properties or methods, the primitive prototype objects do not derive from Object.Prototype
. In other words, methods such as DefineProp and HasOwnProp are not accessible by default. They can be called indirectly. For example:
549 | DefProp := {}.DefineProp 550 | DefProp( "".base, "Length", { get: StrLen } ) 551 | MsgBox A_AhkPath.length " == " StrLen(A_AhkPath) 552 |553 |
Although primitive values can inherit value properties from their prototype, an exception is thrown if the script attempts to set a value property on a primitive value. For example:
554 |"".base.test := 1 ; Don't try this at home. 555 | MsgBox "".test ; 1 556 | "".test := 2 ; Error: Property is read-only.557 |
Although __Set and property setters can be used, they are not useful since primitive values should be considered immutable.
558 | 559 |AutoHotkey uses a basic reference counting mechanism to automatically free the resources used by an object when it is no longer referenced by the script. Understanding this mechanism can be essential for properly managing the lifetime of an object, allowing it to be deleted when it is no longer needed, and not before then.
562 |An object's reference count is incremented whenever a reference is stored. When a reference is released, the count is used to determine whether that reference is the last one. If it is, the object is deleted; otherwise, the count is decremented. The following example shows how references are counted in some simple cases:
563 |564 | a := {Name: "Bob"} ; Bob's ref count is initially 1 565 | b := [a] ; Bob's ref count is incremented to 2 566 | a := "" ; Bob's ref count is decremented to 1 567 | c := b.Pop() ; Bob is transferred, ref count still 1 568 | c := "" ; Bob is deleted... 569 |570 |
Temporary references returned by functions, methods or operators within an expression are released after evaluation of that expression has completed or been aborted. In the following example, the new GMem object is freed only after MsgBox has returned:
571 |MsgBox DllCall("GlobalSize", "ptr", GMem(0, 20).ptr, "ptr") ; 20572 |
Note: In this example, .ptr
could have been omitted since the Ptr arg type permits objects with a Ptr
property. However, the pattern shown above will work even with other property names.
To run code when the last reference to an object is being released, implement the __Delete meta-function.
574 |Relying solely on reference counting sometimes creates catch-22 situations: an object is designed to free its resources when deleted, but would only be deleted if its resources are first freed. Specifically, this occurs when those resources are other objects or functions which retain a reference to the object, often indirectly.
576 |A circular reference or reference cycle is when an object directly or indirectly refers to itself. If each reference which is part of the cycle is included in the count, the object cannot be deleted until the cycle is manually broken. For example, the following creates a reference cycle:
577 |parent := {} ; parent: 1 (reference count) 578 | child := {parent: parent} ; parent: 2, child: 1 579 | parent.child := child ; parent: 2, child: 2580 |
If the variables parent
and child
are reassigned, the reference count for each object is decremented to 1. Both objects would be inaccessible to the script, but would not be deleted because the last references are not released.
A cycle is often less obvious than this, and can involve several objects. For example, ShowRefCycleGui demonstrates a cycle involving a Gui, MenuBar, Menu and closures. The use of a separate object to handle GUI events is also prone to cycles, if the handler object has a reference to the GUI.
582 |Non-cyclic references to an object can also cause issues. For instance, objects with a dependency on built-in functions like SetTimer or OnMessage generally cause the program to hold an indirect reference to the object. This would prevent the object from being deleted, which means that it cannot use __New and __Delete to manage the timer or message monitor.
583 |Below are several strategies for solving issues like those described above.
584 |Avoid cycles: If reference cycles are a problem, avoid creating them. For example, either parent.child
or child.parent
would not be set. This is often not practical, as related objects may need a way to refer to each other.
When defining event handlers for OnEvent (Gui), avoid capturing the source Gui in a closure or bound function and instead utilize the Gui or Gui.Control parameter. Likewise for Add (Menu) and the callback's Menu parameter, but of course, a menu item which needs to refer to a Gui cannot use this approach.
586 |In some cases, the other object can be retrieved by an indirect method which doesn't rely on a counted reference. For example, retain a HWND and use GuiFromHwnd(hwnd)
to retrieve a Gui object. Retaining a reference is not necessary to prevent deletion while the window is visible, as the Gui itself handles this.
Break cycles: If the script can avoid relying on reference counting and instead manage the lifetime of the object directly, it needs only break the cycle when the objects are to be deleted:
588 |child.parent := unset ; parent: 1, child: 2 589 | child := unset ; parent: 1, child: 1 590 | parent := unset ; both deleted591 |
Dispose: __Delete is called precisely when the last reference is released, so one might come to think of a simple assignment like myGui := ""
as a cleanup step which triggers deletion of the object. Sometimes this is done explicitly when the object is no longer needed, but it is neither reliable nor truly showing the intent of the code. An alternative pattern is to define a Dispose or Destroy method which frees the object's resources, and design it to do nothing if called a second time. It can then also be called from __Delete, as a safeguard.
An object following this pattern would still need to break any reference cycles when it is disposed, otherwise some memory would not be reclaimed, and __Delete would not be called for other objects referenced by the object.
593 |Cycles caused by a Gui object's event handlers, MenuBar or event sink object are automatically "broken" when Destroy is called, as it releases those objects. (This is demonstrated in the ShowRefCycleGui example.) However, this would not break cycles caused by new properties which the script has added, as Destroy does not delete them.
594 |Similar to the Dispose pattern, InputHook has a Stop method which must be called explicitly, so it does not rely on __Delete to signal when its operation should end. While operating, the program effectively holds a reference to the object which prevents it from being deleted, but this becomes a strength rather than a flaw: event callbacks can still be called and will receive the InputHook as a parameter. When the operation ends, the internal reference is released and the InputHook is deleted if the script has no reference to it.
595 |Pointers: Storing any number of pointer values does not affect the reference count of the object, since a pointer is just an integer. A pointer retrieved with ObjPtr can be used to produce a reference by passing it to ObjFromPtrAddRef. The AddRef version of the function must be used because the reference count will be decremented when the temporary reference is automatically released.
596 |For example, suppose that an object needs to update some properties each second. A timer holds a reference to the callback function, which has the object bound as a parameter. Normally this would prevent the object from being deleted before the timer is deleted. Storing a pointer instead of a reference allows the object to be deleted regardless of the timer, so it can be managed automatically by __New and __Delete.
597 |a := SomeClass() 598 | Sleep 5500 ; Let the timer run 5 times. 599 | a := "" 600 | Sleep 3500 ; Prevent exit temporarily to show that the timer has stopped. 601 | 602 | class SomeClass { 603 | __New() { 604 | ; The closure must be stored so that the timer can be deleted later. 605 | ; Synthesize a counted reference each time the method needs to be called. 606 | this.Timer := (p => ObjFromPtrAddRef(p).Update()).Bind(ObjPtr(this)) 607 | SetTimer this.Timer, 1000 608 | } 609 | __Delete() { 610 | SetTimer this.Timer, 0 611 | ; If this object is truly deleted, all properties will be 612 | ; deleted and the following __Delete method will be called. 613 | ; This is just for confirmation and wouldn't normally be used. 614 | this.Test := {__Delete: test => ToolTip("object deleted")} 615 | } 616 | ; This is just to demonstrate that the timer is running. 617 | ; Hypothetically, this class has some other purpose. 618 | count := 0 619 | Update() => ToolTip(++this.count) 620 | }621 |
A drawback of this approach is that the pointer is not directly usable as an object, and is not recognized as such by Type or the debugger. The script must be absolutely certain not to use the pointer after the object is deleted, as doing so is invalid and the result would be indeterminate.
622 |If the pointer-reference is needed in multiple places, encapsulating it might make sense. For instance, b := ObjFromPtrAddRef.Bind(ObjPtr(this))
would produce a BoundFunc which can be called (b()
) to retrieve the reference, while ((this, p) => ObjFromPtrAddRef(p)).Bind(ObjPtr(this))
can be used as a property getter (the property would return a reference).
Uncounted references: If the object's reference count accounts for a reference, we call it a counted reference, otherwise we call it an uncounted reference. The idea of the latter is to allow the script to store a reference which does not prevent the object from being deleted.
624 |Note: This is about how the object's reference count relates to a given reference as per the script's logic, and doesn't affect the nature of the reference itself. The program will still attempt to release the reference automatically at whatever time it would normally, so the terms weak reference and strong reference are unsuitable.
625 |A counted reference can be turned into an uncounted reference by simply decrementing the object's reference count. This must be reversed before the reference is released, which must occur before the object is deleted. Since the point of an uncounted reference is to allow the object to be deleted without first manually unsetting the reference, generally the count must be corrected within that object's own __Delete method.
626 |For example, __New and __Delete from the previous example can be replaced with the following.
627 |__New() { 628 | ; The BoundFunc must be stored so that the timer can be deleted later. 629 | SetTimer this.Timer := this.Update.Bind(this), 1000 630 | ; Decrement ref count to compensate for the AddRef done by Bind. 631 | ObjRelease(ObjPtr(this)) 632 | } 633 | __Delete() { 634 | ; Increment ref count so that the ref within the BoundFunc 635 | ; can be safely released. 636 | ObjPtrAddRef(this) 637 | ; Delete the timer to release its reference to the BoundFunc. 638 | SetTimer this.Timer, 0 639 | ; Release the BoundFunc. This may not happen automatically 640 | ; due to the reference cycle which exists now that the ref 641 | ; in the BoundFunc is counted again. 642 | this.Timer := unset 643 | ; If this object is truly deleted, all properties will be 644 | ; deleted and the following __Delete method will be called. 645 | ; This is just for confirmation and wouldn't normally be used. 646 | this.Test := {__Delete: test => ToolTip("object deleted")} 647 | }648 |
This can generally be applied regardless of where the uncounted reference is stored and what it is used for. The key points are:
649 |The reference count must be incremented and decremented as many times as there are references which are intended to be uncounted. This may not be practical if the script cannot accurately predict how many references will be stored by some function.
655 | 656 |As part of creating an object, some memory is allocated to hold the basic structure of the object. This structure is essentially the object itself, so we call its address a pointer to the object. An address is an integer value which corresponds to a location within the virtual memory of the current process, and is valid only until the object is deleted.
658 |In some rare cases it may be necessary to pass an object to external code via DllCall or store it in a binary data structure for later retrieval. An object's address can be retrieved via address := ObjPtr(myObject)
; however, this effectively makes two references to the object, but the program only knows about the one in myObject. If the last known reference to the object was released, the object would be deleted. Therefore, the script must inform the object that it has gained a reference. This can be done as follows (the two lines below are equivalent):
660 | ObjAddRef(address := ObjPtr(myObject)) 661 | address := ObjPtrAddRef(myObject) 662 |663 |
The script must also inform the object when it is finished with that reference:
664 |ObjRelease(address)665 |
Generally each new copy of an object's address should be treated as another reference to the object, so the script should call ObjAddRef when it gains a copy and ObjRelease immediately before losing one. For example, whenever an address is copied via something like x := address
, ObjAddRef should be called. Similarly, when the script is finished with x (or is about to overwrite x's value), it should call ObjRelease.
To convert an address to a proper reference, use the ObjFromPtr function:
667 |myObject := ObjFromPtr(address)668 |
ObjFromPtr assumes that address is a counted reference, and claims ownership of it. In other words, myObject := ""
would cause the reference originally represented by address to be released. After that, address must be considered invalid. To instead make a new reference, use one of the following:
670 | ObjAddRef(address), myObject := ObjFromPtr(address) 671 | myObject := ObjFromPtrAddRef(address) 672 |673 | 674 | 675 | 676 | -------------------------------------------------------------------------------- /docs/Program.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |
AutoHotkey doesn't do anything on its own; it needs a script to tell it what to do. A script is simply a plain text file with the .ahk
filename extension containing instructions for the program, like a configuration file, but much more powerful. A script can do as little as performing a single action and then exiting, but most scripts define a number of hotkeys, with each hotkey followed by one or more actions to take when the hotkey is pressed.
#z::Run "https://www.autohotkey.com" ; Win+Z 15 | 16 | ^!n:: ; Ctrl+Alt+N 17 | { 18 | if WinExist("Untitled - Notepad") 19 | WinActivate 20 | else 21 | Run "Notepad" 22 | }23 |
Tip: If your browser supports it, you can download any code block (such as the one above) as a script file by clicking the ↓ button which appears in the top-right of the code block when you hover your mouse over it.
24 | 25 |There are a few common ways to create a script file:
46 |.ahk
filename extension. On some systems you may need to enclose the name in quotes to ensure the editor does not add another extension (such as .txt).
48 | Be sure to save the file as UTF-8 with BOM if it will contain non-ASCII characters. For details, see the FAQ.
.ahk
extension if it is visible)..ahk
extension) and click Create or Edit. The template used to create the script and the location it will be saved can be configured within this window, and set as default if desired.See Scripting Language for details about how to write a script.
53 | 54 |To open a script for editing, right-click on the script file and select Edit Script. If the script is already running, you can use the Edit function or right-click the script's tray icon and select Edit Script. If you haven't selected a default editor yet, you should be prompted to select one. Otherwise, you can change your default editor via Editor settings in the Dash. Of course, you can always open a text editor first and then open the script as you would any other text file.
56 |After editing a script, you must run or reload the script for the changes to take effect. A running script can usually be reloaded via its tray menu.
57 | 58 |With AutoHotkey installed, there are several ways to run a script:
60 |Most scripts have an effect only while they are running. Use the tray menu or the ExitApp function to exit a script. Scripts are also forced to exit when Windows shuts down. To configure a script to start automatically after the user logs in, the easiest way is to place a shortcut to the script file in the Startup folder.
67 |Scripts can also be compiled; that is, combined together with an AutoHotkey binary file to form a self-contained executable (.exe) file.
68 | 69 |By default, each script adds its own icon to the taskbar notification area (commonly known as the tray).
71 |The tray icon usually looks like this:
72 | 78 |81 | | The default tray icon. | 82 |
85 | | The script is paused. | 86 |
89 | | The script is suspended. | 90 |
93 | | The script is paused and suspended. | 94 |
Right-click the tray icon to show the tray menu, which has the following options by default:
97 |By default, double-clicking the tray icon shows the script's main window.
108 |The behavior and appearance of the tray icon and menu can be customized:
109 |The script's main window is usually hidden, but can be shown via the tray icon or one of the functions listed below to gain access to information useful for debugging the script. Items under the View menu control what the main window displays:
118 |Known issue: Keyboard shortcuts for menu items do not work while the script is displaying a message box or other dialog.
125 |The built-in variable A_ScriptHwnd contains the unique ID (HWND) of the script's main window.
126 |Closing this window with WinClose (even from another script) causes the script to exit, but most other methods just hide the window and leave the script running.
127 |Minimizing the main window causes it to automatically be hidden. This is done to prevent any owned windows (such as GUI windows or certain dialog windows) from automatically being minimized, but also has the effect of hiding the main window's taskbar button. To instead allow the main window to be minimized normally, override the default handling with OnMessage. For example:
128 |; This prevents the main window from hiding on minimize: 129 | OnMessage 0x0112, PreventAutoMinimize ; WM_SYSCOMMAND = 0x0112 130 | OnMessage 0x0005, PreventAutoMinimize ; WM_SIZE = 0x0005 131 | ; This prevents owned GUI windows (but not dialogs) from automatically minimizing: 132 | OnMessage 0x0018, PreventAutoMinimize 133 | Persistent 134 | 135 | PreventAutoMinimize(wParam, lParam, uMsg, hwnd) { 136 | if (uMsg = 0x0112 && wParam = 0xF020 && hwnd = A_ScriptHwnd) { ; SC_MINIMIZE = 0xF020 137 | WinMinimize 138 | return 0 ; Prevent main window from hiding. 139 | } 140 | if (uMsg = 0x0005 && wParam = 1 && hwnd = A_ScriptHwnd) ; SIZE_MINIMIZED = 1 141 | return 0 ; Prevent main window from hiding. 142 | if (uMsg = 0x0018 && lParam = 1) ; SW_PARENTCLOSING = 1 143 | return 0 ; Prevent owned window from minimizing. 144 | }145 | 146 |
The title of the script's main window is used by the #SingleInstance and Reload mechanisms to identify other instances of the same script. Changing the title prevents the script from being identified as such. The default title depends on how the script was loaded:
148 |Loaded From | Title Expression | Example |
---|---|---|
.ahk file | A_ScriptFullPath " - AutoHotkey v" A_AhkVersion | E:\My Script.ahk - AutoHotkey v1.1.33.09 |
Main resource (compiled script) | A_ScriptFullPath | E:\My Script.exe |
Any other resource | A_ScriptFullPath " - " A_LineFile | E:\My AutoHotkey.exe - *BUILTIN-TOOL.AHK |
The following code illustrates how the default title could be determined by the script itself (but the actual title can be retrieved with WinGetTitle):
155 |156 | title := A_ScriptFullPath 157 | if !A_IsCompiled 158 | title .= " - AutoHotkey v" A_AhkVersion 159 | ; For the correct result, this must be evaluated by the resource being executed, 160 | ; not an #include (unless the #include was merged into the script by Ahk2Exe): 161 | else if SubStr(A_LineFile, 1, 1) = "*" && A_LineFile != "*#1" 162 | title .= " - " A_LineFile 163 |164 | 165 |
Scripts may be embedded into a standard AutoHotkey .exe file by adding them as Win32 (RCDATA) resources using the Ahk2Exe compiler. To add additional scripts, see the AddResource compiler directive.
167 |An embedded script can be specified on the command line or with #Include by writing an asterisk (*) followed by the resource name. For an integer ID, the resource name must be a hash sign (#) followed by a decimal number.
168 |The program may automatically load script code from the following resources, if present in the file:
169 |ID | Spec | Usage |
---|---|---|
1 | *#1 | 173 |This is the means by which a compiled script is created from an .exe file. This script is executed automatically and most command line switches are passed to the script instead of being interpreted by the program. External scripts and alternative embedded scripts can be executed by using the /script switch. | 174 |
2 | *#2 | 177 |If present, this script is automatically "included" before any script that the program loads, and before any file specified with /include. | 178 |
When the source of the main script is an embedded resource, the program acts in "compiled script" mode, with the exception that A_AhkPath always contains the path of the current executable file (the same as A_ScriptFullPath). For resources other than *#1, the resource specifier is included in the main window's title to support #SingleInstance and Reload.
181 |When referenced from code that came from an embedded resource, A_LineFile contains an asterisk (*) followed by the resource name.
182 | 183 |See Passing Command Line Parameters to a Script for command line usage, including a list of command line switches which affect the program's behavior.
185 | 186 |The file AutoHotkey.exe is all that is needed to launch any .ahk script.
188 |Renaming AutoHotkey.exe also changes which script it runs by default, which can be an alternative to compiling a script for use on a computer without AutoHotkey installed. For instance, MyScript.exe automatically runs MyScript.ahk if a filename is not supplied, but is also capable of running other scripts.
189 | 190 |The launcher enables the use of v1 and v2 scripts on one system, with a single filename extension, without necessarily giving preference to one version or requiring different methods of launching scripts. It does this by checking the script for clues about which version it requires, and then locating an appropriate exe to run the script.
192 |If the script contains the #Requires directive, the launcher looks for an exe that satisfies the requirement. Otherwise, the launcher optionally checks syntax. That is, it checks for patterns that are valid only in one of the two major versions. Some of the common patterns it may find include:
193 |MsgBox, with comma
, MsgBox % "no end percent"
and Legacy = assignment
.'single quotes'
or fat arrow =>
in an expression.Detection is conservative; if a case is ambiguous, it should generally be ignored.
201 |In any case where detection fails, by default a menu is shown for the user to select a version. This default can be changed to instead launch either v1 or v2.
202 |Known limitations:
203 |/****/
in v1, but */
at line-end only closes comments in v2, the presence of such a line may cause a large portion of the script to be ignored (by both the launcher and the v1 interpreter).xyz,
is invalid in v2, so is assumed to be a valid v1 command. xyz 1
could be a function statement in v2, but is assumed to also be a valid v1 command, and is therefore ignored.Note: Declaring the required version with #Requires at the top of the main file eliminates any ambiguity.
210 | 211 |The launcher can be enabled, disabled or configured via the Launch Settings GUI, which can be accessed via the dash.
213 |Run all scripts with a specific interpreter disables the launcher and allows the user to select which exe to use to run all scripts, the traditional way. Be aware that selecting a v1 exe will make it difficult to run any of the support scripts, except via the "AutoHotkey" shortcut in the Start menu.
214 |Auto-detect version when launching script enables the launcher. Additional settings control how the launcher selects which interpreter to use.
215 | 216 |When multiple interpreters with the same version number are found, the launcher can rank them according to a predetermined or user-defined set of criteria. The criteria can be expressed as a comma-delimited list of substrings, where each substring may be prefixed with "!" to negate a match. A score is calculated based on which substrings matched, with the left-most substring having highest priority.
218 |Substrings are matched in the file's description, with the exception of "UIA", which matches if the filename contains "_UIA".
219 |For example, _H, 64, !ANSI
would prefer AutoHotkey_H if available, 64-bit if compatible with the system, and finally Unicode over ANSI.
Although the Launcher Settings GUI presents drop-down lists with options such as "Unicode 32-bit", a list of substrings can be manually entered.
221 |Additional (higher-priority) criteria can be specified on the command line with the /RunWith launcher switch.
222 |Criteria can be specified within the script by using the #Requires directive, either as a requirement (if supported by the target AutoHotkey version), or appended to the directive as a comment beginning with "prefer" and ending with a full stop or line ending. For example:
223 |#Requires AutoHotkey v1.1.35 ; prefer 64-bit, Unicode. More comments.224 | 225 |
The installer registers a hidden shell verb named "launch", which executes the launcher with the /Launch switch. It can be utilized by following this example:
227 |pid := RunWait('*Launch "' PathOfScript '"')228 |
By contrast with the default action for .ahk files:
229 |RunWait(PathOfScript)
, which wouldn't work as expected if the launcher exited before the launched script.The launcher can be explicitly executed at the command line for cases where .ahk files are not set to use the launcher by default, or for finer control over its behaviour. If the launcher is compiled, its usage is essentially the same as AutoHotkey.exe except for the additional launcher switches. Otherwise, the format for command line use is as follows:
236 |AutoHotkeyUX.exe launcher.ahk [Switches] [Script Filename] [Script Parameters]237 |
Typically full paths and quote marks would be used for the path to AutoHotkeyUX.exe and launcher.ahk, which can be found in the UX subdirectory of the AutoHotkey installation. An appropriate version of AutoHotkey32.exe or AutoHotkey64.exe can be used instead of AutoHotkeyUX.exe (which is just a copy).
238 |Switches can be a mixture of any of the standard switches and the following launcher-only switches:
239 |Switch | Meaning |
---|---|
/Launch | 243 |Causes the launcher to exit immediately after launching the script, instead of waiting in the background for it to terminate. The launcher's exit code is the process ID (PID) of the new script process. | 244 |
/RunWith criteria | 247 |Specifies additional criteria for determining which executable to use to launch the script. For example, /RunWith UIA . |
248 |
/Which | 251 |
252 | Causes the launcher to identify which interpreter it would use and return it instead of running the script. 253 |The launcher's exit code is the major version number (1 or 2) if identified by #Requires or syntax (if syntax detection is enabled), otherwise 0. 254 |Stdout receives the following UTF-8 strings, each terminated with
Additional lines may be returned in future. 261 | |
262 |
The dash provides access to support scripts and documentation. It can be opened via the "AutoHotkey" shortcut in the Start menu after installation, or by directly running UX\ui-dash.ahk from the installation directory. Currently it is little more than a menu containing the following items, but it might be expanded to provide controls for active scripts, or other convenient functions.
267 |Note that although the Start menu shortcut launches the dash, if it is pinned to the taskbar (or to the Start menu in Windows 7 or 10), the jump list will include any recent scripts launched with the open, runas or UIAccess shell verbs (which are normally accessed via the Explorer context menu or by double-clicking a file). Scripts can be pinned for easy access.
276 | 277 |The New Script GUI can be accessed via the dash or by right-clicking within a folder in Explorer and selecting New → AutoHotkey Script. It can be used to create a new script file from a preinstalled or user-defined template, and optionally open it for editing.
279 |Right-clicking on a template in the list gives the following options:
280 |HKCU\Software\AutoHotkey\New\HideTemplate
.By default, the GUI closes after creating a file unless the Ctrl key is held down.
286 |Additional settings can be accessed via the settings button at the bottom-left of the GUI:
287 |Template files are drawn from UX\Templates (preinstalled) and %A_MyDocuments%\AutoHotkey\Templates (user), with a user-defined template overriding any preinstalled template which has the same name. If a file exists at %A_WinDir%\ShellNew\Template.ahk, it is shown as "Legacy" and can be overridden by a user-defined template of that name.
297 |Each template may contain an INI section as follows:
298 |/* 299 | [NewScriptTemplate] 300 | Description = Descriptive text 301 | Execute = true|false|1|0 302 | */303 |
If the INI section starts with /*
and ends with */
as shown above, it is not included in the created file.
Description is optional. It is shown in the GUI, in addition to the file's name.
305 |Execute is optional. If set to true, the template script is executed with A_Args[1]
containing the path of the file to be created and A_Args[2]
containing either "Create" or "Edit", depending on which button the user clicked. The template script is expected to create the file and open it for editing if applicable. If the template script needs to #include
other files, they can be placed in a subdirectory to avoid having them shown in the template list.
This installer and related scripts are designed to permit multiple versions of AutoHotkey to coexist. The installer provides very few options, as most things can be configured after installation. Only the following choices must be made during installation:
309 |By default the installer will install to "%A_ProgramFiles%\AutoHotkey" for all users. This is recommended, as the UI Access option requires the program to be installed under Program Files. If the installer is not already running as admin, it will attempt to elevate when the Install button is clicked, as indicated by the shield icon on the button.
314 |Current user installation does not require admin rights, as long as the user has write access to the chosen directory. The default directory for a current user installation is "%LocalAppData%\Programs\AutoHotkey".
315 | 316 |There are two methods of installing v1 and v2 together:
318 |/install
switch described below. Each version installs into its own subdirectory.Running a v1.1.34.02 or older installer (or a custom install with v1.1.34.03 or newer) will overwrite some of the values set in the registry by the v2 installer, such as the version number, uninstaller entry and parts of the file type registration. It will also register the v1 uninstaller, which is not capable of correctly uninstalling both versions. To re-register v2, re-run any v2 installer or run UX\install.ahk using AutoHotkey32.exe or AutoHotkey64.exe.
323 | 324 |Unlike a v1 installation, a default version is not selected during installation. Defaults are instead handled more dynamically by the launcher, and can be configured per-user.
326 | 327 |To directly install to the DESTINATION directory, use /installto
or /to
(the two switches are interchangeable) as shown below, from within the source directory. Use either a downloaded setup.exe or files extracted from a downloaded zip or other source.
AutoHotkey_setup.exe /installto "%DESTINATION%"330 |
AutoHotkey32.exe UX\install.ahk /to "%DESTINATION%"331 |
To install an additional version from SOURCE (which should be a directory containing AutoHotkey*.exe files), execute the following from within the current installation directory (adjusting the path of AutoHotkey32.exe as needed):
332 |AutoHotkey32.exe UX\install.ahk /install "%SOURCE%"333 |
The full command string for the above is registered as InstallCommand under HKLM\Software\AutoHotkey
or HKCU\Software\AutoHotkey
, with %1
as the substitute for the source directory. Using this registry value may be more future-proof.
To re-register the current installation:
335 |AutoHotkey32.exe UX\install.ahk336 |
To uninstall:
337 |AutoHotkey32.exe UX\install.ahk /uninstall338 |
Alternatively, read the QuietUninstallString value from one of the following registry keys, and execute it:
339 |HKLM\Microsoft\Windows\CurrentVersion\Uninstall\AutoHotkey 340 | HKCU\Microsoft\Windows\CurrentVersion\Uninstall\AutoHotkey341 |
Use the /silent
switch to suppress warning or confirmation dialogs and prevent the Dash from being shown when installation is complete. The following actions may be taken automatically, without warning:
The v2 installer does not provide an option to separate taskbar buttons. This was previously achieved by registering each AutoHotkey executable as a host app (IsHostApp), but this approach has limitations, and becomes less manageable when multiple versions can be installed. Instead, each script should set the AppUserModelID of its process or windows to control grouping.
349 | 350 |When installing under Program Files, the installer creates an additional set of AutoHotkey exe files that can be used to work around some common UAC-related issues. These files are given the "_UIA.exe" suffix. When one of these UIA.exe files is used by an administrator to run a script, the script is able to interact with windows of programs that run as admin, without the script itself running as admin.
352 |The installer does the following:
353 |The launcher can also be configured to run v1 scripts, v2 scripts or both with UI Access by default, but this option has no effect if a UIA.exe file does not exist for the selected version and build.
360 |Scripts which need to run other scripts with UI access can simply Run the appropriate UIA.exe file with the normal command line parameters. Alternatively, if the UIAccess shell verb is registered, it can be used via Run. For example: Run '*UIAccess "Script.ahk"'
Known limitations:
362 |ComObjActive("Word.Application")
will fail because Word is not marked for UI Access.InstallMouseHook
) may prevent all mouse hotkeys from working when the mouse is pointing at a window owned by a UIA script, even hotkeys implemented by the UIA script itself. A workaround is to ensure UIA scripts are loaded last.For more details, see Enable interaction with administrative programs on the archived forum.
373 | 374 | 375 | 376 | -------------------------------------------------------------------------------- /docs/Scripts.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Related topics:
15 |Each script is a plain text file containing lines to be executed by the program (AutoHotkey.exe). A script may also contain hotkeys and hotstrings, or even consist entirely of them. However, in the absence of hotkeys and hotstrings, a script will perform its functions sequentially from top to bottom the moment it is launched.
34 |The program loads the script into memory line by line. During loading, the script is optimized and validated. Any syntax errors will be displayed, and they must be corrected before the script can run.
35 | 36 |After the script has been loaded, the auto-execute thread begins executing at the script's top line, and continues until instructed to stop, such as by Return, ExitApp or Exit. The physical end of the script also acts as Exit.
38 |The script will terminate after completing startup if it lacks hotkeys, hotstrings, visible GUIs, active timers, clipboard monitors and InputHooks, and has not called the Persistent function. Otherwise, it will stay running in an idle state, responding to events such as hotkeys, hotstrings, GUI events, custom menu items, and timers. If these conditions change after startup completes (for example, the last timer is disabled), the script may exit when the last running thread completes or the last GUI closes.
39 |Whenever any new thread is launched (whether by a hotkey, hotstring, timer, or some other event), the following settings are copied from the auto-execute thread. If not set by the auto-execute thread, the standard defaults will apply (as documented on each of the following pages): CoordMode, Critical, DetectHiddenText, DetectHiddenWindows, FileEncoding, ListLines, SendLevel, SendMode, SetControlDelay, SetDefaultMouseSpeed, SetKeyDelay, SetMouseDelay, SetRegView, SetStoreCapsLockMode, SetTitleMatchMode, SetWinDelay, and Thread.
40 |Each thread retains its own collection of the above settings, so changes made to those settings will not affect other threads.
41 |The "default setting" for one of the above functions usually refers to the current setting of the auto-execute thread, which starts out the same as the program-defined default setting.
42 |Traditionally, the top of the script has been referred to as the auto-execute section. However, the auto-execute thread is not limited to just the top of the script. Any functions which are called on the auto-execute thread may also affect the default settings. As directives and function, hotkey, hotstring and class definitions are skipped when encountered during execution, it is possible for startup code to be placed throughout each file. For example, a global variable used by a group of hotkeys may be initialized above (or even below) those hotkeys rather than at the top of the script.
43 | 44 |Long lines can be divided up into a collection of smaller ones to improve readability and maintainability. This does not reduce the script's execution speed because such lines are merged in memory the moment the script launches.
46 |There are three methods, and they can generally be used in combination:
47 |Continuation operator: A line that starts with a comma or any other expression operator (except ++ and --) is automatically merged with the line directly above it. Similarly, a line that ends with an expression operator is automatically merged with the line below it. In the following example, the second line is appended to the first because it begins with a comma:
53 |FileAppend "This is the text to append.`n" ; A comment is allowed here. 54 | , A_ProgramFiles "\SomeApplication\LogFile.txt" ; Comment.55 |
Similarly, the following lines would get merged into a single line because the last two start with "and" or "or":
56 |if Color = "Red" or Color = "Green" or Color = "Blue" ; Comment. 57 | or Color = "Black" or Color = "Gray" or Color = "White" ; Comment. 58 | and ProductIsAvailableInColor(Product, Color) ; Comment.59 |
The ternary operator is also a good candidate:
60 |ProductIsAvailable := (Color = "Red") 61 | ? false ; We don't have any red products, so don't bother calling the function. 62 | : ProductIsAvailableInColor(Product, Color)63 |
The following examples are equivalent to those above:
64 |FileAppend "This is the text to append.`n", ; A comment is allowed here. 65 | A_ProgramFiles "\SomeApplication\LogFile.txt" ; Comment. 66 | 67 | if Color = "Red" or Color = "Green" or Color = "Blue" or ; Comment. 68 | Color = "Black" or Color = "Gray" or Color = "White" and ; Comment. 69 | ProductIsAvailableInColor(Product, Color) ; Comment. 70 | 71 | ProductIsAvailable := (Color = "Red") ? 72 | false : ; We don't have any red products, so don't bother calling the function. 73 | ProductIsAvailableInColor(Product, Color)74 |
Although the indentation used in the examples above is optional, it might improve clarity by indicating which lines belong to ones above them. Also, blank lines or comments may be added between or at the end of any of the lines in the above examples.
75 |A continuation operator cannot be used with an auto-replace hotstring or directive other than #HotIf.
76 |Continuation by enclosure: If a line contains an expression or function/property definition with an unclosed (
/[
/{
, it is joined with subsequent lines until the number of opening and closing symbols balances out. In other words, a sub-expression enclosed in parentheses, brackets or braces can automatically span multiple lines in most cases. For example:
78 | myarray := [ 79 | "item 1", 80 | "item 2", 81 | ] 82 | MsgBox( 83 | "The value of item 2 is " myarray[2], 84 | "Title", 85 | "ok iconi" 86 | ) 87 |88 |
Continuation expressions may contain both types of comments.
89 |Continuation expressions may contain normal continuation sections. Therefore, as with any line containing an expression, if a line begins with a non-escaped open parenthesis ((
), it is considered to be the start of a continuation section unless there is a closing parenthesis ()
) on the same line.
Quoted strings cannot span multiple lines using this method alone. However, see above.
91 |Continuation by enclosure can be combined with a continuation operator. For example:
92 |myarray := ; The assignment operator causes continuation. 93 | [ ; Brackets enclose the following two lines. 94 | "item 1", 95 | "item 2", 96 | ]97 |
Brace ({
) at the end of a line does not cause continuation if the program determines that it should be interpreted as the beginning of a block (OTB style) rather than the start of an object literal. Specifically (in descending order of precedence):
(
/[
/{
, since that would produce an invalid expression. For example, the brace in If ({
is the start of an object literal.)
or ]
, so if the brace follows either of those symbols (excluding whitespace), it is interpreted as the beginning of a block (such as for a function or property definition).:= {
or for x in {
. In particular, the brace in Loop {
is always block-begin, and If {
and While {
are always errors.A brace can be safely used for line continuation with any function call, expression or control flow statement which does not require a body. For example:
104 |myfn() { 105 | return { 106 | key: "value" 107 | } 108 | }109 |
Continuation section: This method should be used to merge a large number of lines or when the lines are not suitable for the other methods. Although this method is especially useful for auto-replace hotstrings, it can also be used with any expression. For example:
110 |; EXAMPLE #1: 111 | Var := " 112 | ( 113 | A line of text. 114 | By default, the hard carriage return (Enter) between the previous line and this one will be stored. 115 | This line is indented with a tab; by default, that tab will also be stored. 116 | Additionally, "quote marks" are automatically escaped when appropriate. 117 | )" 118 | 119 | ; EXAMPLE #2: 120 | FileAppend " 121 | ( 122 | Line 1 of the text. 123 | Line 2 of the text. By default, a linefeed (`n) is present between lines. 124 | )", A_Desktop "\My File.txt"125 |
In the examples above, a series of lines is bounded at the top and bottom by a pair of parentheses. This is known as a continuation section. Notice that any code after the closing parenthesis is also joined with the other lines (without any delimiter), but the opening and closing parentheses are not included.
126 |If the line above the continuation section ends with a name character and the section does not start inside a quoted string, a single space is automatically inserted to separate the name from the contents of the continuation section.
127 |Quote marks are automatically escaped (i.e. they are interpreted as literal characters) if the continuation section starts inside a quoted string, as in the examples above. Otherwise, quote marks act as they do normally; that is, continuation sections can contain expressions with quoted strings.
128 |By default, leading spaces or tabs are omitted based on the indentation of the first line inside the continuation section. If the first line mixes spaces and tabs, only the first type of character is treated as indentation. If any line is indented less than the first line or with the wrong characters, all leading whitespace on that line is left as is.
129 |By default, trailing spaces or tabs are omitted.
130 |The default behavior of a continuation section can be overridden by including one or more of the following options to the right of the section's opening parenthesis. If more than one option is present, separate each one from the previous with a space. For example: ( LTrim Join|
.
JoinString: Specifies how lines should be connected together. If this option is not used, each line except the last will be followed by a linefeed character (`n). If String is omitted, lines are connected directly to each other without any characters in between. Otherwise, specify for String a string of up to 15 characters. For example, Join`s
would insert a space after each line except the last. Another example is Join`r`n
, which inserts CR+LF between lines. Similarly, Join|
inserts a pipe between lines. To have the final line in the section also ended by String, include a blank line immediately above the section's closing parenthesis.
LTrim: Omits all spaces and tabs at the beginning of each line. This is usually unnecessary because of the default "smart" behaviour.
133 |LTrim0 (LTrim followed by a zero): Turns off the omission of spaces and tabs from the beginning of each line.
134 |RTrim0 (RTrim followed by a zero): Turns off the omission of spaces and tabs from the end of each line.
135 |Comments (or Comment or Com or C): Allows semicolon comments inside the continuation section (but not /*..*/
). Such comments (along with any spaces and tabs to their left) are entirely omitted from the joined result rather than being treated as literal text. Each comment can appear to the right of a line or on a new line by itself.
` (accent): Treats each backtick character literally rather than as an escape character. This also prevents the translation of any explicitly specified escape sequences such as `r
and `t
.
( or ): If an opening or closing parenthesis appears to the right of the initial opening parenthesis (except as a parameter of the Join option), the line is reinterpreted as an expression instead of the beginning of a continuation section. This enables expressions like (x.y)[z]()
to be used at the start of a line, and also allows multi-line expressions to start with a line like ((
or (MyFunc(
.
Escape sequences such as `n (linefeed) and `t (tab) are supported inside the continuation section except when the accent (`) option has been specified.
141 |When the comment option is absent, semicolon and /*..*/ comments are not supported within the interior of a continuation section because they are seen as literal text. However, comments can be included on the bottom and top lines of the section. For example:
142 |FileAppend " ; Comment. 143 | ; Comment. 144 | ( LTrim Join ; Comment. 145 | ; This is not a comment; it is literal. Include the word Comments in the line above to make it a comment. 146 | )", "C:\File.txt" ; Comment.147 |
As a consequence of the above, semicolons never need to be escaped within a continuation section.
148 |Since a closing parenthesis indicates the end of a continuation section, to have a line start with literal closing parenthesis, precede it with an accent/backtick: `)
. However, this cannot be combined with the accent (`) option.
A continuation section can be immediately followed by a line containing the open-parenthesis of another continuation section. This allows the options mentioned above to be varied during the course of building a single line.
150 |The piecemeal construction of a continuation section by means of #Include is not supported.
151 | 152 |The library folders provide a few standard locations to keep shared scripts which other scripts utilise by means of #Include. A library script typically contains a function or class which is designed to be used and reused in this manner. Placing library scripts in one of these locations makes it easier to write scripts that can be shared with others and work across multiple setups. The library locations are:
154 |A_ScriptDir "\Lib\" ; Local library. 155 | A_MyDocuments "\AutoHotkey\Lib\" ; User library. 156 | "directory-of-the-currently-running-AutoHotkey.exe\Lib\" ; Standard library.157 |
The library folders are searched in the order shown above.
158 |For example, if a script includes the line #Include <MyLib>
, the program searches for a file named "MyLib.ahk" in the local library. If not found there, it searches for it in the user library, and then the standard library. If a match is still not found and the library's name contains an underscore (e.g. MyPrefix_MyFunc
), the program searches again with just the prefix (e.g. MyPrefix.ahk
).
Although by convention a library file generally contains only a single function or class of the same name as its filename, it may also contain private functions that are called only by it. However, such functions should have fairly distinct names because they will still be in the global namespace; that is, they will be callable from anywhere in the script.
160 | 161 |A script compiler (courtesy of fincs, with additions by TAC109) is available as a separate automatic download.
163 |Once a script is compiled, it becomes a standalone executable; that is, AutoHotkey.exe is not required in order to run the script. The compilation process creates an executable file which contains the following: the AutoHotkey interpreter, the script, any files it includes, and any files it has incorporated via the FileInstall function. Additional files can be included using compiler directives.
164 |The same compiler is used for v1.1 and v2 scripts. The compiler distinguishes script versions by checking the major version of the base file supplied.
165 |Ahk2Exe can be used in the following ways:
175 |GUI Interface: Run the "Convert .ahk to .exe" item in the Start Menu. (After invoking the GUI, there may be a pause before the window is shown; see Background Information for more details.)
178 |Right-click: Within an open Explorer window, right-click any .ahk file and select "Compile Script" (only available if the script compiler option was chosen when AutoHotkey was installed). This creates an EXE file of the same base filename as the script, which appears after a short time in the same directory. Note: The EXE file is produced using the same custom icon, .bin file and compression setting that were last saved in Method #1 above, or as specified by any relevant compiler directive in the script.
181 |Command Line: The compiler can be run from the command line by using the parameters shown below. If any command line parameters are used, the script is compiled immediately unless /gui
is used. All parameters are optional, except that there must be one /gui
or /in
parameter.
Parameter pair | 192 |Meaning | 193 |
---|---|
/in script_name | 196 |The path and name of the script to compile. This is mandatory if any other parameters are used, unless /gui is used. |
197 |
/out exe_name | 200 |The path\name of the output .exe to be created. Default is the directory\base_name of the input file plus extension of .exe, or any relevant compiler directive in the script. | 201 |
/icon icon_name | 204 |The icon file to be used. Default is the last icon saved in the GUI interface, or any SetMainIcon compiler directive in the script. | 205 |
/base file_name | 208 |The base file to be used (a .bin or .exe file). The major version of the base file used must be the same as the version of the script to be compiled. Default is the last base file name saved in the GUI interface, or any Base compiler directive in the script. | 209 |
/resourceid name | 212 |Assigns a non-standard resource ID to be used for the main script for compilations which use an .exe base file (see Embedded Scripts). Numeric resource IDs should consist of a hash sign (#) followed by a decimal number. Default is #1, or any ResourceID compiler directive in the script. | 213 |
/cp codepage | 216 |Overrides the default codepage used to read script files. For a list of possible values, see Code Page Identifiers. Note that Unicode scripts should begin with a byte-order-mark (BOM), rendering the use of this parameter unnecessary. | 217 |
/compress n | 220 |Compress the exe? 0 = no, 1 = use MPRESS if present, 2 = use UPX if present. Default is the last setting saved in the GUI interface. | 221 |
/gui | 224 |Shows the GUI instead of immediately compiling. The other parameters can be used to override the settings last saved in the GUI. /in is optional in this case. |
225 |
/silent [verbose] | 228 |Disables all message boxes and instead outputs errors to the standard error stream (stderr); or to the standard output stream (stdout) if stderr fails. Other messages are also output to stdout. Optionally enter the word verbose to output status messages to stdout as well. |
229 |
Deprecated: /ahk file_name |
232 | The path\name of AutoHotkey.exe to be used as a utility when compiling the script. | 233 |
Deprecated: /mpress 0or1 |
236 | Compress the exe with MPRESS? 0 = no, 1 = yes. Default is the last setting used in the GUI interface. | 237 |
Deprecated: /bin file_name |
240 | The .bin file to be used. Default is the last .bin file name saved in the GUI interface. | 241 |
For example:
244 |Ahk2Exe.exe /in "MyScript.ahk" /icon "MyIcon.ico"245 |
Notes:
248 |The compiler's source code and newer versions can be found at GitHub.
257 | 258 |Each compiled script .exe is based on an executable file which implements the interpreter. The base files included in the Compiler directory have the ".bin" extension; these are versions of the interpreter which do not include the capability to load external script files. Instead, the program looks for a Win32 (RCDATA) resource named ">AUTOHOTKEY SCRIPT<" and loads that, or fails if it is not found.
260 |The standard AutoHotkey executable files can also be used as the base of a compiled script, by embedding a Win32 (RCDATA) resource with ID 1. (Additional scripts can be added with the AddResource compiler directive.) This allows the compiled script .exe to be used with the /script switch to execute scripts other than the main embedded script. For more details, see Embedded Scripts.
261 | 262 |Script compiler directives allow the user to specify details of how a script is to be compiled. Some of the features are:
264 |See Script Compiler Directives for more details.
271 | 272 |Ahk2Exe optionally uses MPRESS or UPX freeware to compress compiled scripts. If MPRESS.exe and/or UPX.exe has been copied to the "Compiler" subfolder where AutoHotkey was installed, either can be used to compress the .exe as directed by the /compress
parameter or the GUI setting.
MPRESS: archived official website (downloads and information) | direct download (95 KB)
275 |UPX: official website (downloads and information)
276 |Note: While compressing the script executable prevents casual inspection of the script's source code using a plain text editor like Notepad or a PE resource editor, it does not prevent the source code from being extracted by tools dedicated to that purpose.
277 | 278 |The following folder structure is supported, where the running version of Ahk2Exe.exe
is in the first \Compiler directory shown below:
\AutoHotkey 281 | AutoHotkeyA32.exe 282 | AutoHotkeyU32.exe 283 | AutoHotkeyU64.exe 284 | \Compiler 285 | Ahk2Exe.exe ; the master version of Ahk2Exe 286 | ANSI 32-bit.bin 287 | Unicode 32-bit.bin 288 | Unicode 64-bit.bin 289 | \AutoHotkey v2.0-a135 290 | AutoHotkey32.exe 291 | AutoHotkey64.exe 292 | \Compiler 293 | \v2.0-beta.1 294 | AutoHotkey32.exe 295 | AutoHotkey64.exe296 |
The base file search algorithm runs for a short amount of time when Ahk2Exe starts, and works as follows:
297 |Qualifying AutoHotkey .exe files and all .bin files are searched for in the compiler's directory, the compiler's parent directory, and any of the compiler's sibling directories with directory names that start with AutoHotkey
or V
, but do not start with AutoHotkey_H
. The selected directories are searched recursively. Any AutoHotkey.exe files found are excluded, leaving files such as AutoHotkeyA32.exe, AutoHotkey64.exe, etc. plus all .bin files found. All .exe files that are included must have a name starting with AutoHotkey
and a file description containing the word AutoHotkey
, and must have a version of 1.1.34+
or 2.0-a135+
.
A version of the AutoHotkey interpreter is also needed (as a utility) for a successful compile, and one is selected using a similar algorithm. In most cases the version of the interpreter used will match the version of the base file selected by the user for the compile.
299 | 300 | 301 |Scripts support command line parameters. The format is:
303 |AutoHotkey.exe [Switches] [Script Filename] [Script Parameters]304 |
And for compiled scripts, the format is:
305 |CompiledScript.exe [Switches] [Script Parameters]306 |
Switches: Zero or more of the following:
307 |Switch | Meaning | Works compiled? |
---|---|---|
/force | 311 |Launch unconditionally, skipping any warning dialogs. This has the same effect as #SingleInstance Off. | 312 |Yes | 313 |
/restart | 316 |Indicate that the script is being restarted and should attempt to close a previous instance of the script (this is also used by the Reload function, internally). | 317 |Yes | 318 |
/ErrorStdOut /ErrorStdOut=Encoding |
321 |
322 | Send syntax errors that prevent a script from launching to the standard error stream (stderr) rather than displaying a dialog. See #ErrorStdOut for details. 323 |An encoding can optionally be specified. For example, |
325 | No | 326 |
/Debug | 329 |Connect to a debugging client. For more details, see Interactive Debugging. | 330 |No | 331 |
/CPn | 334 |
335 | Overrides the default codepage used to read script files. For more details, see Script File Codepage. 336 | |
337 | No | 338 |
/Validate | 341 |
342 | AutoHotkey loads the script and then exits instead of running it. 343 |By default, load-time errors and warnings are displayed as usual. The /ErrorStdOut switch can be used to suppress or capture any error messages. 344 |The process exit code is zero if the script successfully loaded, or non-zero if there was an error. 345 | |
346 | No | 347 |
/iLib "OutFile" | 350 |
351 | Deprecated: Equivalent to /validate; use that instead. 352 |"OutFile" must be specified but is ignored. In previous versions of AutoHotkey, filenames of auto-included files were written to the file specified by OutFile, formatted as #Include directives. 353 | |
354 | No | 355 |
/include "IncFile" | 358 |
359 | Includes a file prior to the main script. Only a single file can be included by this method. When the script is reloaded, this switch is automatically passed to the new instance. 360 | |
361 | No | 362 |
/script | 365 |
366 | When used with a compiled script based on an .exe file, this switch causes the program to ignore the main embedded script. This allows a compiled script .exe to execute external script files or embedded scripts other than the main one. Other switches not normally supported by compiled scripts can be used but must be listed to the right of this switch. For example: 367 |CompiledScript.exe /script /ErrorStdOut MyScript.ahk "Script's arg 1"368 | If the current executable file does not have an embedded script, this switch is permitted but has no effect. 369 |This switch is not supported by compiled scripts which are based on a .bin file. 370 |See also: Base Executable File (Ahk2Exe) 371 | |
372 | N/A | 373 |
Script Filename: This can be omitted if there are no Script Parameters. If omitted, it defaults to the path and name of the AutoHotkey executable, replacing ".exe" with ".ahk". For example, if you rename AutoHotkey.exe to MyScript.exe, it will attempt to load MyScript.ahk. If you run AutoHotkey32.exe without parameters, it will attempt to load AutoHotkey32.ahk.
377 |Specify an asterisk (*) for the filename to read the script text from standard input (stdin). This also puts the following into effect:
378 |For an example, see ExecScript().
384 |If the current executable file has embedded scripts, this parameter can be an asterisk followed by the resource name or ID of an embedded script. For compiled scripts (i.e. if an embedded script with the ID #1 exists), this parameter must be preceded by the /script
switch.
Script Parameters: The string(s) you want to pass into the script, with each separated from the next by one or more spaces. Any parameter that contains spaces should be enclosed in quotation marks. If you want to pass an empty string as a parameter, specify two consecutive quotation marks. A literal quotation mark may be passed in by preceding it with a backslash (\"). Consequently, any trailing slash in a quoted parameter (such as "C:\My Documents\") is treated as a literal quotation mark (that is, the script would receive the string C:\My Documents"). To remove such quotes, use A_Args[1] := StrReplace(A_Args[1], '"')
Incoming parameters, if present, are stored as an array in the built-in variable A_Args, and can be accessed using array syntax. A_Args[1]
contains the first parameter. The following example exits the script when too few parameters are passed to it:
if A_Args.Length < 3 388 | { 389 | MsgBox "This script requires at least 3 parameters but it only received " A_Args.Length "." 390 | ExitApp 391 | }392 |
If the number of parameters passed into a script varies (perhaps due to the user dragging and dropping a set of files onto a script), the following example can be used to extract them one by one:
393 |for n, param in A_Args ; For each parameter: 394 | { 395 | MsgBox "Parameter number " n " is " param "." 396 | } 397 |398 |
If the parameters are file names, the following example can be used to convert them to their case-corrected long names (as stored in the file system), including complete/absolute path:
399 |for n, GivenPath in A_Args ; For each parameter (or file dropped onto a script): 400 | { 401 | Loop Files, GivenPath, "FD" ; Include files and directories. 402 | LongPath := A_LoopFileFullPath 403 | MsgBox "The case-corrected long path name of file`n" GivenPath "`nis:`n" LongPath 404 | }405 | 406 |
In order for non-ASCII characters to be read correctly from file, the encoding used when the file was saved (typically by the text editor) must match what AutoHotkey uses when it reads the file. If it does not match, characters will be decoded incorrectly. AutoHotkey uses the following rules to decide which encoding to use:
408 |Note that this applies only to script files loaded by AutoHotkey, not to file I/O within the script itself. FileEncoding controls the default encoding of files read or written by the script, while IniRead and IniWrite always deal in UTF-16 or ANSI.
414 |As all text is converted (where necessary) to the native string format, characters which are invalid or don't exist in the native codepage are replaced with a placeholder: '�'. This should only occur if there are encoding errors in the script file or the codepages used to save and load the file don't match.
415 |RegWrite may be used to set the default for scripts launched from Explorer (e.g. by double-clicking a file):
416 |; Uncomment the appropriate line below or leave them all commented to 417 | ; reset to the default of the current build. Modify as necessary: 418 | ; codepage := 0 ; System default ANSI codepage 419 | ; codepage := 65001 ; UTF-8 420 | ; codepage := 1200 ; UTF-16 421 | ; codepage := 1252 ; ANSI Latin 1; Western European (Windows) 422 | if (codepage != "") 423 | codepage := " /CP" . codepage 424 | cmd := Format('"{1}"{2} "%1" %*', A_AhkPath, codepage) 425 | key := "AutoHotkeyScript\Shell\Open\Command" 426 | if A_IsAdmin ; Set for all users. 427 | RegWrite cmd, "REG_SZ", "HKCR\" key 428 | else ; Set for current user only. 429 | RegWrite cmd, "REG_SZ", "HKCU\Software\Classes\" key430 |
This assumes AutoHotkey has already been installed. Results may be less than ideal if it has not.
431 | 432 |Built-in functions such as ListVars and Pause can help you debug a script. For example, the following two lines, when temporarily inserted at carefully chosen positions, create "break points" in the script:
434 |ListVars 435 | Pause436 |
When the script encounters these two lines, it will display the current contents of all variables for your inspection. When you're ready to resume, un-pause the script via the File or Tray menu. The script will then continue until reaching the next "break point" (if any).
437 |It is generally best to insert these "break points" at positions where the active window does not matter to the script, such as immediately before a WinActivate function. This allows the script to properly resume operation when you un-pause it.
438 |The following functions are also useful for debugging: ListLines, KeyHistory, and OutputDebug.
439 |Some common errors, such as typos and missing "global" declarations, can be detected by enabling warnings.
440 |Interactive debugging is possible with a supported DBGp client. Typically the following actions are possible:
442 |Note that this functionality is disabled for compiled scripts which are based on a BIN file. For compiled scripts based on an EXE file, /debug must be specified after /script.
449 |To enable interactive debugging, first launch a supported debugger client then launch the script with the /Debug command-line switch.
450 |AutoHotkey.exe /Debug[=SERVER:PORT] ...451 |
SERVER and PORT may be omitted. For example, the following are equivalent:
452 |AutoHotkey /Debug "myscript.ahk" 453 | AutoHotkey /Debug=localhost:9000 "myscript.ahk"454 |
To attach the debugger to a script which is already running, send it a message as shown below:
455 |ScriptPath := "" ; SET THIS TO THE FULL PATH OF THE SCRIPT 456 | A_DetectHiddenWindows := true 457 | if WinExist(ScriptPath " ahk_class AutoHotkey") 458 | ; Optional parameters: 459 | ; wParam = the IPv4 address of the debugger client, as a 32-bit integer. 460 | ; lParam = the port which the debugger client is listening on. 461 | PostMessage DllCall("RegisterWindowMessage", "Str", "AHK_ATTACH_DEBUGGER") 462 |463 |
Once the debugger client is connected, it may detach without terminating the script by sending the "detach" DBGp command.
464 | 465 |See this page for some useful scripts.
467 | 468 | 469 | -------------------------------------------------------------------------------- /docs/Tutorial.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |Before we begin our journey, let me give some advice. Throughout this tutorial you will see a lot of text and a lot of code. For optimal learning power, it is advised that you read the text and try the code. Then, study the code. You can copy and paste most examples on this page. If you get confused, try reading the section again.
69 | 70 |Before learning to use AutoHotkey (AHK), you will need to download it. After downloading it, you may possibly need to install it. But that depends on the version you want. For this guide we will use the Installer since it is easiest to set up.
77 | 78 |Text instructions:
79 |Once you have AutoHotkey installed, you will probably want it to do stuff. AutoHotkey is not magic, we all wish it was, but it is not. So we will need to tell it what to do. This process is called "Scripting".
88 | 89 |Text instructions:
90 |So now that you have created a script, we need to add stuff into the file. For a list of all built-in function and variables, see section 5.
99 |Here is a very basic script containing a hotkey which types text using the Send function when the hotkey is pressed:
100 |101 | ^j:: 102 | { 103 | Send "My First Script" 104 | }105 |
We will get more in-depth later on. Until then, here's an explanation of the above code:
106 |^j::
is the hotkey. ^
means Ctrl, j
is the letter J. Anything to the left of ::
are the keys you need to press.Send "My First Script"
is how you send keystrokes. Send
is the function, anything after the space inside the quotes will be typed.{
and }
marks the start and end of the hotkey.For a video instruction, watch Install and Hello World on YouTube.
116 | 117 |Downloads for v2.0-a076 and later include an offline help file in the same zip as the main program. If you manually extracted the files, the help file should be wherever you put it.
119 |v2.0-beta.4 and later include an installation script. If you have used this to install AutoHotkey, the help file for each version should be in a subdirectory of the location where AutoHotkey was installed, such as "C:\Program Files\AutoHotkey\v2.0-beta.7". There may also be a symbolic link named "v2" pointing to the subdirectory of the last installed version. If v1.x is installed, a help file for that version may also be present in the root directory.
120 |Look for AutoHotkey.chm or a file that says AutoHotkey and has a yellow question mark on it.
121 |If you don't need to find the file itself, there are also a number of ways to launch it:
122 |What is a hotkey? A hotkey is a key that is hot to the touch. ... Just kidding. It is a key or key combination that the person at the keyboard presses to trigger some actions. For example:
131 |^j:: 132 | { 133 | Send "My First Script" 134 | }135 |
What is a hotstring? Hotstrings are mainly used to expand abbreviations as you type them (auto-replace), they can also be used to launch any scripted action. For example:
136 |::ftw::Free the whales137 |
The difference between the two examples is that the hotkey will be triggered when you press Ctrl+J while the hotstring will convert your typed "ftw" into "Free the whales".
138 |"So, how exactly does a person such as myself create a hotkey?" Good question. A hotkey is created by using a single pair of colons. The key or key combo needs to go on the left of the ::
. And the content needs to go below, enclosed in curly brackets.
Note: There are exceptions, but those tend to cause confusion a lot of the time. So it won't be covered in the tutorial, at least, not right now.
140 |Esc:: 141 | { 142 | MsgBox "Escape!!!!" 143 | }144 |
A hotstring has a pair of colons on each side of the text you want to trigger the text replacement. While the text to replace your typed text goes on the right of the second pair of colons.
145 |Hotstrings, as mentioned above, can also launch scripted actions. That's fancy talk for "do pretty much anything". Same with hotkeys.
146 |::btw:: 147 | { 148 | MsgBox "You typed btw." 149 | }150 |
A nice thing to know is that you can have many lines of code for each hotkey, hotstring, label, and a lot of other things we haven't talked about yet.
151 |^j:: 152 | { 153 | MsgBox "Wow!" 154 | MsgBox "There are" 155 | Run "notepad.exe" 156 | WinActivate "Untitled - Notepad" 157 | WinWaitActive "Untitled - Notepad" 158 | Send "7 lines{!}{Enter}" 159 | SendInput "inside the CTRL{+}J hotkey." 160 | }161 | 162 |
You might be wondering "How the crud am I supposed to know that ^ means Ctrl?!". Well, good question. To help you learn what ^ and other symbols mean, gaze upon this chart:
164 |Symbol | 167 |Description | 168 |
---|---|
# | 171 |Win (Windows logo key) | 172 |
! | 175 |Alt | 176 |
^ | 179 |Ctrl | 180 |
+ | 183 |Shift | 184 |
& | 187 |An ampersand may be used between any two keys or mouse buttons to combine them into a custom hotkey. | 188 |
(For the full list of symbols, see the Hotkey page)
191 |Additionally, for a list of all/most hotkey names that can be used on the left side of a hotkey's double-colon, see List of Keys, Mouse Buttons, and Controller Controls.
192 |You can define a custom combination of two (and only two) keys (except controller buttons) by using &
between them. In the example below, you would hold down Numpad0 then press Numpad1 or Numpad2 to trigger one of the hotkeys:
Numpad0 & Numpad1:: 195 | { 196 | MsgBox "You pressed Numpad1 while holding down Numpad0." 197 | } 198 | 199 | Numpad0 & Numpad2:: 200 | { 201 | Run "notepad.exe" 202 | }203 | 204 |
But you are now wondering if hotstrings have any cool modifiers since hotkeys do. Yes, they do! Hotstring modifiers go between the first set of colons. For example:
205 |:*:ftw::Free the whales206 | 207 |
Visit Hotkeys and Hotstrings for additional hotkey and hotstring modifiers, information and examples.
208 |Sometime you might want a hotkey or hotstring to only work (or be disabled) in a certain window. To do this, you will need to use one of the fancy commands with a # in-front of them, namely #HotIf, combined with the built-in function WinActive or WinExist:
211 |#HotIf WinActive(WinTitle) 212 | #HotIf WinExist(WinTitle)213 |
This special command (technically called "directive") creates context-sensitive hotkeys and hotstrings. Simply specify a window title for WinTitle. But in some cases you might want to specify criteria such as HWND, group or class. Those are a bit advanced and are covered more in-depth here: The WinTitle Parameter & the Last Found Window.
214 |#HotIf WinActive("Untitled - Notepad") 215 | #Space:: 216 | { 217 | MsgBox "You pressed WIN+SPACE in Notepad." 218 | }219 |
To turn off context sensitivity for subsequent hotkeys or hotstrings, specify #HotIf without its parameter. For example:
; Untitled - Notepad 220 | #HotIf WinActive("Untitled - Notepad") 221 | !q:: 222 | { 223 | MsgBox "You pressed ALT+Q in Notepad." 224 | } 225 | 226 | ; Any window that isn't Untitled - Notepad 227 | #HotIf 228 | !q:: 229 | { 230 | MsgBox "You pressed ALT+Q in any window." 231 | } 232 |233 |
When #HotIf directives are never used in a script, all hotkeys and hotstrings are enabled for all windows.
234 |The #HotIf directive is positional: it affects all hotkeys and hotstrings physically beneath it in the script, until the next #HotIf directive.
235 |; Notepad 236 | #HotIf WinActive("ahk_class Notepad") 237 | #Space:: 238 | { 239 | MsgBox "You pressed WIN+SPACE in Notepad." 240 | } 241 | ::msg::You typed msg in Notepad 242 | 243 | ; MSPaint 244 | #HotIf WinActive("Untitled - Paint") 245 | #Space:: 246 | { 247 | MsgBox "You pressed WIN+SPACE in MSPaint!" 248 | } 249 | ::msg::You typed msg in MSPaint!250 |
For more in-depth information, check out the #HotIf page.
251 |This, for some reason crosses some people's minds. So I'll set it clear: AutoHotkey has the ability to have as many hotkeys and hotstrings in one file as you want. Whether it's 1, or 3253 (or more).
253 |#i:: 254 | { 255 | Run "https://www.google.com/" 256 | } 257 | 258 | ^p:: 259 | { 260 | Run "notepad.exe" 261 | } 262 | 263 | ~j:: 264 | { 265 | Send "ack" 266 | } 267 | 268 | :*:acheiv::achiev 269 | ::achievment::achievement 270 | ::acquaintence::acquaintance 271 | :*:adquir::acquir 272 | ::aquisition::acquisition 273 | :*:agravat::aggravat 274 | :*:allign::align 275 | ::ameria::America276 |
The above code is perfectly acceptable. Multiple hotkeys, multiple hotstrings. All in one big happy script file.
277 | 278 |::btw::by the way ; Replaces "btw" with "by the way" as soon as you press a default ending character.280 |
:*:btw::by the way ; Replaces "btw" with "by the way" without needing an ending character.281 |
^n:: ; CTRL+N hotkey 282 | { 283 | Run "notepad.exe" ; Run Notepad when you press CTRL+N. 284 | } ; This ends the hotkey. The code below this will not be executed when pressing the hotkey.285 |
^b:: ; CTRL+B hotkey 286 | { 287 | Send "{Ctrl down}c{Ctrl up}" ; Copies the selected text. ^c could be used as well, but this method is more secure. 288 | SendInput "[b]{Ctrl down}v{Ctrl up}[/b]" ; Wraps the selected text in BBCode tags to make it bold in a forum. 289 | } ; This ends the hotkey. The code below this will not be executed when pressing the hotkey.290 | 291 |
So now you decided that you want to send (type) keys to a program. We can do that. Use the Send function. This function literally sends keystrokes, to simulate typing or pressing of keys.
293 |But before we get into things, we should talk about some common issues that people have.
294 |Just like hotkeys, the Send function has special keys too. Lots and lots of them. Here are the four most common symbols:
295 |Symbol | 298 |Description | 299 |
---|---|
! | 302 |Sends Alt. For example, Send "This is text!a" would send the keys "This is text" and then press Alt+A. Note: !A produces a different effect in some programs than !a . This is because !A presses Alt+Shift+A and !a presses Alt+A. If in doubt, use lowercase. |
303 |
+ | 306 |Sends Shift. For example, Send "+abC" would send the text "AbC", and Send "!+a" would press Alt+Shift+A. |
307 |
^ | 310 |Sends Ctrl. For example, Send "^!a" would press Ctrl+Alt+A, and Send "^{Home}" would send Ctrl+Home. Note: ^A produces a different effect in some programs than ^a . This is because ^A presses Ctrl+Shift+A and ^a presses Ctrl+A. If in doubt, use lowercase. |
311 |
# | 314 |Sends Win (the key with the Windows logo) therefore Send "#e" would hold down Win and then press E. |
315 |
The gigantic table on the Send page shows pretty much every special key built-in to AHK. For example: {Enter}
and {Space}
.
Caution: This table does not apply to hotkeys. Meaning, you do not wrap Ctrl or Enter (or any other key) inside curly brackets when making a hotkey.
319 |An example showing what shouldn't be done to a hotkey:
320 |; When making a hotkey... 321 | ; WRONG 322 | {LCtrl}:: 323 | { 324 | Send "AutoHotkey" 325 | } 326 | 327 | ; CORRECT 328 | LCtrl:: 329 | { 330 | Send "AutoHotkey" 331 | } 332 |333 |
A common issue lots of people have is, they assume that the curly brackets are put in the documentation pages just for fun. But in fact they are needed. It's how AHK knows that {!}
means "exclamation point" and not "press Alt". So please remember to check the table on the Send page and make sure you have your brackets in the right places. For example:
Send "This text has been typed{!}" ; Notice the ! between the curly brackets? That's because if it wasn't, AHK would press the ALT key. 335 |336 |
; Same as above, but with the ENTER key. AHK would type out "Enter" if 337 | ; it wasn't wrapped in curly brackets. 338 | Send "Multiple Enter lines have Enter been sent." ; WRONG 339 | Send "Multiple{Enter}lines have{Enter}been sent." ; CORRECT 340 |341 |
Another common issue is that people think that everything needs to be wrapped in brackets with the Send function. That is FALSE. If it's not in the chart, it does not need brackets. You do not need to wrap common letters, numbers or even some symbols such as .
(period) in curly brackets. Also, with the Send functions you are able to send more than one letter, number or symbol at a time. So no need for a bunch of Send functions with one letter each. For example:
Send "{a}" ; WRONG 343 | Send "{b}" ; WRONG 344 | Send "{c}" ; WRONG 345 | Send "{a}{b}{c}" ; WRONG 346 | Send "{abc}" ; WRONG 347 | Send "abc" ; CORRECT348 | 349 |
To hold down or release a key, enclose the key name in curly brackets and then use the word UP or DOWN. For example:
350 |; This is how you hold one key down and press another key (or keys). 351 | ; If one method doesn't work in your program, please try the other. 352 | Send "^s" ; Both of these send CTRL+S 353 | Send "{Ctrl down}s{Ctrl up}" ; Both of these send CTRL+S 354 | Send "{Ctrl down}c{Ctrl up}" 355 | Send "{b down}{b up}" 356 | Send "{Tab down}{Tab up}" 357 | Send "{Up down}" ; Press down the up-arrow key. 358 | Sleep 1000 ; Keep it down for one second. 359 | Send "{Up up}" ; Release the up-arrow key.360 | 361 |
But now you are wondering "How can I make my really long Send functions readable?". Easy. Use what is known as a continuation section. Simply specify an opening parenthesis on a new line, then your content, finally a closing parenthesis on its own line. For more information, read about Continuation Sections.
362 |Send " 363 | ( 364 | Line 1 365 | Line 2 366 | Apples are a fruit. 367 | )"368 |
Note: There are several different forms of Send. Each has their own special features. If one form of Send does not work for your needs, try another type of Send. Simply replace the function name "Send" with one of the following: SendText, SendInput, SendPlay, SendEvent. For more information on what each one does, read this.
369 | 370 |This is important: Some games, especially multiplayer games, use anti-cheat programs. Things like GameGuard, Hackshield, PunkBuster and several others. Not only is bypassing these systems in violation of the games policies and could get you banned, they are complex to work around.
372 |If a game has a cheat prevention system and your hotkeys, hotstrings and Send functions do not work, you are out of luck. However there are methods that can increase the chance of working in some games, but there is no magical "make it work in my game now!!!" button. So try all of these before giving up.
373 | 374 |There are also known issues with DirectX. If you are having issues and you know the game uses DirectX, try the stuff described on the FAQ page. More DirectX issues may occur when using PixelSearch, PixelGetColor or ImageSearch. Colors might turn out black (0x000000) no matter the color you try to get. You should also try running the game in windowed mode, if possible. That fixes some DirectX issues.
375 |There is no single solution to make AutoHotkey work in all programs. If everything you try fails, it may not be possible to use AutoHotkey for your needs.
376 | 377 |To run a program such as mspaint.exe, calc.exe, script.ahk or even a folder, you can use the Run function. It can even be used to open URLs such as https://www.autohotkey.com/. If your computer is setup to run the type of program you want to run, it's very simple:
379 |; Run a program. Note that most programs will require a FULL file path: 380 | Run A_ProgramFiles "\Some_Program\Program.exe" 381 | 382 | ; Run a website: 383 | Run "https://www.autohotkey.com"384 |
There are some other advanced features as well, such as command line parameters and CLSID. If you want to learn more about that stuff, visit the Run page.
385 |Here are a few more samples:
386 |; Several programs do not need a full path, such as Windows-standard programs: 387 | Run "notepad.exe" 388 | Run "mspaint.exe" 389 | 390 | ; Run the "My Documents" folder using a built-in variable: 391 | Run A_MyDocuments 392 | 393 | ; Run some websites: 394 | Run "https://www.autohotkey.com" 395 | Run "https://www.google.com"396 |
For more in-depth information and examples, check out the Run page.
397 | 398 |In AutoHotkey, function calls can be specified with or without parentheses. The parentheses are usually only necessary if the return value of the function is needed or the function name is not written at the start of the line.
400 |A list of all built-in functions can be found here.
401 |A typical function call looks like this:
402 |Function(Parameter1, Parameter2, Parameter3) ; with parentheses 403 | Function Parameter1, Parameter2, Parameter3 ; without parentheses404 |
The parameters support any kind of expression; this means for example:
405 |SubStr(37 * 12, 1, 2) 408 | SubStr(A_Hour - 12, 2)409 |
SubStr(A_AhkPath, InStr(A_AhkPath, "AutoHotkey"))412 |
SubStr("I'm scripting, awesome!", 16)415 |
The most common way assigning the return value of a function to a variable is like so:
419 |MyVar := SubStr("I'm scripting, awesome!", 16)
420 | This isn't the only way, but the most common. You are using MyVar
to store the return value of the function that is to the right of the :=
operator. See Functions for more details.
In short:
422 |; These are function calls without parentheses: 423 | MsgBox "This is some text." 424 | StrReplace Input, "AutoHotKey", "AutoHotkey" 425 | SendInput "This is awesome{!}{!}{!}" 426 | 427 | ; These are function calls with parentheses: 428 | SubStr("I'm scripting, awesome!", 16) 429 | FileExist(VariableContainingPath) 430 | Output := SubStr("I'm scripting, awesome!", 16)431 | 432 |
Code blocks are lines of code surrounded by little curly brackets ({
and }
). They group a section of code together so that AutoHotkey knows it's one big family and that it needs to stay together. They are most often used with functions and control flow statements such as If and Loop. Without them, only the first line in the block is called.
In the following code, both lines are run only if MyVar equals 5:
435 |if (MyVar = 5) 436 | { 437 | MsgBox "MyVar equals " MyVar "!!" 438 | ExitApp 439 | }440 |
In the following code, the message box is only shown if MyVar equals 5. The script will always exit, even if MyVar is not 5:
441 |if (MyVar = 5) 442 | MsgBox "MyVar equals " MyVar "!!" 443 | ExitApp444 |
This is perfectly fine since the if-statement only had one line of code associated with it. It's exactly the same as above, but I outdented the second line so we know it's separated from the if-statement:
445 |if (MyVar = 5) 446 | MsgBox "MyVar equals " MyVar "!!" 447 | MsgBox "We are now 'outside' of the if-statement. We did not need curly brackets since there was only one line below it."448 | 449 |
Variables are like little post-it notes that hold some information. They can be used to store text, numbers, data from functions or even mathematical equations. Without them, programming and scripting would be much more tedious.
451 |Variables can be assigned a few ways. We'll cover the most common forms. Please pay attention to the colon-equal operator (:=
).
MyVar := "Text"456 |
This is the simplest form for a variable. Simply type in your text and done. Any text needs to be in quotes.
457 |MyVar := MyVar2461 |
Same as above, but you are assigning a value of a variable to another variable.
462 |MyVar := 6 + 8 / 3 * 2 - Sqrt(9)466 |
Thanks to expressions, you can do math!
467 |MyVar := "The value of 5 + " MyVar2 " is: " 5 + MyVar2471 |
A combination of the three assignments above.
472 |Equal signs (=) with a symbol in front of it such as :=
+=
-=
.=
etc. are called assignment operators.
Sometimes you want to have the user to choose the value of stuff. There are several ways of doing this, but the simplest way is InputBox. Here is a simple example on how to ask the user a couple of questions and doing some stuff with what was entered:
478 |IB1 := InputBox("What is your first name?", "Question 1") 479 | if IB1.Value = "Bill" 480 | MsgBox "That's an awesome name, " IB1.Value "." 481 | 482 | IB2 := InputBox("Do you like AutoHotkey?", "Question 2") 483 | if IB2.Value = "yes" 484 | MsgBox "Thank you for answering " IB2.Value ", " IB1.Value "! We will become great friends." 485 | else 486 | MsgBox IB1.Value ", That makes me sad."487 | 488 |
Result := MsgBox("Would you like to continue?",, 4) 490 | if Result = "No" 491 | return ; If No, stop the code from going further. 492 | MsgBox "You pressed YES." ; Otherwise, the user picked yes.493 |
Var := "text" ; Assign some text to a variable. 494 | Num := 6 ; Assign a number to a variable. 495 | Var2 := Var ; Assign a variable to another. 496 | Var3 .= Var ; Append a variable to the end of another. 497 | Var4 += Num ; Add the value of a variable to another. 498 | Var4 -= Num ; Subtract the value of a variable from another. 499 | Var5 := SubStr(Var, 2, 2) ; Variable inside a function. 500 | Var6 := Var "Text" ; Assigns a variable to another with some extra text. 501 | MsgBox(Var) ; Variable inside a function. 502 | MsgBox Var ; Same as above. 503 | Var := StrSplit(Var, "x") ; Variable inside a function that uses InputVar and OutputVar. 504 | if (Num = 6) ; Check if a variable is equal to a number. 505 | if Num = 6 ; Same as above. 506 | if (Var != Num) ; Check if a variable is not equal to another. 507 | if Var1 < Var2 ; Check if a variable is lesser than another.508 |
Objects are a way of organizing your data for more efficient usage. An object is basically a collection of variables. A variable that belongs to an object is known as a "property". An object might also contain items, such as array elements.
510 |There are a number of reasons you might want to use an object for something. Some examples:
511 |There are a few ways to create an object, and the most common ones are listed below:
519 |MyArray := ["one", "two", "three", 17]523 |
This creates an Array, which represents a list of items, numbered 1 and up. In this example, the value "one"
is stored at index 1, and the value 17
is stored at index 4.
Banana := {Color: "Yellow", Taste: "Delicious", Price: 3}528 |
This creates an ad hoc Object. It is a quick way to create an object with a short set of known properties. In this example, the value "Yellow"
is stored in the Color property and the value 3
is stored in the Price property.
MyArray := Array("one", "two", "three", 17)533 |
This is equivalent to the bracket syntax. It is actually calling the Array class, not a function.
534 |MyMap := Map("^", "Ctrl", "!", "Alt")538 |
This creates a Map, or associative array. In this example, the value "Ctrl"
is associated with the key "^"
, and the value "Alt"
is associated with the key "!"
. Maps are often created empty with Map()
and later filled with items.
Banana := Fruit()543 |
Creates an object of the given class (Fruit in this case).
544 |There are many ways to use objects, including retrieving values, setting values, adding more values, and more.
549 | 550 |MyArray[2] := "TWO" 555 | MyMap["#"] := "Win"556 |
Setting array elements or items in a map or collection is similar to assigning a value to a variable. Simply append bracket notation to the variable which contains the object (array, map or whatever). The index or key between the brackets is an expression, so quote marks must be used for any non-numeric literal value.
557 |Banana.Consistency := "Mushy"561 |
This example assigns a new value to a property of the object contained by Banana. If the property doesn't already exist, it is created.
562 |Value := MyMap["^"]570 |
This example retrieves the value previously associated with (mapped to) the key "^"
. Often the key would be contained by a variable, such as MyMap[modifierChar]
.
Value := Banana.Color575 |
This example retrieves the Color property of the Banana object.
576 |MyMap["NewerKey"] := 3.1415584 |
To directly add a key and value, just set a key that doesn't exist yet. However, note that when assigning to an Array, the index must be within the range of 1 to the array's current length. Different objects may have different requirements.
585 |MyObject.NewProperty := "Shiny"589 |
As mentioned above, assigning to a property that hasn't already been defined will create a new property.
590 |MyArray.InsertAt(Index, Value1, Value2, Value3...)594 |
InsertAt is a method used to insert new values at a specific position within an Array, but other kinds of objects may also define a method by this name.
595 |MyArray.Push(Value1, Value2, Value3...)599 |
Push "appends" the values to the end of the Array MyArray. It is the preferred way to add new elements to an array, since the bracket notation can't be used to assign outside the current range of values.
600 |RemovedValue := MyObject.Delete(AnyKey)608 |
Array and Map have a Delete method, which removes the value from the array or map. The previous value of MyObject[AnyKey]
will be stored in RemovedValue. For an Array, this leaves the array element without a value and doesn't affect other elements in the array.
MyArray.Pop()613 |
This Array method removes the last element from an array and returns its value. The array's length is reduced by 1.
614 |RemovedValue := MyArray.RemoveAt(Index)618 |
MyArray.RemoveAt(Index, Length)619 |
Array has the RemoveAt method, which removes an array element or range of array elements. Elements (if any) to the right of the removed elements are shifted to the left to fill the vacated space.
620 |We have reached the end of our journey, my good friend. I hope you have learned something. But before we go, here are some other things that I think you should know. Enjoy!
625 | 626 |Throughout the documentation, you will see these two symbols ([
and ]
) surrounding code in the yellow syntax box at the top of almost all pages. Anything inside of these brackets are optional. Meaning the stuff inside can be left out if you don't need them. When writing your code, it is very important to not type the square brackets in your code.
On the ControlGetText page you will see this:
629 |Text := ControlGetText(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)630 |
So you could simply do this if you wanted:
631 |Text := ControlGetText(Control)632 |
Or add in some more details:
633 |Text := ControlGetText(Control, WinTitle)634 |
What if you wanted to use ExcludeTitle but not fill in WinText or WinTitle? Simple!
635 |Text := ControlGetText(Control,,, ExcludeTitle)636 |
Please note that you cannot IGNORE parameters, but you can leave them blank. If you were to ignore WinTitle, WinText
, it would look like this and cause issues:
Text := ControlGetText(Control, ExcludeTitle)638 | 639 |
Run this code to see your AHK version:
641 |MsgBox A_AhkVersion642 |
Or look for "AutoHotkey Help File" or "AutoHotkey.chm" in the start menu or your installation directory.
643 | 644 |Trial and Error is a very common and effective way of learning. Instead of asking for help on every little thing, sometimes spending some time alone (sometimes hours or days) and trying to get something to work will help you learn faster.
646 |If you try something and it gives you an error, study that error. Then try to fix your code. Then try running it again. If you still get an error, modify your code some more. Keep trying and failing until your code fails no more. You will learn a lot this way by reading the documentation, reading errors and learning what works and what doesn't. Try, fail, try, fail, try, try, try, fail, fail, succeed!
647 |This is how a lot of "pros" have learned. But don't be afraid to ask for help, we don't bite (hard). Learning takes time, the "pros" you encounter did not learn to be masters in just a few hours or days.
648 |"If at first you don't succeed, try, try, try again." - Hickson, William E.
649 |This stuff (indentation) is very important! Your code will run perfectly fine without it, but it will be a major headache for you and other to read your code. Small code (25 lines or less) will probably be fine to read without indentation, but it'll soon get sloppy. It's best you learn to indent ASAP. Indentation has no set style, but it's best to keep everything consistent.
651 |"What is indentation?" you ask? It's simply spacing to break up your code so you can see what belongs to what. People usually use 3 or 4 spaces or 1 tab per "level".
652 |Not indented:
653 |if (car = "old") 654 | { 655 | MsgBox "The car is really old." 656 | if (wheels = "flat") 657 | { 658 | MsgBox "This car is not safe to drive." 659 | return 660 | } 661 | else 662 | { 663 | MsgBox "Be careful! This old car will be dangerous to drive." 664 | } 665 | } 666 | else 667 | { 668 | MsgBox "My, what a shiny new vehicle you have there." 669 | }670 |
Indented:
671 | 672 |if (car = "old") 673 | { 674 | MsgBox "The car is really old." 675 | if (wheels = "flat") 676 | { 677 | MsgBox "This car is not safe to drive." 678 | return 679 | } 680 | else 681 | { 682 | MsgBox "Be careful! This old car will be dangerous to drive." 683 | } 684 | } 685 | else 686 | { 687 | MsgBox "My, what a shiny new vehicle you have there." 688 | }689 |
See Wikipedia's Indentation style page for various styles and examples. Choose what you like or learn to indent how you think it's easiest to read.
690 | 691 |Before you ask, try doing some research yourself or try to code it yourself. If that did not yield results that satisfy you, read below.
693 |If you don't get an answer right away, wait at least 1 day (24 hours) before asking for more help. We love to help, but we also do this for free on our own time. We might be at work, sleeping, gaming, with family or just too busy to help.
705 |And while you wait for help, you can try learning and doing it yourself. It's a good feeling, making something yourself without help.
706 | 707 |Frequently Asked Questions (FAQ)
709 | 710 | 711 | -------------------------------------------------------------------------------- /docs/Variables.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |See Variables for general explanation and details about how variables work.
25 |Storing values in variables: To store a string or number in a variable, use the colon-equal operator (:=) followed by a number, quoted string or any other type of expression. For example:
26 |MyNumber := 123 27 | MyString := "This is a literal string." 28 | CopyOfVar := Var29 |
A variable cannot be explicitly deleted, but its previous value can be released by assigning a new value, such as an empty string:
30 |MyVar := ""31 |
A variable can also be assigned a value indirectly, by taking its reference and using a double-deref or passing it to a function. For example:
32 |MouseGetPos &x, &y33 |
Reading the value of a variable which has not been assigned a value is considered an error. IsSet can be used to detect this condition.
34 |Retrieving the contents of variables: To include the contents of a variable in a string, use concatenation or Format. For example:
35 |MsgBox "The value of Var is " . Var . "." 36 | MsgBox "The value in the variable named Var is " Var "." 37 | MsgBox Format("Var has the value {1}.", Var) 38 |39 |
Sub-expressions can be combined with strings in the same way. For example:
40 |MsgBox("The sum of X and Y is " . (X + Y)) 41 |42 |
Comparing variables: Please read the expressions section below for important notes about the different kinds of comparisons.
43 |See Expressions for a structured overview and further explanation.
45 |Expressions are used to perform one or more operations upon a series of variables, literal strings, and/or literal numbers.
46 |Plain words in expressions are interpreted as variable names. Consequently, literal strings must be enclosed in double quotes to distinguish them from variables. For example:
47 |if (CurrentSetting > 100 or FoundColor != "Blue") 48 | MsgBox "The setting is too high or the wrong color is present."49 |
In the example above, "Blue" appears in quotes because it is a literal string. Single-quote marks (') and double-quote marks (") function identically, except that a string enclosed in single-quote marks can contain literal double-quote marks and vice versa. Therefore, to include an actual quote mark inside a literal string, escape the quote mark or enclose the string in the opposite type of quote mark. For example:
50 |MsgBox "She said, `"An apple a day.`"" 51 | MsgBox 'She said, "An apple a day."'52 |
Empty strings: To specify an empty string in an expression, use an empty pair of quotes. For example, the statement if (MyVar != "")
would be true if MyVar is not blank.
Storing the result of an expression: To assign a result to a variable, use the colon-equal operator (:=). For example:
54 |NetPrice := Price * (1 - Discount/100)55 |
Boolean values: When an expression is required to evaluate to true or false (such as an IF-statement), a blank or zero result is considered false and all other results are considered true. For example, the statement if ItemCount
would be false only if ItemCount is blank or 0. Similarly, the expression if not ItemCount
would yield the opposite result.
Operators such as NOT/>/=/< automatically produce a true or false value: they yield 1 for true and 0 for false. However, the AND/OR operators always produce one of the input values. For example, in the following expression, the variable Done is assigned 1 if A_Index is greater than 5 or the value of FoundIt in all other cases:
57 |Done := A_Index > 5 or FoundIt58 |
As hinted above, a variable can be used to hold a false value simply by making it blank or assigning 0 to it. To take advantage of this, the shorthand statement if Done
can be used to check whether the variable Done is true or false.
In an expression, the keywords true and false resolve to 1 and 0. They can be used to make a script more readable as in these examples:
60 |CaseSensitive := false 61 | ContinueSearch := true62 |
Integers and floating point: Within an expression, numbers are considered to be floating point if they contain a decimal point or scientific notation; otherwise, they are integers. For most operators -- such as addition and multiplication -- if either of the inputs is a floating point number, the result will also be a floating point number.
63 |Within expressions and non-expressions alike, integers may be written in either hexadecimal or decimal format. Hexadecimal numbers all start with the prefix 0x. For example, Sleep 0xFF
is equivalent to Sleep 255
. Floating point numbers can optionally be written in scientific notation, with or without a decimal point (e.g. 1e4
or -2.1E-4
).
Within expressions, unquoted literal numbers such as 128
, 0x7F
and 1.0
are converted to pure numbers before the script begins executing, so converting the number to a string may produce a value different to the original literal value. For example:
MsgBox(0x7F) ; Shows 128 66 | MsgBox(1.00) ; Shows 1.067 | 68 |
See Operators for general information about operators.
70 |Except where noted below, any blank value (empty string) or non-numeric value involved in a math operation is not assumed to be zero. Instead, a TypeError is thrown. If Try is not used, the unhandled exception causes an error dialog by default.
71 | 72 |Operator | 76 |Description | 77 |
---|---|
%Expr% | 80 |
81 | Dereference or name substitution. 82 |When Expr evaluates to a VarRef, Otherwise, the value of the sub-expression Expr is used as the name or partial name of a variable or property. This allows the script to refer to a variable or property whose name is determined by evaluating Expr, which is typically another variable. Variables cannot be created dynamically, but a variable can be assigned dynamically if it has been declared or referenced non-dynamically somewhere in the script. 84 |Note: The result of the sub-expression Expr must be the name or partial name of the variable or property to be accessed. 85 |Percent signs cannot be used directly within Expr due to ambiguity, but can be nested within parentheses. Otherwise, Expr can be any expression. 86 |If there are any adjoining %Expr% sequences and partial names (without any spaces or other characters between them), they are combined to form a single name. 87 |An Error is typically thrown if the variable does not already exist, or if it is uninitialized and its value is being read. The or-maybe operator (??) can be used to avoid that case by providing a default value. For example: Although this is historically known as a "double-deref", this term is inaccurate when Expr does not contain a variable (first deref), and also when the resulting variable is the target of an assignment, not being dereferenced (second deref). 89 | |
90 |
x.y x.%z% |
93 | Member access. Get or set a value or call a method of object x, where y is a literal name and z is an expression which evaluates to a name. See object syntax. | 94 |
var? | 97 |
98 | Maybe. Permits the variable to be unset. This is valid only when passing a variable to an optional parameter, array element or object literal; or on the right-hand side of a direct assignment. The question mark must be followed by one of the following symbols (ignoring whitespace): The variable is typically an optional parameter, but can be any variable. For variables that are not function parameters, a VarUnset warning may still be shown at load-time if there are other references to the variable but no assignments. 100 |This operator is currently supported only for variables. To explicitly or conditionally omit a parameter in more general cases, use the See also: unset (Optional Parameters) 102 | |
103 |
++ 106 | -- |
107 |
108 | Pre- and post-increment/decrement. Adds or subtracts 1 from a variable. The operator may appear either before or after the variable's name. If it appears before the name, the operation is performed and its result is used by the next operation (the result is a variable reference in this case). For example, These operators can also be used with a property of an object, such as |
111 |
** | 114 |
115 | Power. Example usage: The power operator is right-associative. For example, Note: A negative Base combined with a fractional Exponent such as |
119 |
- 122 | ! 123 | ~ 124 | & |
125 |
126 | Unary minus (-): Inverts the sign of its operand. 127 |Unary plus (+): Logical-not (!): If the operand is blank or 0, the result of applying logical-not is 1, which means "true". Otherwise, the result is 0 (false). For example: Bitwise-not (~): This inverts each bit of its operand. As 64-bit signed integers are used, a positive input value will always give a negative result and vice versa. For example, Reference (&): Creates a VarRef, which is a value representing a reference to a variable. A VarRef can then be used to indirectly access the target variable. For example, Taking a reference to a built-in variable such as A_Clipboard is currently not supported, except when being passed directly to an OutputVar parameter of a built-in function. 132 | |
133 |
* 136 | / 137 | // 138 | |
139 | Multiply (*): The result is an integer if both inputs are integers; otherwise, it is a floating point number. 140 |Other uses: The asterisk (*) symbol is also used in variadic function calls. 141 |True divide (/): True division yields a floating point result even when both inputs are integers. For example, Integer divide (//): The double-slash operator uses high-performance integer division. For example, The *= and /= operators are a shorthand way to multiply or divide the value in a variable by another value. For example, Division by zero causes a ZeroDivisionError to be thrown. |
145 |
+ 148 | - |
149 | Add (+) and subtract (-). On a related note, the += and -= operators are a shorthand way to increment or decrement a variable. For example, Other uses: If the + or - symbol is not preceded by a value (or a sub-expression which yields a value), it is interpreted as a unary operator instead. 151 | |
152 |
<< 155 | >> 156 | >>> |
157 |
158 | Bit shift left (<<). Example usage: Arithmetic bit shift right (>>). Example usage: Logical bit shift right (>>>). Example usage: The following applies to all three operators: 162 |
|
168 |
& 171 | ^ 172 | | 173 | |
174 |
175 | Bitwise-and (&), bitwise-exclusive-or (^), and bitwise-or (|). Of the three, & has the highest precedence and | has the lowest. 176 |The following applies to all three operators: 177 |
Related: Bitwise-not (~) 182 | |
183 |
. | 186 |
187 | Concatenate. A period (dot) with at least one space or tab on each side is used to combine two items into a single string. You may also omit the period to achieve the same result (except where ambiguous such as Var := "The color is " . FoundColor ; Explicit concat 189 | Var := "The color is " FoundColor ; Auto-concat 190 |191 | Sub-expressions can also be concatenated. For example: A line that begins with a period (or any other operator) is automatically appended to the line above it. 193 |The entire length of each input is used, even if it includes binary zero. For example, Other uses: If there is no space or tab to the right of a period (dot), it is interpreted as either a literal floating-point number or member access. For example, |
196 |
~= | 199 |Shorthand for RegExMatch. For example, the result of "abc123" ~= "\d" is 4 (the position of the first numeric character). |
200 |
> < 203 | >= <= |
204 |
205 | Greater (>), less (<), greater-or-equal (>=), and less-or-equal (<=). The inputs are compared numerically. A TypeError is thrown if either of the inputs is not a number or a numeric string. 206 | |
207 |
= 210 | == 211 | != 212 | !== |
213 |
214 | Case-insensitive equal (=) / not-equal (!=) and case-sensitive equal (==) / not-equal (!==). The == operator behaves identically to = except when either of the inputs is not numeric (or both are strings), in which case == is always case-sensitive and = is always case-insensitive. The != and !== behave identically to their counterparts without !, except that the result is inverted. 215 |The == and !== operators can be used to compare strings which contain binary zero. All other comparison operators except ~= compare only up to the first binary zero. 216 |For case-insensitive comparisons, only the ASCII letters A-Z are considered equivalent to their lowercase counterparts. To instead compare according to the rules of the current user's locale, use StrCompare and specify "Locale" for the CaseSense parameter. 217 | |
218 |
IS IN CONTAINS |
221 |
222 |
|
225 |
NOT | 228 |Logical-NOT. Except for its lower precedence, this is the same as the ! operator. For example, not (x = 3 or y = 3) is the same as !(x = 3 or y = 3) . |
229 |
AND 232 | && |
233 | Both of these are logical-AND. For example: In an expression where all operands are true, the last operand is returned. Otherwise, the first operand that is false is returned. In other words, the result is true only if all operands are true. Boolean expressions are subject to short-circuit evaluation (from left to right) to improve performance. 235 |In the following example, all operands are true and will be evaluated: 236 |A := 1, B := {}, C := 20, D := true, E := "str" 237 | MsgBox(A && B && C && D && E) ; Shows "str" (E).238 | In the following example, only the first two operands will be evaluated because B is false. The rest is ignored, i.e. C is not incremented either: 239 |A := 1, B := "", C := 0, D := false, E := "str" 240 | MsgBox(A && B && ++C && D && E) ; Shows "" (B).241 | A line that begins with |
242 |
OR 245 | || |
246 | Both of these are logical-OR. For example: In an expression where at least one operand is true, the first operand that is true is returned. Otherwise, the last operand that is false is returned. In other words, if at least one operand is true, the result is true. Boolean expressions are subject to short-circuit evaluation (from left to right) to improve performance. 248 |In the following example, at least one operand is true. All operands up to D will be evaluated. E is ignored and will never be incremented: 249 |A := "", B := false, C := 0, D := "str", E := 20 250 | MsgBox(A || B || C || D || ++E) ; Shows "str" (D).251 | In the following example, all operands are false and will be evaluated: 252 |A := "", B := false, C := 0 253 | MsgBox(A || B || C) ; Shows "0" (C).254 | A line that begins with |
255 |
?? | 258 |
259 | Or maybe, otherwise known as the coalescing operator. If the left operand (which must be a variable) has a value, it becomes the result and the right branch is skipped. Otherwise, the right operand becomes the result. In other words, This is typically used to provide a default value when it is known that a variable or optional parameter might not already have a value. For example: 261 |MsgBox MyVar ?? "Default value"262 | Since the variable is expected to sometimes be uninitialized, no error is thrown in that case. Unlike |
264 |
?: | 267 |
268 | Ternary operator. This operator is a shorthand replacement for the if-else statement. It evaluates the condition on its left side to determine which of its two branches should become its final result. For example, See also: maybe (var?), or-maybe (??) 270 |Note: When used at the beginning of a line, the ternary condition should usually be enclosed in parentheses to reduce ambiguity with other types of statements. For details, see Expression Statements. 271 | |
272 |
:= 275 | += 276 | -= 277 | *= 278 | /= 279 | //= 280 | .= 281 | |= 282 | &= 283 | ^= 284 | >>= 285 | <<= 286 | >>>= 287 | |
288 | Assign. Performs an operation on the contents of a variable and stores the result back in the same variable. The simplest assignment operator is colon-equal (:=), which stores the result of an expression in a variable. For a description of what the other operators do, see their related entries in this table. For example, Unlike most other operators, assignments are evaluated from right to left. Consequently, a line such as If an assignment is used as the input for some other operator, its value is the variable itself. For example, the expression The precedence of the assignment operators is automatically raised when it would avoid a syntax error or provide more intuitive behavior. For example: The target variable can be un-set by combining a direct assignment ( An assignment can also target a property of an object, such as |
295 |
() => expr | 298 |
299 | Fat arrow function. Defines a simple function and returns a Func or Closure object. Write the function's parameter list (optionally preceded by a function name) to the left of the operator. When the function is called (via the returned reference), it evaluates the sub-expression expr and returns the result. 300 |The following two examples are equivalent: 301 |sumfn := Sum(a, b) => a + b302 | Sum(a, b) { 303 | return a + b 304 | } 305 | sumfn := Sum306 | In both cases, the function is defined unconditionally at the moment the script launches, but the function reference is stored in sumfn only if and when the assignment is evaluated. 307 |If the function name is omitted and the parameter list consists of only a single parameter name, the parentheses can be omitted. The example below defines an anonymous function with one parameter double := a => a * 2309 | Variable references in expr are resolved in the same way as in the equivalent full function definition. For instance, expr may refer to an outer function's local variables (as in any nested function), in which case a new closure is created and returned each time the fat arrow expression is evaluated. The function is always assume-local, since declarations cannot be used. 310 |Specifying a name for the function allows it to be called recursively or by other nested functions without storing a reference to the closure within itself (thereby creating a problematic circular reference). It can also be helpful for debugging, such as with Func.Name or when displayed on the debugger's call stack. 311 |Fat arrow syntax can also be used to define shorthand properties and methods. 312 | |
313 |
314 |
, | 317 |Comma (multi-statement). Commas may be used to write multiple sub-expressions on a single line. This is most commonly used to group together multiple assignments or function calls. For example: Note: A line that begins with a comma (or any other operator) is automatically appended to the line above it. 319 |Comma is also used to delimit the parameters of a function call or control flow statement. To include a multi-statement expression in a parameter list, enclose it in an extra set of parentheses. For example, |
321 |
The following types of sub-expressions override precedence/order of evaluation:
324 |Expression | 327 |Description | 328 |
---|---|
(expression) | 331 |
332 | Any sub-expression enclosed in parentheses. For example, For a multi-statement expression, the result of the last statement is returned. For example, |
335 |
Mod() |
340 | Function call. There must be no space between the function name or expression and the open parenthesis which begins the parameter list. For details, see Function Calls. 341 |(expression) is not necessarily required to be enclosed in parentheses, but doing so may eliminate ambiguity. For example, |
343 |
(expression)() |
346 | |
Fn(Params*) | 349 |Variadic function call. Params is an enumerable object (an object with an __Enum method), such as an Array containing parameter values. |
350 |
x[y] [a, b, c] |
353 |
354 | Item access. Get or set the __Item property (or default property) of object x with the parameter y (or multiple parameters in place of y). This typically corresponds to an array element or item within a collection, where y is the item's index or key. The item can be assigned a value by using any assignment operator immediately after the closing bracket. For example, Array literal. If the open-bracket is not preceded by a value (or a sub-expression which yields a value), it is interpreted as the beginning of an array literal. For example, |
358 |
{a: b, c: d} | 361 |
362 | Object literal. Create an Object. Each pair consists of a literal property name To use a dynamic property name, enclose the sub-expression in percent signs. For example: |
365 |
The variables below are built into the program and can be referenced by any script.
370 |See Built-in Variables for general information.
371 |Variable | 387 |Description | 388 |
---|---|
A_Space | 391 |Contains a single space character. | 392 |
A_Tab | 395 |Contains a single tab character. | 396 |
Variable | 402 |Description | 403 |
---|---|
A_Args | 406 |Contains an array of command line parameters. For details, see Passing Command Line Parameters to a Script. | 407 |
A_WorkingDir | 410 |Can be used to get or set the script's current working directory, which is where files will be accessed by default. The final backslash is not included unless it is the root directory. Two examples: C:\ and C:\My Documents. 411 |SetWorkingDir can also be used to change the working directory. 412 |The script's working directory defaults to A_ScriptDir, regardless of how the script was launched. |
413 |
A_InitialWorkingDir | 416 |The script's initial working directory, which is determined by how it was launched. For example, if it was run via shortcut -- such as on the Start Menu -- its initial working directory is determined by the "Start in" field within the shortcut's properties. | 417 |
A_ScriptDir | 420 |
421 | The full path of the directory where the current script is located. The final backslash is omitted (even for root directories). 422 |If the script text is read from stdin rather than from file, this variable contains the initial working directory. |
423 |
A_ScriptName | 426 |
427 | Can be used to get or set the default title for MsgBox, InputBox, FileSelect, DirSelect and Gui. If not set by the script, it defaults to the file name of the current script, without its path, e.g. MyScript.ahk. 428 |If the script text is read from stdin rather than from file, this variable contains an asterisk (*). 429 |If the script is compiled or embedded, this is the name of the current executable file. 430 | |
431 |
A_ScriptFullPath | 434 |
435 | The full path of the current script, e.g. C:\Scripts\My Script.ahk 436 |If the script text is read from stdin rather than from file, this variable contains an asterisk (*). 437 |If the script is compiled or embedded, this is the full path of the current executable file. 438 | |
439 |
A_ScriptHwnd | 442 |The unique ID (HWND/handle) of the script's hidden main window. | 443 |
A_LineNumber | 446 |The number of the currently executing line within the script (or one of its #Include files). This line number will match the one shown by ListLines; it can be useful for error reporting such as this example: Since a compiled script has merged all its #Include files into one big script, its line numbering may be different than when it is run in non-compiled mode. |
448 |
A_LineFile | 451 |
452 | The full path and name of the file to which A_LineNumber belongs. If the script was loaded from an external file, this is the same as A_ScriptFullPath unless the line belongs to one of the script's #Include files. 453 |If the script was compiled based on a .bin file, this is the full path and name of the current executable file, the same as A_ScriptFullPath. 454 |If the script is embedded, A_LineFile contains an asterisk (*) followed by the resource name; e.g. *#1 455 | |
456 |
A_ThisFunc | 459 |The name of the user-defined function that is currently executing (blank if none); for example: MyFunction. See also: Name property (Func) | 460 |
A_AhkVersion | 463 |Contains the version of AutoHotkey that is running the script, such as 1.0.22. In the case of a compiled script, the version that was originally used to compile it is reported. The formatting of the version number allows a script to check whether A_AhkVersion is greater than some minimum version number with > or >= as in this example: if (A_AhkVersion >= "1.0.25.07") . See also: #Requires and VerCompare |
464 |
A_AhkPath | 467 |
468 | For non-compiled or embedded scripts: The full path and name of the EXE file that is actually running the current script. For example: C:\Program Files\AutoHotkey\AutoHotkey.exe 469 |For compiled scripts based on a .bin file, the value is determined by reading the installation directory from the registry and appending "\AutoHotkey.exe". If AutoHotkey is not installed, the value is blank. The example below is equivalent: 470 |InstallDir := RegRead("HKLM\SOFTWARE\AutoHotkey", "InstallDir", "") 471 | AhkPath := InstallDir ? InstallDir "\AutoHotkey.exe" : ""472 | For compiled scripts based on an .exe file, A_AhkPath contains the full path of the compiled script. This can be used in combination with /script to execute external scripts. To instead locate the installed copy of AutoHotkey, read the registry as shown above. 473 | |
474 |
A_IsCompiled | 477 |Contains 1 if the script is running as a compiled EXE and 0 (which is considered false) if it is not. | 478 |
Variable | 484 |Description | 485 |
---|---|
A_YYYY | 488 |
489 | Current 4-digit year (e.g. 2004). Synonymous with A_Year. 490 |Note: To retrieve a formatted time or date appropriate for your locale and language, use |
492 |
A_MM | 495 |Current 2-digit month (01-12). Synonymous with A_Mon. | 496 |
A_DD | 499 |Current 2-digit day of the month (01-31). Synonymous with A_MDay. | 500 |
A_MMMM | 503 |Current month's full name in the current user's language, e.g. July | 504 |
A_MMM | 507 |Current month's abbreviation in the current user's language, e.g. Jul | 508 |
A_DDDD | 511 |Current day of the week's full name in the current user's language, e.g. Sunday | 512 |
A_DDD | 515 |Current day of the week's abbreviation in the current user's language, e.g. Sun | 516 |
A_WDay | 519 |Current 1-digit day of the week (1-7). 1 is Sunday in all locales. | 520 |
A_YDay | 523 |Current day of the year (1-366). The value is not zero-padded, e.g. 9 is retrieved, not 009. To retrieve a zero-padded value, use the following: FormatTime(, "YDay0") . |
524 |
A_YWeek | 527 |Current year and week number (e.g. 200453) according to ISO 8601. To separate the year from the week, use Year := SubStr(A_YWeek, 1, 4) and Week := SubStr(A_YWeek, -2) . Precise definition of A_YWeek: If the week containing January 1st has four or more days in the new year, it is considered week 1. Otherwise, it is the last week of the previous year, and the next week is week 1. |
528 |
A_Hour | 531 |Current 2-digit hour (00-23) in 24-hour time (for example, 17 is 5pm). To retrieve 12-hour time as well as an AM/PM indicator, follow this example: FormatTime(, "h:mm:ss tt") |
532 |
A_Min | 535 |Current 2-digit minute (00-59). |
536 |
A_Sec | 539 |Current 2-digit second (00-59). | 540 |
A_MSec | 543 |Current 3-digit millisecond (000-999). To remove the leading zeros, follow this example: Milliseconds := A_MSec + 0 . |
544 |
A_Now | 547 |
548 | The current local time in YYYYMMDDHH24MISS format. 549 |Note: Date and time math can be performed with DateAdd and DateDiff. Also, FormatTime can format the date and/or time according to your locale or preferences. 550 | |
551 |
A_NowUTC | 554 |The current Coordinated Universal Time (UTC) in YYYYMMDDHH24MISS format. UTC is essentially the same as Greenwich Mean Time (GMT). | 555 |
A_TickCount | 558 |The number of milliseconds that have elapsed since the system was started, up to 49.7 days. By storing A_TickCount in a variable, elapsed time can later be measured by subtracting that variable from the latest A_TickCount value. For example: 559 |StartTime := A_TickCount 560 | Sleep 1000 561 | ElapsedTime := A_TickCount - StartTime 562 | MsgBox ElapsedTime " milliseconds have elapsed."563 | If you need more precision than A_TickCount's 10 ms, use QueryPerformanceCounter(). 564 | |
565 |
Variable | 571 |Description | 572 |
---|---|
A_IsSuspended | 575 |Contains 1 if the script is suspended, otherwise 0. | 576 |
A_IsPaused | 579 |Contains 1 if the thread immediately underneath the current thread is paused, otherwise 0. | 580 |
A_IsCritical | 583 |Contains 0 if Critical is off for the current thread. Otherwise it contains an integer greater than zero, namely the message-check interval being used by Critical. The current state of Critical can be saved and restored via Old_IsCritical := A_IsCritical followed later by Critical Old_IsCritical . |
584 |
A_ListLines | 587 |Can be used to get or set whether to log lines. Possible values are 0 (disabled) and 1 (enabled). For details, see ListLines. | 588 |
A_TitleMatchMode | 591 |Can be used to get or set the title match mode. Possible values are 1, 2, 3, and RegEx. For details, see SetTitleMatchMode. | 592 |
A_TitleMatchModeSpeed | 595 |Can be used to get or set the title match speed. Possible values are Fast and Slow. For details, see SetTitleMatchMode. | 596 |
A_DetectHiddenWindows | 599 |Can be used to get or set whether to detect hidden windows. Possible values are 0 (disabled) and 1 (enabled). For details, see DetectHiddenWindows. | 600 |
A_DetectHiddenText | 603 |Can be used to get or set whether to detect hidden text in a window. Possible values are 0 (disabled) and 1 (enabled). For details, see DetectHiddenText. | 604 |
A_FileEncoding | 607 |Can be used to get or set the default encoding for various built-in functions. For details, see FileEncoding. | 608 |
A_SendMode | 611 |Can be used to get or set the send mode. Possible values are Event, Input, Play, and InputThenPlay. For details, see SendMode. | 612 |
A_SendLevel | 615 |Can be used to get or set the send level, an integer from 0 to 100. For details, see SendLevel. | 616 |
A_StoreCapsLockMode | 619 |Can be used to get or set whether to restore the state of CapsLock after a Send. Possible values are 0 (disabled) and 1 (enabled). For details, see SetStoreCapsLockMode. | 620 |
A_KeyDelay 623 | A_KeyDuration |
624 | Can be used to get or set the delay or duration for keystrokes, in milliseconds. For details, see SetKeyDelay. | 625 |
A_KeyDelayPlay 628 | A_KeyDurationPlay |
629 | Can be used to get or set the delay or duration for keystrokes sent via SendPlay mode, in milliseconds. For details, see SetKeyDelay. | 630 |
A_WinDelay | 633 |Can be used to get or set the delay for windowing functions, in milliseconds. For details, see SetWinDelay. | 634 |
A_ControlDelay | 637 |Can be used to get or set the delay for control-modifying functions, in milliseconds. For details, see SetControlDelay. | 638 |
A_MenuMaskKey | 641 |Controls which key is used to mask Win or Alt keyup events. For details, see A_MenuMaskKey. | 642 |
A_MouseDelay 645 | A_MouseDelayPlay |
646 | Can be used to get or set the mouse delay, in milliseconds. A_MouseDelay is for the traditional SendEvent mode, whereas A_MouseDelayPlay is for SendPlay. For details, see SetMouseDelay. | 647 |
A_DefaultMouseSpeed | 650 |Can be used to get or set the default mouse speed, an integer from 0 (fastest) to 100 (slowest). For details, see SetDefaultMouseSpeed. | 651 |
A_CoordModeToolTip 654 | A_CoordModePixel 655 | A_CoordModeMouse 656 | A_CoordModeCaret 657 | A_CoordModeMenu |
658 | Can be used to get or set the area to which coordinates are to be relative. Possible values are Screen, Window, and Client. For details, see CoordMode. | 659 |
A_RegView | 662 |Can be used to get or set the registry view. Possible values are 32, 64 and Default. For details, see SetRegView. | 663 |
A_TrayMenu | 666 |Returns a Menu object which can be used to modify or display the tray menu. |
667 |
A_AllowMainWindow | 670 |Can be used to get or set whether the script's main window is allowed to be opened via the tray icon. Possible values are 0 (forbidden) and 1 (allowed). 671 |If the script is neither compiled nor embedded, this variable defaults to 1, otherwise this variable defaults to 0 but can be overridden by assigning it a value. Setting it to 1 also restores the "Open" menu item to the tray menu and enables the items in the main window's View menu such as "Lines most recently executed", which allows viewing of the script's source code and other info. 672 |The following functions are always able to show the main window and select the corresponding View options when they are encountered in the script at runtime: ListLines, ListVars, ListHotkeys, and KeyHistory. 673 |Setting it to 1 does not prevent the main window from being shown by WinShow or inspected by ControlGetText or similar methods, but it does prevent the script's source code and other info from being exposed via the main window, except when one of the functions listed above is called by the script. |
674 |
A_IconHidden | 677 |Can be used to get or set whether to hide the tray icon. Possible values are 0 (visible) and 1 (hidden). For details, see #NoTrayIcon. | 678 |
A_IconTip | 681 |Can be used to get or set the tray icon's tooltip text, which is displayed when the mouse hovers over it. If blank, the script's name is used instead. 682 |To create a multi-line tooltip, use the linefeed character (`n) in between each line, e.g. On Windows 10 and earlier, to display tooltip text containing ampersands (&), escape each ampersand with two additional ampersands. For example, assigning |
684 |
A_IconFile | 687 |Blank unless a custom tray icon has been specified via TraySetIcon -- in which case it is the full path and name of the icon's file. | 688 |
A_IconNumber | 691 |Blank if A_IconFile is blank. Otherwise, it's the number of the icon in A_IconFile (typically 1). | 692 |
Variable | 698 |Description | 699 |
---|---|
A_TimeIdle | 702 |
703 | The number of milliseconds that have elapsed since the system last received keyboard, mouse, or other input. This is useful for determining whether the user is away. Physical input from the user as well as artificial input generated by any program or script (such as the Send or MouseMove functions) will reset this value back to zero. Since this value tends to increase by increments of 10, do not check whether it is equal to another value. Instead, check whether it is greater or less than another value. For example: 704 |if A_TimeIdle > 600000 705 | MsgBox "Last activity was 10 minutes ago"706 | |
707 |
A_TimeIdlePhysical | 710 |Similar to above but ignores artificial keystrokes and/or mouse clicks whenever the corresponding hook (keyboard or mouse) is installed; that is, it responds only to physical events. (This prevents simulated keystrokes and mouse clicks from falsely indicating that a user is present.) If neither hook is installed, this variable is equivalent to A_TimeIdle. If only one hook is installed, only its type of physical input affects A_TimeIdlePhysical (the other/non-installed hook's input, both physical and artificial, has no effect). | 711 |
A_TimeIdleKeyboard | 714 |If the keyboard hook is installed, this is the number of milliseconds that have elapsed since the system last received physical keyboard input. Otherwise, this variable is equivalent to A_TimeIdle. | 715 |
A_TimeIdleMouse | 718 |If the mouse hook is installed, this is the number of milliseconds that have elapsed since the system last received physical mouse input. Otherwise, this variable is equivalent to A_TimeIdle. | 719 |
Variable | 725 |Description | 726 |
---|---|
A_ThisHotkey | 729 |The most recently executed hotkey or non-auto-replace hotstring (blank if none), e.g. #z. This value will change if the current thread is interrupted by another hotkey or hotstring, so it is generally better to use the parameter ThisHotkey when available. 730 |When a hotkey is first created -- either by the Hotkey function or the double-colon syntax in the script -- its key name and the ordering of its modifier symbols becomes the permanent name of that hotkey, shared by all variants of the hotkey. 731 |When a hotstring is first created -- either by the Hotstring function or a double-colon label in the script -- its trigger string and sequence of option characters becomes the permanent name of that hotstring. 732 | |
733 |
A_PriorHotkey | 736 |Same as above except for the previous hotkey. It will be blank if none. | 737 |
A_PriorKey | 740 |The name of the last key which was pressed prior to the most recent key-press or key-release, or blank if no applicable key-press can be found in the key history. All input generated by AutoHotkey scripts is excluded. For this variable to be of use, the keyboard or mouse hook must be installed and key history must be enabled. | 741 |
A_TimeSinceThisHotkey | 744 |The number of milliseconds that have elapsed since A_ThisHotkey was pressed. It will be blank whenever A_ThisHotkey is blank. | 745 |
A_TimeSincePriorHotkey | 748 |The number of milliseconds that have elapsed since A_PriorHotkey was pressed. It will be blank whenever A_PriorHotkey is blank. | 749 |
A_EndChar | 752 |The ending character that was pressed by the user to trigger the most recent non-auto-replace hotstring. If no ending character was required (due to the * option), this variable will be blank. | 753 |
A_MaxHotkeysPerInterval | 756 |Can be used to get or set the maximum number of hotkeys that can be pressed within the interval defined by A_HotkeyInterval without triggering a warning dialog. For details, see A_MaxHotkeysPerInterval. | 757 |
A_HotkeyInterval | 760 |Can be used to get or set the length of the interval used by A_MaxHotkeysPerInterval, in milliseconds. | 761 |
A_HotkeyModifierTimeout | 764 |Can be used to get or set the timeout affecting the behavior of Send with hotkey modifiers Ctrl, Alt, Win, and Shift. For details, see A_HotkeyModifierTimeout. | 765 |
Variable | 771 |Description | 772 |
---|---|
A_ComSpec | 775 |Contains the same string as the ComSpec environment variable, which is usually the full path to the command prompt executable (cmd.exe). Often used with Run/RunWait. For example: 776 |C:\Windows\system32\cmd.exe777 | |
778 |
A_Temp | 781 |The full path and name of the folder designated to hold temporary files. It is retrieved from one of the following locations (in order): 1) the environment variables TMP, TEMP, or USERPROFILE; 2) the Windows directory. For example: 782 |C:\Users\<UserName>\AppData\Local\Temp783 | |
784 |
A_OSVersion | 787 |
788 | The version number of the operating system, in the format "major.minor.build". For example, Windows 7 SP1 is 6.1.7601. 789 |Applying compatibility settings in the AutoHotkey executable or compiled script's properties causes the OS to report a different version number, which is reflected by A_OSVersion. 790 | |
791 |
A_Is64bitOS | 794 |Contains 1 (true) if the OS is 64-bit or 0 (false) if it is 32-bit. | 795 |
A_PtrSize | 798 |Contains the size of a pointer, in bytes. This is either 4 (32-bit) or 8 (64-bit), depending on what type of executable (EXE) is running the script. | 799 |
A_Language | 802 |The system's default language, which is one of these 4-digit codes. | 803 |
A_ComputerName | 806 |The name of the computer as seen on the network. | 807 |
A_UserName | 810 |The logon name of the user who launched this script. | 811 |
A_WinDir | 814 |The Windows directory. For example: C:\Windows |
815 |
A_ProgramFiles | 818 |
819 | The Program Files directory (e.g. On 64-bit systems (and not 32-bit systems), the following applies: 821 |
|
827 |
A_AppData | 830 |
831 | The full path and name of the folder containing the current user's application-specific data. For example: 832 |C:\Users\<UserName>\AppData\Roaming833 | |
834 |
A_AppDataCommon | 837 |
838 | The full path and name of the folder containing the all-users application-specific data. For example: 839 |C:\ProgramData840 | |
841 |
A_Desktop | 844 |
845 | The full path and name of the folder containing the current user's desktop files. For example: 846 |C:\Users\<UserName>\Desktop847 | |
848 |
A_DesktopCommon | 851 |
852 | The full path and name of the folder containing the all-users desktop files. For example: 853 |C:\Users\Public\Desktop854 | |
855 |
A_StartMenu | 858 |
859 | The full path and name of the current user's Start Menu folder. For example: 860 |C:\Users\<UserName>\AppData\Roaming\Microsoft\Windows\Start Menu861 | |
862 |
A_StartMenuCommon | 865 |
866 | The full path and name of the all-users Start Menu folder. For example: 867 |C:\ProgramData\Microsoft\Windows\Start Menu868 | |
869 |
A_Programs | 872 |
873 | The full path and name of the Programs folder in the current user's Start Menu. For example: 874 |C:\Users\<UserName>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs875 | |
876 |
A_ProgramsCommon | 879 |
880 | The full path and name of the Programs folder in the all-users Start Menu. For example: 881 |C:\ProgramData\Microsoft\Windows\Start Menu\Programs882 | |
883 |
A_Startup | 886 |
887 | The full path and name of the Startup folder in the current user's Start Menu. For example: 888 |C:\Users\<UserName>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup889 | |
890 |
A_StartupCommon | 893 |
894 | The full path and name of the Startup folder in the all-users Start Menu. For example: 895 |C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup896 | |
897 |
A_MyDocuments | 900 |
901 | The full path and name of the current user's "My Documents" folder. Unlike most of the similar variables, if the folder is the root of a drive, the final backslash is not included (e.g. it would contain C:\Users\<UserName>\Documents903 | |
904 |
A_IsAdmin | 907 |Contains 1 if the current user has admin rights, otherwise 0. 908 |To have the script restart itself as admin (or show a prompt to the user requesting admin), use Run *RunAs. However, note that running the script as admin causes all programs launched by the script to also run as admin. For a possible alternative, see the FAQ. 909 | |
910 |
A_ScreenWidth |
914 | The width and height of the primary monitor, in pixels (e.g. 1024 and 768). 915 |To discover the dimensions of other monitors in a multi-monitor system, use SysGet. 916 |To instead discover the width and height of the entire desktop (even if it spans multiple monitors), use the following example: 917 |918 | VirtualWidth := SysGet(78) 919 | VirtualHeight := SysGet(79) 920 |921 | In addition, use SysGet to discover the work area of a monitor, which can be smaller than the monitor's total area because the taskbar and other registered desktop toolbars are excluded. |
922 |
A_ScreenDPI | 925 |Number of pixels per logical inch along the screen width. This is typically 96 if the display scale is set to 100 %. In a system with multiple displays, this value corresponds to the primary display at the time the program started. 926 |See also DPI Scaling and the GUI's -DPIScale option. |
927 |
Variable | 933 |Description | 934 |
---|---|
A_Clipboard | 937 |Can be used to get or set the contents of the OS's clipboard. For details, see A_Clipboard. | 938 |
A_Cursor | 941 |The type of mouse cursor currently being displayed. It will be one of the following words: AppStarting, Arrow, Cross, Help, IBeam, Icon, No, Size, SizeAll, SizeNESW, SizeNS, SizeNWSE, SizeWE, UpArrow, Wait, Unknown. The acronyms used with the size-type cursors are compass directions, e.g. NESW = NorthEast+SouthWest. The hand-shaped cursors (pointing and grabbing) are classified as Unknown. |
942 |
A_EventInfo | 945 |Contains additional information about the following events: 946 |
Note: Unlike variables such as A_ThisHotkey, each thread retains its own value for A_EventInfo. Therefore, if a thread is interrupted by another, upon being resumed it will still see its original/correct values in these variables. 952 |A_EventInfo can also be set by the script, but can only accept unsigned integers within the range available to pointers (32-bit or 64-bit depending on the version of AutoHotkey). |
953 |
A_LastError | 956 |This is usually the result from the OS's GetLastError() function after the script calls certain functions, including DllCall, Run/RunWait, File/Ini/Reg functions (where documented) and possibly others. A_LastError is a number between 0 and 4294967295 (always formatted as decimal, not hexadecimal). Zero (0) means success, but any other number means the call failed. Each number corresponds to a specific error condition. See OSError for how to get the localized error description text, or search www.microsoft.com for "system error codes" to get a list. A_LastError is a per-thread setting; that is, interruptions by other threads cannot change it. 957 |Assigning a value to A_LastError also causes the OS's SetLastError() function to be called. |
958 |
True False |
961 | Contain 1 and 0. They can be used to make a script more readable. For details, see Boolean Values. 962 |These are actually keywords, not variables. 963 | |
964 |
Variable | 970 |Description | 971 |
---|---|
A_Index | 974 |Can be used to get or set the number of the current loop iteration (a 64-bit integer). It contains 1 the first time the loop's body is executed. For the second time, it contains 2; and so on. If an inner loop is enclosed by an outer loop, the inner loop takes precedence. A_Index works inside all types of loops, but contains 0 outside of a loop. For counted loops such as Loop, changing A_Index affects the number of iterations that will be performed. | 975 |
A_LoopFileName, etc. | 978 |This and other related variables are valid only inside a file loop. | 979 |
A_LoopRegName, etc. | 982 |This and other related variables are valid only inside a registry loop. | 983 |
A_LoopReadLine | 986 |See file-reading loop. | 987 |
A_LoopField | 990 |See parsing loop. | 991 |
var := ""
.If you have not already downloaded AutoHotkey, you can get it from one of the following locations:
16 |Note: This tutorial is for AutoHotkey v2.
21 |The main download has a filename like AutoHotkey_2.0_setup.exe
. Run this file to begin installing AutoHotkey.
If you are not the administrator of your computer, you may need to select the Current user option.
23 |Otherwise, the recommended options are already filled in, so just click Install.
24 |For users of v1: AutoHotkey v2 includes a launcher which allows multiple versions of AutoHotkey to co-exist while sharing one file extension (.ahk
). Installing AutoHotkey v1 and v2 into different directories is not necessary and is currently not supported.
If you are installing for all users, you will need to provide administrator consent in the standard UAC prompt that appears (in other words, click Yes).
26 |If there were no complications, AutoHotkey is now installed!
27 |Once installation completes, the Dash is shown automatically.
28 | 29 |Using the Program covers the basics of how to use AutoHotkey.
31 |Consider installing an editor with AutoHotkey support to make editing and testing scripts much easier.
32 |The documentation contains many examples, which you can test out as described in How to Run Example Code.
33 |These tutorials focus on specific common tasks:
34 |AutoHotkey Beginner Tutorial by tidbit covers a range of topics.
40 | 41 |If you have problems installing AutoHotkey, please try searching for your issue on the forum or start a new topic to get help or report the issue.
43 | 44 |AutoHotkey can also be installed from the zip download.
46 |You may receive one or more security prompts, depending on several factors.
55 | 56 |Common web browsers may show a warning like "AutoHotkey_2.0_setup.exe was blocked because it could harm your device." This is a generic warning that applies to any executable file type that isn't "commonly downloaded". In other words, it often happens for new releases of software, until more users have downloaded that particular version.
58 |To keep the download, methods vary between browsers. Look for a menu button near where downloads are shown, or try right clicking on the blocked download.
59 |Sometimes the download might be blocked due to an antivirus false-positive; in that case, see Antivirus below.
60 |The Google Safe Browsing service (also used by other browsers) has been known to show false warnings about AutoHotkey. For details, see Safe Browsing.
61 | 62 |Microsoft Defender SmartScreen may show a prompt like "Windows protected your PC". This is common for software from open source developers and Independent Software Vendors (ISV), especially soon after the release of each new version. The following blog article by Louis Kessler describes the problem well: That’s not very Smart of you, Microsoft
64 |To continue installation, select More info and then Run anyway.
65 | 66 |If your antivirus flags the download as malicious, please refer to the following:
68 |One of the easiest and most useful things AutoHotkey can do is allow you to create keyboard shortcuts (hotkeys) that manipulate windows. A script can activate, close, minimize, maximize, restore, hide, show or move almost any window. This is done by calling the appropriate Win function, specifying the window by title or some other criteria:
15 |Run "notepad.exe" 16 | WinWait "Untitled - Notepad" 17 | WinActivate "Untitled - Notepad" 18 | WinMove 0, 0, A_ScreenWidth/4, A_ScreenHeight/2, "Untitled - Notepad"19 |
This example should open a new Notepad window and then move it to fill a portion of the primary screen (¼ of its width and ½ its height). To learn how to try it out, refer to How to Run Example Code.
20 | 21 |We won't go into detail about many of the functions for manipulating windows, since there's not much to it. For instance, to minimize a window instead of activating it, replace WinActivate
with WinMinimize
. See Win functions for a list of functions which can manipulate windows or retrieve information.
Most of this tutorial is about ways to identify which window you want to operate on, since that is often the most troublesome part. For instance, there are a number of problems with the example above:
23 |We'll address these issues one at a time, after covering a few basics.
30 |Tip: AutoHotkey comes with a script called Window Spy, which can be used to confirm the title, class and process name of a window. The class and process name are often used when identifying a window by title alone is not feasible. You can find Window Spy in the script's tray menu or the AutoHotkey Dash.
31 | 32 |There are a few things to know when specifying a window by title:
34 |See Matching Behaviour for more details.
40 | 41 |To refer to the active window, use the letter "A" in place of a window title. For example, this minimizes the active window:
43 |WinMinimize "A"44 | 45 |
When WinWait, WinExist, WinActive, WinWaitActive or WinWaitNotActive find a matching window, they set it as the last found window. Most window functions allow the window title (and related parameters) to be omitted, and will in that case default to the last found window. For example:
47 |Run "notepad.exe" 48 | WinWait "Untitled - Notepad" 49 | WinActivate 50 | WinMove 0, 0, A_ScreenWidth/4, A_ScreenHeight/251 |
This saves repeating the window title, which saves a little of your time, makes the script easier to update if the window title needs to be changed, and might make the code easier to read. It makes the script more reliable by ensuring that it operates on the same window each time, even when there are multiple matching windows, or if the window title changes after the window is "found". It also makes the script execute more efficiently, but not by much.
52 | 53 |A window class is a set of attributes that is used as a template to create a window. Often the name of a window's class is related to the app or the purpose of the window. A window's class never changes while the window exists, so we can often use it to identify a window when identifying by title is impractical or impossible.
55 |For example, instead of the window title "Untitled - Notepad", we can use the window's class, which in this case happens to be "Notepad" regardless of the system language:
56 |Run "notepad.exe" 57 | WinWait "ahk_class Notepad" 58 | WinActivate 59 | WinMove 0, 0, A_ScreenWidth/4, A_ScreenHeight/260 |
A window class is distinguished from a title by using the word "ahk_class" as shown above. To combine multiple criteria, list the window title first. For example: "Untitled ahk_class Notepad"
.
Related: ahk_class
62 | 63 |Windows can be identified by the process which created them by using the word "ahk_exe" followed by the name or path of the process. For example:
65 |Run "notepad.exe" 66 | WinWait "ahk_exe notepad.exe" 67 | WinActivate 68 | WinMove 0, 0, A_ScreenWidth/4, A_ScreenHeight/269 |
Related: ahk_exe
70 | 71 |Each process has an ID number which remains unique until the process exits. We can use this to make our Notepad example more reliable by ensuring that it ignores any Notepad window except the one that is created by the new process:
73 |Run "notepad.exe",,, ¬epad_pid 74 | WinWait "ahk_pid " notepad_pid 75 | WinActivate 76 | WinMove 0, 0, A_ScreenWidth/4, A_ScreenHeight/277 |
We need three commas in a row; two of them are just to skip the unused WorkingDir and Options parameters of the Run function, since the one we want (OutputVarPID) is the fourth parameter.
78 |Ampersand (&) is the reference operator. This is used to pass the notepad_pid
variable to the Run function by reference (in other words, to pass the variable itself instead of its value), allowing the function to assign a new value to the variable. Then notepad_pid
becomes a placeholder for the actual process ID.
The string "ahk_pid " is concatenated with the process ID contained by the notepad_pid variable by simply writing them in sequence, separated by whitespace. The result is a string like "ahk_pid 1040", but the number isn't predictable.
80 |If the new process might create multiple windows, a window title and other criteria can be combined by delimiting them with spaces. The window title must always come first. For example: "Untitled ahk_class Notepad ahk_pid " notepad_pid
.
Related: ahk_pid
82 | 83 |Each window has an ID number which remains unique until the window is destroyed. In programming parlance, this is known as a "window handle" or HWND. Although not as convenient as using the last found window, the window's ID can be stored in a variable so that the script can refer to it by a name of your choice, even if the title changes. There can be only one last found window at a time, but you can use as many window IDs as you can make up variable names for (or you can use an array).
85 |A window ID is returned by WinWait, WinExist or WinActive, or can come from some other sources. The Notepad example can be rewritten to take advantage of this:
86 |Run "notepad.exe" 87 | notepad_id := WinWait("Untitled - Notepad") 88 | WinActivate notepad_id 89 | WinMove 0, 0, A_ScreenWidth/4, A_ScreenHeight/2, notepad_id90 |
This assigns the return value of WinWait to the variable "notepad_id". In other words, when WinWait finds the window, it produces the window's ID as its result, and the script then stores this result in the variable. "notepad_id" is just a name that I've made up for this example; you can use whatever variable names make sense to you (within certain constraints).
91 |Notice that I added parentheses around the window title, immediately following the function name. Parentheses can be omitted in function call statements (that is, function calls at the very beginning of the line), but in that case you cannot get the function's return value.
92 |The script can also retain the variable notepad_id
for later use, such as to close or reactivate the window or move it somewhere else.
Related: ahk_id
94 | 95 |By default, WinWait will wait indefinitely for a matching window to appear. You can determine whether this has happened by opening the script's main window via the tray icon (unless you've disabled it). The window normally opens on ListLines view by default. If WinWait is still waiting, it will appear at the very bottom of the list of lines, followed by the number of seconds since it began waiting. The number doesn't update unless you select "Refresh" from the View menu.
97 |Try running this example and opening the main window as described above:
98 |WinWait "Untitled - Notpad" ; (intentional typo)99 |
If the script is stuck waiting for a window, you will usually need to exit or reload the script to get it unstuck. To prevent that from happening in the first place (or happening again), you can use the Timeout parameter of WinWait. For example, this will wait at most 5 seconds for the window to appear:
100 |Run "notepad.exe",,, ¬epad_pid 101 | if WinWait("ahk_pid " notepad_pid,, 5) 102 | { 103 | WinActivate 104 | WinMove 0, 0, A_ScreenWidth/4, A_ScreenHeight/2 105 | }106 |
The block below the if statement is executed only if WinWait finds a matching window. If it times out, the block is skipped and execution continues after the closing brace (if there is any code after it).
107 |Note that the parentheses after "WinWait" are required when we want to use the function's result in an expression (such as the condition of an if statement). You can think of the function call itself as a substitute for the result of the function. For instance, if WinWait finds a match before timing out, the result is non-zero. if 1
would execute the block below the if statement, whereas if 0
would skip it.
Another way to write it is to return early (in other words, abort) if the wait times out. For example:
109 |Run "notepad.exe",,, ¬epad_pid 110 | if !WinWait("ahk_pid " notepad_pid,, 5) 111 | return 112 | WinActivate 113 | WinMove 0, 0, A_ScreenWidth/4, A_ScreenHeight/2114 |
The result is inverted by applying the logical-not operator (!
or not
). If WinWait times out, its result is 0. The result of !0
is 1, so when WinWait times out, the if statement executes the return
.
WinWait's result is actually the ID of the window (as described above) or zero if it timed out. If you also want to refer to the window by ID, you can assign the result to a variable instead of using it directly in the if statement:
116 |Run "notepad.exe",,, ¬epad_pid 117 | notepad_id := WinWait("ahk_pid " notepad_pid,, 5) 118 | if notepad_id 119 | { 120 | WinActivate notepad_id 121 | WinMove 0, 0, A_ScreenWidth/4, A_ScreenHeight/2, notepad_id 122 | }123 |
To avoid repeating the variable name, you can both assign the result to a variable and check that it is non-zero (true) at the same time:
124 |Run "notepad.exe",,, ¬epad_pid 125 | if notepad_id := WinWait("ahk_pid " notepad_pid,, 2) 126 | { 127 | WinActivate notepad_id 128 | WinMove 0, 0, A_ScreenWidth/4, A_ScreenHeight/2, notepad_id 129 | }130 |
In that case, be careful not to confuse :=
(assignment) with =
or ==
(comparison). For example, if myvar := 0
assigns a new value and gives the same result every time (false), whereas if myvar = 0
compares a previously-assigned value with 0.
When you want to move a window, it is often useful to move or size it relative to its previous position or size, which can be retrieved by using the WinGetPos function. For example, the following set of hotkeys can be used to move the active window by 10 pixels in each direction, by holding RCtrl and pressing the arrow keys:
134 |>^Left:: MoveActiveWindowBy(-10, 0) 135 | >^Right:: MoveActiveWindowBy(+10, 0) 136 | >^Up:: MoveActiveWindowBy( 0, -10) 137 | >^Down:: MoveActiveWindowBy( 0, +10) 138 | 139 | MoveActiveWindowBy(x, y) { 140 | WinExist "A" ; Make the active window the Last Found Window 141 | WinGetPos ¤t_x, ¤t_y 142 | WinMove current_x + x, current_y + y 143 | }144 |
The example defines a function to avoid repeating code several times. x
and y
become placeholders for the two numbers specified in each hotkey. WinGetPos stores the current position in current_x
and current_y
, which we then add to x
and y
.
Simple expressions such as this should look fairly familiar. For more details, see Expressions; but be aware there is a lot of detail that you probably won't need to learn immediately.
146 | 147 | 148 | 149 | -------------------------------------------------------------------------------- /docs/howto/RunExamples.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |The easiest way to get started quickly with AutoHotkey is to take example code, try it out and adapt it to your needs.
15 |Within this documentation, there are many examples in code blocks such as the one below.
16 |MsgBox "Hello, world!"17 |
Most (but not all) examples can be executed as-is to demonstrate their effect. There are generally two ways to do this:
18 |Run the file: Once you have the code in a script (.ahk) file, running it is usually just a case of double-clicking the file; but there are other methods.
23 | 24 |Sometimes testing code is easier if you assign it to a hotkey first. For example, consider this code for maximizing the active window:
26 |WinMaximize "A"27 |
If you save this into a file and run the file by double-clicking it, it will likely maximize the File Explorer window which contains the file. You can instead assign it to a hotkey to test its effect on whatever window you want. For example:
28 |^1::WinMaximize "A"29 |
Now you can activate your test subject and press Ctrl+1 to maximize it.
30 |For more about hotkeys, see How to Write Hotkeys.
31 | 32 |If you make a mistake in a script, sometimes it can make the computer harder to use. For example, the hotkey n::
would activate whenever you press N and would prevent you from typing that character. To undo this, all you need to do is exit the script. You can do that by right clicking on the script's tray icon and selecting Exit.
Keys can get "stuck down" if you send a key-down and don't send a key-up. In that case, exiting the script won't necessarily be enough, as the operating system still thinks the key is being held down. Generally you can "unstick" the key by physically pressing it.
35 |If a script gets into a runaway loop or is otherwise difficult to stop, you can log off or shut down the computer as a last resort. When you log off, all apps running under your session are terminated, including AutoHotkey. In some cases you might need to click "log off anyway" or "shut down anyway" if a script or program is preventing shutdown.
36 | 37 |After you've started the script, changes to the script's file do not take effect automatically. In order to make them take effect, you must reload the script. This can be done via the script's tray icon or the Reload function, which you can call from a hotkey. In many cases it can also be done by simply running the script again, but that depends on the script's #SingleInstance setting.
39 | 40 |Learning to code is often a repetitious process; take some code, make a small change, test the code, rinse and repeat. This process is quicker and more productive if you use a text editor with support for AutoHotkey. Support varies between editors, but the most important features are (in my opinion):
42 |For recommendations, try Editors with AutoHotkey Support or the Editors subforum.
47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /docs/howto/RunPrograms.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |One of the easiest and most useful things AutoHotkey can do is allow you to create keyboard shortcuts (hotkeys) that launch programs.
15 |Programs are launched by calling the Run function, passing the command line of the program as a parameter:
16 |Run "C:\Windows\notepad.exe"17 |
This example launches Notepad. To learn how to try it out, refer to How to Run Example Code.
18 |At this stage, we haven't defined a hotkey (in other words, assigned a keyboard shortcut), so the instructions are carried out immediately. In this case, the script has nothing else to do, so it automatically exits. If you prefer to make useful hotkeys while learning, check out How to Write Hotkeys first.
19 |Note: Run can also be used to open documents, folders and URLs.
20 |To launch other programs, simply replace the path in the example above with the path of the program you wish to launch. Some programs have their paths registered with the system, in which case you can get away with just passing the filename of the program, with or (sometimes) without the ".exe" extension. For example:
21 |Run "notepad"22 | 23 |
If the program accepts command-line parameters, they can be passed as part of the Run function's first parameter. The following example should open license.txt in Notepad:
25 |26 | Run "notepad C:\Program Files\AutoHotkey\license.txt" 27 |28 |
Note: This example assumes AutoHotkey is installed in the default location, and will show an error otherwise.
29 |Simple, right? Now suppose that we want to open the file in WordPad instead of Notepad.
30 |Run "wordpad C:\Program Files\AutoHotkey\license.txt"31 |
Run this code and see what you can learn from the result.
32 |Okay, so the new code doesn't work. Hopefully you didn't dismiss the error dialog immediately; error dialogs are a normal part of the process of coding, and often contain very useful information. This one should tell us a few things:
33 |But why did Notepad work? Running either "notepad" or "wordpad" on its own works, but for different reasons. Unlike notepad.exe, wordpad.exe cannot be found by checking each directory listed in the PATH environment variable. It can be located by a different method, which requires the Run function to separate the program name and parameters.
39 |So in this case, the Run function needs a bit of help, in any or all of the following forms:
40 |For now, go with the easiest option:
46 |Run "wordpad.exe C:\Program Files\AutoHotkey\license.txt"47 |
Now WordPad launches, but it shows an error: "C:\Program" wasn't found.
48 | 49 |Often when passing command-line parameters to a program, it is necessary to enclose each parameter in quote marks if the parameter contains a space. This wasn't necessary with Notepad, but Notepad is an exception to the general rule. A naive attempt at a solution might be to simply add more quote marks:
51 |Run "wordpad.exe "C:\Program Files\AutoHotkey\license.txt""52 |
But this won't work, because by default, quote marks are used to denote the start and end of literal text. So how do we include a literal quote mark within the command line, rather than having it end the command line?
53 |Method 1: Precede each literal quote mark with `
(back-tick, back-quote or grave accent). This is known as an escape sequence. The quote mark is then included in the command line (i.e. the string that is passed to the Run function), whereas the back-tick, having fulfilled its purpose, is left out.
Run "wordpad.exe `"C:\Program Files\AutoHotkey\license.txt`""55 |
Method 2: Enclose the command line in single quotes instead of double quotes.
56 |Run 'wordpad.exe "C:\Program Files\AutoHotkey\license.txt"'57 |
Of course, in that case any literal single quotes (or apostrophes) in the text would need to be escaped (`'
).
How you write the code affects which quote marks actually make it through to the Run function. In the two examples above, the Run function receives the string wordpad.exe "C:\Program Files\AutoHotkey\license.txt"
. The Run function either splits this into a program name and parameters (everything else) or leaves that up to the system. In either case, how the remaining quote marks are interpreted depends entirely on the target program.
Many programs treat a quote mark as part of the parameter if it is preceded by a backslash. For example, Run 'my.exe "A\" B'
might produce a parameter with the value A" B
instead of two parameters. This is up to the program, and can usually be avoided by doubling the backslash, as in Run 'my.exe "A\\" B'
, which usually produces two parameters (A\
and B
).
Most programs interpret quote marks as a sort of toggle, switching modes between "space ends the parameter" and "space is included in the parameter". In other words, Run 'my.exe "A B"'
is generally equivalent to Run 'my.exe A" "B'
. So another way to avoid issues with slashes is to quote the spaces instead of the entire parameter, or end the quote before the slash, as in Run 'my.exe "A"\ B'
.
Often a command line needs to include some variables. For example, the location of the "Program Files" directory can vary between systems, and a script can take this into account by using the A_ProgramFiles variable. If the variable contains the entire command line, simply pass the variable to the Run function to execute it.
64 |Run A_ComSpec ; Start a command prompt (almost always cmd.exe). 65 | Run A_MyDocuments ; Open the user's Documents folder.66 |
Including a variable inside a quoted string won't work; instead, we use concatenation to join literal strings together with variables. For example:
67 |Run 'notepad.exe "' A_MyDocuments '\AutoHotkey.ahk"'68 |
Another method is to use Format to perform substitution. For example:
69 |Run Format('notepad.exe "{1}\AutoHotkey.ahk"', A_MyDocuments)70 |
Note: Format can perform additional formatting at the same time, such as padding with 0s or spaces, or formatting numbers as hexadecimal instead of decimal.
71 | 72 |Aside from the command line to execute, the Run function accepts a few other parameters that affect its behaviour.
74 |WorkingDir specifies the working directory for the new process. If you specify a relative path for the program, it is relative to this directory. Relative paths in command line parameters are often also relative to this directory, but that depends on the program.
75 |Run "cmd", "C:\" ; Open a command prompt at C:\76 |
Options can often be used to run a program minimized or hidden, instead of having it pop up on screen, but some programs ignore it.
77 |OutputVarPID gives you the process ID, which is often used with WinWait or WinWaitActive and ahk_pid to wait until the program shows a window on screen, or to identify one of its windows. For example:
78 |Run "mspaint",,, &pid 79 | WinWaitActive "ahk_pid " pid 80 | Send "^e" ; Ctrl+E opens the Image Properties dialog.81 | 82 |
System verbs are actions that the system or applications register for specific file types. They are normally available in the file's right-click menu in Explorer, but their actual names don't always match the text displayed in the menu. For example, AutoHotkey scripts have an "edit" verb which opens the script in an editor, and (if Ahk2Exe is installed) a "compile" verb which compiles the script.
84 |"Edit" is one of a list of common verbs that Run recognizes by default, so can be used by just writing the word followed by a space and the filename, as follows:
85 |Run 'edit ' A_ScriptFullPath ; Generally equivalent to Edit86 |
Any verb registered with the system can be executed by using the * prefix as shown below:
87 |Run '*Compile-Gui ' A_ScriptFullPath88 |
If Ahk2Exe is installed, this opens the Ahk2Exe Gui with the current script pre-selected.
89 | 90 |Whenever a new process starts, it generally inherits the environment of the process which launched it (the parent process). This basically means that all of the script's environment variables are inherited by any program that you launch with Run.
92 |In some cases, environment variables can be set with EnvSet before launching the program to affect its behaviour, or pass information to it. A script can also use EnvGet to read environment variables that it might have inherited from its parent process.
93 |On 64-bit systems, the script's own environment heavily depends on whether the EXE running it is 32-bit or 64-bit. 32-bit processes not only have different environment variables, but also have file system redirection in place for compatibility reasons.
94 |Run "cmd /k set pro"95 |
The example above shows a command prompt which prints all environment variables beginning with "pro". If you run it from a 32-bit script, you will likely see PROCESSOR_ARCHITECTURE=x86
and ProgramFiles=C:\Program Files (x86)
. Although the title shows something like "C:\Windows\System32\cmd.exe", this is a lie; it is actually the 32-bit version, which really resides in "C:\Windows\SysWow64\cmd.exe".
In simple cases like this, the easiest way to bypass the redirection of "System32" is to use "SysNative" instead. However, this only works from a 32-bit process on a 64-bit system, so must be done conditionally. When the following example is executed on a 64-bit system, it shows a 64-bit command prompt even if the script is 32-bit:
97 |if FileExist(A_WinDir "\SysNative") 98 | Run A_WinDir "\SysNative\cmd.exe /k set pro" 99 | else 100 | Run "cmd /k set pro"101 | 102 | 103 | 104 | -------------------------------------------------------------------------------- /docs/howto/SendKeys.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
Send "Hello, world{!}{Left}^+{Left}"15 |
Sending keystrokes (or keys for short) is the most common method of automating programs, because it is the one that works most generally. More direct methods tend to work only in particular types of app.
16 |There are broadly two parts to learning how to send keys:
17 |It is important to understand that sending a key does not perfectly replicate the act of physically pressing the key, even if you slow it down to human speeds. But before we go into that, we'll cover some basics.
22 | 23 |If you run an example like SendText "Hi!"
, the text will be immediately sent to the active (focused) window, which might be less than useful depending on how you ran the example. It's usually better to define a hotkey, run the example to load it up, and press the hotkey when you want to test its effect. Some of the examples below will use numbered hotkeys like ^1::
(Ctrl and a number, so you can try multiple examples at once if there are no duplicates), but you can change that to whatever suits you.
To learn how to customize the hotkeys or create your own, see How to Write Hotkeys.
26 |If you're not sure how to try out the examples, see How to Run Example Code.
27 | 28 |When sending keys, you generally want to either send a key or key combination for its effect (like Ctrl+C to copy to the clipboard), or type some text. Typing text is simpler, so we'll start there: just call the SendText function, passing it the exact text you want to send.
30 |^1::SendText "To Whom It May Concern"31 |
Technically SendText actually sends Unicode character packets and not keystrokes, and that makes it much more reliable for characters that are normally typed with a key-combination like Shift+2 or AltGr+a.
32 | 33 |SendText sends the text verbatim, but keep in mind the rules of the language. For instance, literal text must be enclosed in quote marks (double "
or single '
), and the quote marks themselves aren't "seen" by the SendText function. To send a literal quote mark, you can enclose it in the opposite type of quote mark. For example:
^2::SendText 'Quote marks are also known as "quotes".'36 |
Alternatively, use an escape sequence. Inside a quoted string, `"
translates to a literal "
and `'
translates to a literal '
. For example:
^3::{ 38 | SendText "Double quote (`")" 39 | SendText 'Single quote (`')' 40 | }41 |
You can also alternate the quote marks:
42 |^4::SendText 'Double (") and' . " single (') quote"43 |
The two strings are joined together (concatenated) before being passed to the SendText function. The dot (.
) can be omitted, but that makes it harder to see where one ends and the other begins.
As you've seen above, the escape character `
(known by backquote, backtick, grave accent and other names) has special meaning, so if you want to send that character literally (or send the corresponding key), you need to double it up, as in Send "``"
. Other common escape sequences include `n
for linefeed (Enter) and `t
for tab. See Escape Sequences for more.
SendText is best for sending text verbatim, but it can't send keys that don't produce text, like Left or Home. Send, SendInput, SendPlay, SendEvent and ControlSend can send both text and key combinations, or keys which don't produce text. To do all of this, they add special meaning to the following symbols: ^!+#{}
The first four symbols correspond to the standard modifier keys, Ctrl (^
), Alt (!
), Shift (+
) and Win (#
). They can be used in combination, but otherwise affect only the next key.
To send a key by name, or to send any one of the above symbols literally, enclose it in braces. For example:
50 |^+{Left}
produces Ctrl+Shift+Left^{+}{Left}
produces Ctrl++ followed by Left^+Left
produces Ctrl+Shift+L followed literally by the letters eft
When you press Ctrl+Shift+", the following example sends two quote marks and then moves the insertion point to the left, ready to type inside the quote marks:
56 |^+"::Send '""{Left}'57 |
For any single character other than ^!+#{}
, Send translates it to the corresponding key combination and presses and releases that combination. For example, Send "aB"
presses and releases A and then presses and releases Shift+B. Similarly, any key name enclosed in braces is pressed and released by default. For example, Send "{Ctrl}a"
would press and release Ctrl, then press and release A; probably not what you want.
To only press (hold down) or release a key, enclose the key name in braces, followed by a space and then the word "down" or "up". The following example causes Ctrl+CapsLock to act as a toggle for Shift:
59 |*^CapsLock::{ 60 | if GetKeyState("Shift") 61 | Send "{Shift up}" 62 | else 63 | Send "{Shift down}" 64 | }65 | 66 |
Warning: Hotkeys and Send have some differences that you should be aware of.
68 |Although hotkeys also use the symbols ^!+#
and the same key names, there are several important differences:
>^a::
corresponds to RCtrl+A, but to send that combination, you need to spell out the key name in full, as in Send "{RCtrl down}a{RCtrl up}"
.Send "^A"
sends the combination of Ctrl with upper-case "a", so Ctrl+Shift+A. By contrast, ^a::
and ^A::
are equivalent.This is because Send serves multiple purposes, whereas hotkeys are optimized for key combinations.
75 |On a related note, hotstrings are exclusively for detecting text entry, so the symbols ^!+#{}
have no special meaning within the hotstring trigger text. However, a hotstring's replacement text uses the same syntax as Send (except when the T option is used). Whenever you type "{" with the following hotstring active, it sends "}" and then Left to move the insertion point back between the braces:
:*?B0:{::{}}{Left}77 | 78 |
Normally, Send assumes that any modifier keys you are physically holding down should not be combined with the keys you are asking it to send. For instance, if you are holding Ctrl and you call Send "Hi"
, Send will automatically release Ctrl before sending "Hi" and press it back down afterward.
Sometimes what you want is to send some keys in combination with other modifiers that were previously pressed or sent. To do this, you can use the {Blind}
prefix. While running the following example, try focusing a non-empty text editor or input field and pressing 1 or 2 while holding Ctrl or Ctrl+Shift:
*^1::Send "{Blind}{Home}" 82 | *^2::Send "{Blind}{End}"83 |
For more about {Blind}
, see Blind mode.
Send supports a few other special constructs, such as:
87 |{U+00B5}
to send a Unicode character by its ordinal value (character code).{ASC 0181}
to send an Alt+Numpad sequence.{Click Options}
to click or move the mouse.For a full list, see Key names.
93 | 94 |Sending a key does not perfectly replicate the act of physically pressing the key. The operating system provides several different ways to send keys, with different caveats for each. Sometimes to get the result you want, you will need to not only try different methods but also tweak the timing.
96 |The main methods are SendInput, SendEvent and SendPlay. SendInput is generally the most reliable, so by default, Send is synonymous with SendInput. SendMode can be used to make Send synonymous with SendEvent or SendPlay instead. The documentation describes other pros and cons of SendInput and SendPlay at length, but I would suggest just trying SendEvent or SendPlay when you have issues with SendInput.
97 |Warning: SendPlay doesn't tend to work on modern systems unless you run with UI access. On Windows 11 and later, SendPlay may have no effect at all.
98 |Another option worth trying is ControlSend. This doesn't use an official method of sending keystrokes, but instead sends messages directly to the window that you specify. The main advantage is that the window usually doesn't need to be active to receive these messages. But since it bypasses the normal processing of keyboard input by the system, sometimes it doesn't work.
99 | 100 |Sometimes you can get away with sending a flood of keystrokes faster than humanly possible, and sometimes you can't. There are generally two situations where you might need a delay:
102 |For the first case, you can simply call Send, then Sleep, then Send, and so on.
107 |SetKeyDelay exists for the second case. This function can set a delay to be performed between each keystroke, and the duration of the keystroke (i.e. the delay between pressing and releasing the key).
108 |^1::{ 109 | SetKeyDelay 75, 25 ; 75ms between keys, 25ms between down/up. 110 | SendEvent "You should see the keys{bs 4}text appear gradually." 111 | }112 |
Warning: SendInput does not support key delays, nor does Send by default.
113 |In order to make SetKeyDelay effective, you must generally either use SendMode "Event"
or call SendEvent, SendPlay or ControlSend instead of Send or SendText.
One way to send multiple lines of text is to use a continuation section:
117 |SendText " 118 | ( 119 | Leading indentation is stripped out, 120 | based on the first line. 121 | Line breaks are kept 122 | unless you use the "Join" option. 123 | )"124 |
Although it is generally quite fast, SendText still has to send each character one at a time, while Send generally needs to send at least twice as many messages (key-down and key-up). This adds up to a noticeable delay when sending a large amount of text. It can also become unreliable, as a longer delay means higher risk of conflict with input by the user, the keyboard focus shifting, or other conditions changing.
125 |Generally it is faster and more reliable to instead place the text on the clipboard and paste it. For example:
126 |^1::{ 127 | old_clip := ClipboardAll() ; Save all clipboard content 128 | A_Clipboard := " 129 | (Join`s 130 | This text is placed on the clipboard, 131 | and will be pasted below by sending Ctrl+V. 132 | )" 133 | Send "^v" 134 | Sleep 500 ; Wait a bit for Ctrl+V to be processed 135 | A_Clipboard := old_clip ; Restore previous clipboard content 136 | }137 | 138 | 139 | 140 | -------------------------------------------------------------------------------- /docs/howto/WriteHotkeys.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
A hotkey is a key or key combination that triggers an action. For example, Win+E normally launches File Explorer, and F1 often activates an app-specific help function. AutoHotkey has the power to define hotkeys that can be used anywhere or only within specific apps, performing any action that you are able to express with code.
15 |The most common way to define a hotkey is to write the hotkey name followed by double-colon, then the action:
16 |#n::Run "notepad"17 |
This example defines a hotkey that runs Notepad whenever you press Win+N. To learn how to try it out, refer to How to Run Example Code.
18 |For more about running programs, see How to Run Programs.
19 |If multiple lines are required, use braces to mark the start and end of the hotkey's action. This is called a block.
20 |#n:: 21 | { 22 | if WinExist("ahk_class Notepad") 23 | WinActivate ; Activate the window found above 24 | else 25 | Run "notepad" ; Open a new Notepad window 26 | }27 |
The opening brace can also be written on the same line as the hotkey, after ::
.
The block following a double-colon hotkey is implicitly the body of a function, but that is only important when you define your own variables. For now, just know that blocks are used to group multiple lines as a single action or statement (see Control Flow if you want to know more about this).
29 | 30 |For most hotkeys, the hotkey name consists of optional modifier symbols immediately followed by a single letter or symbol, or a key name. Try making the following changes to the example above:
32 |#
to make the hotkey activate whenever you press N on its own. Keep in mind that if something goes wrong, you can always exit the script.#
with ^
for Ctrl, !
for Alt or +
for Shift, or try combinations.#
with <^
to make it activate only when the left Ctrl key is pressed, or >^
for the right Ctrl key, or both to require both keys.n
with any other letter or symbol (except :
).n
with any name from the key list.Note: The last character before ::
is never interpreted as a modifier symbol.
With this form of hotkey, only the final key in the combination can be written literally as a single character or have its name spelled out in full. For example:
41 |#::
would create a hotkey activated by the hash key, or whatever combination is associated with that symbol (on the US layout, it's Shift+3).##::
would create a hotkey like the above, but which activates only if you are also holding the Windows key.LWin::
would create a hotkey activated by pressing down the left Windows key without any other modifier keys.The most common modifiers are Ctrl (^
), Alt (!
), Shift (+
) and Win (#
).
The symbols <
and >
can be prefixed to any one of the above four modifiers to specify the left or right variant of that key. The modifier combination <^>!
corresponds to the AltGr key (if present on your keyboard layout), since the operating system implements it as a combination of LCtrl and RAlt.
The other modifiers are:
49 |*
(wildcard) allows the hotkey to fire even if you are holding modifier keys that the hotkey doesn't include symbols for.~
(no-suppress) prevents the hotkey from blocking the key's native function.$
(use hook) prevents unintentional loops when sending keys, and in some instances makes the hotkey more reliable.To make a hotkey fire only when you release the key instead of when you press it, use the UP suffix.
55 |Related: Hotkey Modifier Symbols, List of Keys
56 | 57 |The #HotIf directive can be used to specify a condition that must be met for the hotkey to activate, such as:
59 |For example:
65 |#HotIf WinActive("ahk_class Notepad") 66 | ^a::MsgBox "You pressed Ctrl-A while Notepad is active. Pressing Ctrl-A in any other window will pass the Ctrl-A keystroke to that window." 67 | #c::MsgBox "You pressed Win-C while Notepad is active." 68 | 69 | #HotIf 70 | #c::MsgBox "You pressed Win-C while any window except Notepad is active."71 |
You define the condition by writing an expression which is evaluated whenever you press the hotkey. If the expression evaluates to true, the hotkey's action is executed.
72 |The same hotkey can be used multiple times by specifying a different condition for each occurrence of the hotkey, or each hotkey variant. When you press the hotkey, the program executes the first hotkey variant whose condition is met, or the one without a condition (such as the final #c::
in the example above).
If the hotkey's condition isn't met and there is no unconditional variant of the hotkey, the keypress is passed on to the active window as though the hotkey wasn't defined in the first place. For instance, if Notepad isn't active while running the example above, Ctrl+A will perform its normal function (probably Select All).
74 |Try making the following changes to the example:
75 |WinActive
with WinExist
so that the hotkeys activate if Notepad is running, even if Notepad doesn't have the focus.GetKeyState("CapsLock", "T")
so that the hotkeys only activate while CapsLock is on.Correctly identifying which window you want the hotkey to affect sometimes requires using criteria other than the window title. To learn more, see How to Manage Windows.
81 |Related: #HotIf, Expressions, WinActive
82 | 83 |A custom combination is a hotkey that combines two keys which aren't normally meant to be used in combination. For example, Numpad0 & Numpad1::
defines a hotkey which activates when you hold Numpad0 and press Numpad1.
When you use a key as a prefix in a custom combination, AutoHotkey assumes that you don't want the normal function of the key to activate, since that would interfere with its use as a modifier key. There are two ways to restore the key's normal function:
86 |Numpad0::Send "{Numpad0}"
to replicate the key's original function. By default, the hotkey will only activate when you release Numpad0, and only if you didn't press Numpad0 and Numpad1 in combination.~Numpad0 & Numpad1::
. This prevents AutoHotkey from suppressing the normal function of Numpad0, unless you have also defined Numpad0::
, in which case the tilde allows the latter hotkey to activate immediately instead of when you release Numpad0.Note: Custom combinations only support combinations of exactly two keys/mouse buttons, and cannot be combined with other modifiers, such as !#^+
for Alt, Win, Ctrl and Shift.
Although AutoHotkey does not directly support custom combinations of more than two keys, a similar end result can be achieved by using #HotIf. If you run the example below, pressing Ctrl+CapsLock+Space or Ctrl+Space+CapsLock should show a message:
92 |#HotIf GetKeyState("Ctrl") 93 | Space & CapsLock:: 94 | CapsLock & Space::MsgBox "Success!"95 |
It is necessary to press Ctrl first in this example. This has the advantage that Space and CapsLock perform their normal function if you are not holding Ctrl.
96 |Related: Custom Combinations
97 | 98 |AutoHotkey's hotkeys have some other features that are worth exploring. While most applications are limited to combinations of Ctrl, Alt, Shift and sometimes Win with one other key (and often not all keys on the keyboard are supported), AutoHotkey isn't so limited. For further reading, see Hotkeys.
100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /docs/index.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |© 2014 Steve Gray, Chris Mallett, portions © AutoIt Team and various others
18 |Software License: GNU General Public License
19 | 20 |Getting started:
22 |Scripts:
38 |Keyboard and mouse:
49 |Other:
56 |A special thanks to Jonathan Bennett, whose generosity in releasing AutoIt v2 as free software in 1999 served as an inspiration and time-saver for myself and many others worldwide. In addition, many of AutoHotkey's enhancements to the AutoIt v2 command set, as well as the Window Spy and the old script compiler, were adapted directly from the AutoIt v3 source code. So thanks to Jon and the other AutoIt authors for those as well.
63 |Finally, AutoHotkey would not be what it is today without these other individuals.
64 |~ Chris Mallett
65 | 66 | 67 | -------------------------------------------------------------------------------- /docs/lib/A_Clipboard.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |A_Clipboard is a built-in variable that reflects the current contents of the Windows clipboard if those contents can be expressed as text.
17 | 18 |Each line of text on A_Clipboard typically ends with carriage return and linefeed (CR+LF), which can be expressed in the script as `r`n
. Files (such as those copied from an open Explorer window via Ctrl+C) are considered to be text: They are automatically converted to their filenames (with full path) whenever A_Clipboard is referenced in the script. To extract the files one by one, follow this example:
Loop Parse A_Clipboard, "`n", "`r" 20 | { 21 | Result := MsgBox("File number " A_Index " is " A_LoopField ".`n`nContinue?",, 4) 22 | if Result = "No" 23 | break 24 | }25 |
To arrange the filenames in alphabetical order, use the Sort function. To write the filenames on the clipboard to a file, use FileAppend A_Clipboard "`r`n", "C:\My File.txt"
. To change how long the script will keep trying to open the clipboard -- such as when it is in use by another application -- use #ClipboardTimeout.
ClipWait may be used to detect when the clipboard contains data (optionally including non-text data):
28 |A_Clipboard := "" ; Start off empty to allow ClipWait to detect when the text has arrived. 29 | Send "^c" 30 | ClipWait ; Wait for the clipboard to contain text. 31 | MsgBox "Control-C copied the following contents to the clipboard:`n`n" A_Clipboard32 | 33 | 34 |
Converts any copied files, HTML, or other formatted text to plain text.
53 |A_Clipboard := A_Clipboard54 |
Replaces all occurrences of ABC with DEF (also converts the clipboard to plain text).
63 |A_Clipboard := StrReplace(A_Clipboard, "ABC", "DEF")64 |
Clipboard utilities written in AutoHotkey v1:
67 |A_HotkeyModifierTimeout is a built-in variable that affects the behavior of Send with hotkey modifiers Ctrl, Alt, Win, and Shift. Specifically, it defines how long after a hotkey is pressed that its modifier keys are assumed to still be held down. This is used by Send to determine whether to push the modifier keys back down after having temporarily released them.
17 |A_HotkeyModifierTimeout can be used to get or set an integer representing the length of the interval in milliseconds. If -1, it never times out (modifier keys are always pushed back down after the Send). If 0, it always times out (modifier keys are never pushed back down).
18 |The default setting is 50 (ms).
19 | 20 |This variable has no effect when:
22 |To illustrate the effect of this variable, consider this example: ^!a::Send "abc"
.
When the Send function executes, the first thing it does is release Ctrl and Alt so that the characters get sent properly. After sending all the keys, the function doesn't know whether it can safely push back down Ctrl and Alt (to match whether the user is still holding them down). But if less than the specified number of milliseconds have elapsed, it will assume that the user hasn't had a chance to release the keys yet and it will thus push them back down to match their physical state. Otherwise, the modifier keys will not be pushed back down and the user will have to release and press them again to get them to modify the same or another key.
28 |The timeout should be set to a value less than the amount of time that the user typically holds down a hotkey's modifiers before releasing them. Otherwise, the modifiers may be restored to the down position (get stuck down) even when the user isn't physically holding them down.
29 |You can reduce or eliminate the need for this variable with one of the following:
30 |Sets the hotkey modifier timeout to 100 ms instead of 50 ms.
42 |A_HotkeyModifierTimeout := 10043 |
A_MaxHotkeysPerInterval and A_HotkeyInterval are built-in variables that control the rate of hotkey activations beyond which a warning dialog will be displayed.
17 |A_MaxHotkeysPerInterval can be used to get or set an integer representing the maximum number of hotkeys that can be pressed within the interval without triggering a warning dialog.
18 |A_HotkeyInterval can be used to get or set an integer representing the length of the interval in milliseconds.
19 |The default settings are 70 (ms) for A_MaxHotkeysPerInterval and 2000 (ms) for A_HotkeyInterval.
20 | 21 |These built-in variables should usually be assigned values when the script starts (if the default settings are not suitable), but the script can get or set their values at any time.
23 |Care should be taken not to make the setting too lenient because if you ever inadvertently introduce an infinite loop of keystrokes (via a Send function that accidentally triggers other hotkeys), your computer could become unresponsive due to the rapid flood of keyboard events.
24 |As an oversimplified example, the hotkey ^c::Send "^c"
would produce an infinite loop of keystrokes. To avoid this, add the $ prefix to the hotkey definition (e.g. $^c::
) so that the hotkey cannot be triggered by the Send function.
The limit might be reached by means other than an infinite loop, such as:
26 |WheelLeft::
and WheelRight::
.To disable the warning dialog entirely, use A_HotkeyInterval := 0
.
Allows a maximum of 200 hotkeys to be pressed within 2000 ms without triggering a warning dialog.
35 |A_HotkeyInterval := 2000 ; This is the default value (milliseconds). 36 | A_MaxHotkeysPerInterval := 20037 |
A_MenuMaskKey is a built-in variable that controls which key is used to mask Win or Alt keyup events.
17 |A_MenuMaskKey can be used to get or set a string representing a vkNNscNNN sequence identifying the virtual key code (NN) and scan code (NNN), in hexadecimal. If blank, masking is disabled.
18 |The script can also assign a key name, vkNN sequence or scNNN sequence, in which case generally either the VK or SC code is left as zero until the key is sent, then determined automatically. Assigning "vk00sc000"
disables masking and is equivalent to assigning ""
.
The returned string is always a vkNNscNNN sequence if enabled or blank if disabled, regardless of how it was assigned. All vkNNscNNN sequences and all non-zero vkNN or scNNN sequences are permitted, but some combinations may fail to suppress the menu. Any other invalid keys cause a ValueError to be thrown.
20 |The default setting is vk11sc01D (the left Ctrl key).
21 | 22 |The mask key is sent automatically to prevent the Start menu or the active window's menu bar from activating at unexpected times.
24 |This variable can be used to change the mask key to a key with fewer side effects. Good candidates are virtual key codes which generally have no effect, such as vkE8, which Microsoft documents as "unassigned", or vkFF, which is reserved to mean "no mapping" (a key which has no function). Some values, such as zero VK with non-zero SC, may fail to suppress the Start menu. Key codes are not required to match an existing key.
25 |Note: Microsoft can assign an effect to an unassigned key code at any time. For example, vk07 was once undefined and safe to use, but since Windows 10 1909 it is reserved for opening the game bar.
26 |This setting is global, meaning that it needs to be specified only once to affect the behavior of the entire script.
27 |Hotkeys: If a hotkey is implemented using the keyboard hook or mouse hook, the final keypress may be invisible to the active window and the system. If the system was to detect only a Win or Alt keydown and keyup with no intervening keypress, it would usually activate a menu. To prevent this, the keyboard or mouse hook may automatically send the mask key.
28 |Pressing a hook hotkey causes the next Alt or Win keyup to be masked if all of the following conditions are met:
29 |$#a::
in combination with AppsKey::RWin
causes masking when Menu+A is pressed, but Menu on its own is able to open the Start Menu.Mouse hotkeys may send the mask key immediately if the keyboard hook is not installed.
38 |Hotkeys with the tilde modifier are not intended to block the native function of the key, so they do not cause masking. Hotkeys like ~#a::
still suppress the menu, since the system detects that Win has been used in combination with another key. However, mouse hotkeys and both Win themselves (~LWin::
and ~RWin::
) do not suppress the Start Menu.
The Start Menu (or the active window's menu bar) can be suppressed by sending any keystroke. The following example disables the ability for the left Win to activate the Start Menu, while still allowing its use as a modifier:
40 |~LWin::Send "{Blind}{vkE8}"41 |
Send: Send, ControlSend and related often release modifier keys as part of their normal operation. For example, the hotkey <#a::SendText Address
usually must release the left Win prior to sending the contents of Address, and press the left Win back down afterward (so that other Win key combinations continue working). The mask key may be sent in such cases to prevent a Win or Alt keyup from activating a menu.
See this archived forum thread for background information.
45 | 46 |A_MenuMaskKey := "vkE8" ; Change the masking key to something unassigned such as vkE8. 50 | #Space::Run A_ScriptDir ; An additional Ctrl keystroke is not triggered.51 |
Shows in detail how this variable causes vkFF to be sent instead of LControl.
55 |A_MenuMaskKey := "vkFF" ; vkFF is no mapping. 56 | #UseHook 57 | #Space:: 58 | !Space:: 59 | { 60 | KeyWait "LWin" 61 | KeyWait "RWin" 62 | KeyWait "Alt" 63 | KeyHistory 64 | }65 |
Any
is the class at the root of AutoHotkey's type hierarchy. All other types are a sub-type of Any.
Any.Prototype
defines methods and properties that are applicable to all values and objects (currently excluding ComValue and derived types) unless overridden. The prototype object itself is natively an Object, but has no base
and therefore does not identify as an instance of Object.
Retrieves the implementation function of a method.
45 |Value.GetMethod(Name, ParamCount)46 |
This method is exactly equivalent to GetMethod(Value, Name, ParamCount)
, unless overridden.
Returns true if the specified base object is in the value's chain of base objects, otherwise false.
51 |Value.HasBase(BaseObj)
52 | This method is exactly equivalent to HasBase(Value, BaseObj)
, unless overridden.
Returns true if the value has a method by this name, otherwise false.
57 |Value.HasMethod(Name, ParamCount)58 |
This method is exactly equivalent to HasMethod(Value, Name, ParamCount)
, unless overridden.
Returns true if the value has a property by this name, otherwise false.
63 |Value.HasProp(Name)
64 | This method is exactly equivalent to HasProp(Value, Name)
, unless overridden.
Retrieves the value's base object.
71 |BaseObj := Value.Base
72 | For primitive values, the return value is the pre-defined prototype object corresponding to Type(Value)
.
See also: ObjGetBase, ObjSetBase, Obj.Base
74 |Returns the value's base object.
79 |BaseObj := ObjGetBase(Value)
80 | No meta-functions or property functions are called. Overriding the Base property does not affect the behaviour of this function.
81 |If there is no base, the return value is an empty string. Only the Any prototype itself has no base.
82 |See also: Base, ObjSetBase, Obj.Base
83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /docs/lib/Array.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |class Array extends Object16 | 17 |
An Array object contains a list or sequence of values.
18 |Values are addressed by their position within the array (known as an array index), where position 1 is the first element.
19 |Arrays are often created by enclosing a list of values in brackets. For example:
20 |veg := ["Asparagus", "Broccoli", "Cucumber"] 21 | Loop veg.Length 22 | MsgBox veg[A_Index]23 |
A negative index can be used to address elements in reverse, so -1 is the last element, -2 is the second last element, and so on.
24 |Attempting to use an array index which is out of bounds (such as zero, or if its absolute value is greater than the Length of the array) is considered an error and will cause an IndexError to be thrown. The best way to add new elements to the array is to call InsertAt or Push. For example:
25 |users := Array() 26 | users.Push(A_UserName) 27 | MsgBox users[1]28 |
An array can also be extended by assigning a larger value to Length. This changes which indices are valid, but Has will show that the new elements have no value. Elements without a value are typically used for variadic calls or by variadic functions, but can be used for any purpose.
29 |"ArrayObj" is used below as a placeholder for any Array object, as "Array" is the class itself.
30 |In addition to the methods and property inherited from Object, Array objects have the following predefined methods and properties.
31 | 32 |Creates a new Array containing the specified values.
67 |ArrayObj := Array(Value, Value2, ..., ValueN) 68 | ArrayObj := Array.Call(Value, Value2, ..., ValueN)69 |
Parameters are defined by __New.
70 |Returns a shallow copy of an array.
76 |Clone := ArrayObj.Clone()
77 | All array elements are copied to the new array. Object references are copied (like with a normal assignment), not the objects themselves.
78 |Own properties, own methods and base are copied as per Obj.Clone.
79 |Removes the value of an array element, leaving the index without a value.
83 |RemovedValue := ArrayObj.Delete(Index)
84 | Type: Integer
89 |A valid array index.
90 |Type: Any
94 |This method returns the removed value (blank if none).
95 |This method does not affect the Length of the array.
97 |A ValueError is thrown if Index is out of range.
98 |Returns the value at a given index, or a default value.
102 |Value := ArrayObj.Get(Index , Default)103 |
This method does the following:
104 |ArrayObj.Default
, if defined.When Default is omitted, this is equivalent to ArrayObj[Index]
, except that __Item is not called.
Returns a non-zero number if the index is valid and there is a value at that position.
116 |HasIndex := ArrayObj.Has(Index)
117 | Inserts one or more values at a given position.
121 |ArrayObj.InsertAt(Index, Value1 , Value2, ... ValueN)122 |
Type: Integer
127 |The position to insert Value1 at. Subsequent values are inserted at Index+1, Index+2, etc. Specifying an index of 0 is the same as specifying Length + 1.
128 |Type: Any
132 |One or more values to insert. To insert an array of values, pass theArray*
as the last parameter.
InsertAt is the counterpart of RemoveAt.
137 |Any items previously at or to the right of Index are shifted to the right. Missing parameters are also inserted, but without a value. For example:
138 |x := [] 139 | x.InsertAt(1, "A", "B") ; => ["A", "B"] 140 | x.InsertAt(2, "C") ; => ["A", "C", "B"] 141 | 142 | ; Missing elements are preserved: 143 | x := ["A", , "C"] 144 | x.InsertAt(2, "B") ; => ["A", "B", , "C"] 145 | 146 | x := ["C"] 147 | x.InsertAt(1, , "B") ; => [ , "B", "C"]148 |
A ValueError is thrown if Index is less than -ArrayObj.Length
or greater than ArrayObj.Length + 1
. For example, with an array of 3 items, Index must be between -3 and 4, inclusive.
Removes and returns the last array element.
153 |RemovedValue := ArrayObj.Pop()
154 | All of the following are equivalent:
155 |RemovedValue := ArrayObj.Pop() 156 | RemovedValue := ArrayObj.RemoveAt(ArrayObj.Length) 157 | RemovedValue := ArrayObj.RemoveAt(-1)158 | 159 |
Appends values to the end of an array.
163 |ArrayObj.Push(Value, Value2, ..., ValueN)164 |
Removes items from an array.
176 |RemovedValue := ArrayObj.RemoveAt(Index) 177 | ArrayObj.RemoveAt(Index, Length)178 |
Type: Integer
183 |The index of the value or values to remove.
184 |Type: Integer
189 |If omitted, one item is removed. Otherwise, specify the length of the range of values to remove.
190 |Type: Any
194 |If Length is omitted, the removed value is returned (blank if none). Otherwise there is no return value.
195 |RemoveAt is the counterpart of InsertAt.
197 |A ValueError is thrown if the range indicated by Index and Length is not entirely within the array's current bounds.
198 |The remaining items to the right of Pos are shifted to the left by Length (or 1 if omitted). For example:
199 |x := ["A", "B"] 200 | MsgBox x.RemoveAt(1) ; A 201 | MsgBox x[1] ; B 202 | 203 | x := ["A", , "C"] 204 | MsgBox x.RemoveAt(1, 2) ; 1 205 | MsgBox x[1] ; C206 |
Appends items. Equivalent to Push.
210 |ArrayObj.__New(Value, Value2, ..., ValueN)211 |
This method exists to support Call, and is not intended to be called directly. See Construction and Destruction.
212 |Enumerates array elements.
216 |For Value in ArrayObj217 |
For Index, Value in ArrayObj218 |
Returns a new enumerator. This method is typically not called directly. Instead, the array object is passed directly to a for-loop, which calls __Enum once and then calls the enumerator once for each iteration of the loop. Each call to the enumerator returns the next array element. The for-loop's variables correspond to the enumerator's parameters, which are:
219 |Type: Integer
223 |The array index, typically the same as A_Index. This is present only in the two-parameter mode.
224 |Type: Any
228 |The value (if there is no value, Value becomes uninitialized).
229 |Retrieves or sets the length of an array.
237 |Length := ArrayObj.Length
238 | ArrayObj.Length := Length
239 | The length includes elements which have no value. Increasing the length changes which indices are considered valid, but the new elements have no value (as indicated by Has). Decreasing the length truncates the array.
240 |241 | MsgBox ["A", "B", "C"].Length ; 3 242 | MsgBox ["A", , "C"].Length ; 3 243 |244 |
Retrieves or sets the current capacity of an array.
248 |MaxItems := ArrayObj.Capacity
249 | ArrayObj.Capacity := MaxItems
250 | MaxItems is an integer representing the maximum number of elements the array should be able to contain before it must be automatically expanded. If setting a value less than Length, elements are removed.
251 |Defines the default value returned when an element with no value is requested.
255 |ArrayObj.Default := Value
256 | This property actually doesn't exist by default, but can be defined by the script. If defined, its value is returned by __Item or Get if the requested element has no value, instead of throwing an UnsetItemError. It can be implemented by any of the normal means, including a dynamic property or meta-function, but determining which key was queried would require overriding __Item or Get instead.
257 |Setting a default value does not prevent an error from being thrown when the index is out of range.
258 |Retrieves or sets the value of an array element.
262 |Value := ArrayObj[Index]
263 | Value := ArrayObj.__Item[Index]
264 | ArrayObj[Index] := Value
265 | ArrayObj.__Item[Index] := Value
266 | Index is an integer representing a valid array index; that is, an integer with absolute value between 1 and Length (inclusive). A negative index can be used to address elements in reverse, so that -1 is the last element, -2 is the second last element, and so on. Attempting to use an index which is out of bounds (such as zero, or if its absolute value is greater than the Length of the array) is considered an error and will cause an IndexError to be thrown.
267 |The property name __Item is typically omitted, as shown above, but is used when overriding the property.
268 |Blocks are one or more statements enclosed in braces. Typically used with function definitions and control flow statements.
15 |16 | { 17 | Statements 18 | }19 | 20 |
A block is used to bind two or more statements together. It can also be used to change which If statement an Else statement belongs to, as in this example where the block forces the Else statement to belong to the first If statement rather than the second:
22 |if (Var1 = 1) 23 | { 24 | if (Var2 = "abc") 25 | Sleep 1 26 | } 27 | else 28 | return29 |
Although blocks can be used anywhere, currently they are only meaningful when used with function definitions, If, Else, Loop statements, Try, Catch or Finally.
30 |If any of the control flow statements mentioned above has only a single statement, that statement need not be enclosed in a block (this does not work for function definitions). However, there may be cases where doing so enhances the readability or maintainability of the script.
31 |A block may be empty (contain zero statements), which may be useful in cases where you want to comment out the contents of the block without removing the block itself.
32 |One True Brace (OTB, K&R style): The OTB style may optionally be used in the following places: function definitions, If, Else, Loop, While, For, Try, Catch, and Finally. This style puts the block's opening brace on the same line as the block's controlling statement rather than underneath on a line by itself. For example:
33 |MyFunction(x, y) { 34 | ... 35 | } 36 | if (x < y) { 37 | ... 38 | } else { 39 | ... 40 | } 41 | Loop RepeatCount { 42 | ... 43 | } 44 | While x < y { 45 | ... 46 | } 47 | For k, v in obj { 48 | ... 49 | } 50 | Try { 51 | ... 52 | } Catch Error { 53 | ... 54 | } Finally { 55 | .... 56 | }57 |
Similarly, a statement may exist to the right of a brace (except the open-brace of the One True Brace style). For example:
58 |if (x = 1) 59 | { MsgBox "This line appears to the right of an opening brace. It executes whenever the IF-statement is true." 60 | MsgBox "This is the next line." 61 | } MsgBox "This line appears to the right of a closing brace. It executes unconditionally."62 | 63 |
Function Definitions, Control Flow Statements, If, Else, Loop Statements, Try, Catch, Finally
65 | 66 | By enclosing the two statements MsgBox "test1"
and Sleep 5
with braces, the If statement knows that it should execute both if x is equal to 1.
if (x = 1) 70 | { 71 | MsgBox "test1" 72 | Sleep 5 73 | } 74 | else 75 | MsgBox "test2"76 |
Disables or enables the user's ability to interact with the computer via keyboard and mouse.
16 | 17 |BlockInput OnOff 18 | BlockInput SendMouse 19 | BlockInput MouseMove20 |
This mode blocks all user inputs unconditionally. Specify one of the following values:
27 |On or 1 (true): The user is prevented from interacting with the computer (mouse and keyboard input has no effect).
28 |Off or 0 (false): Input is re-enabled.
29 |Type: String
33 |This mode only blocks user inputs while specific send and/or mouse functions are in progress. Specify one of the following words:
34 |Send: The user's keyboard and mouse input is ignored while a SendEvent is in progress (including Send and SendText if SendMode "Event"
has been used). This prevents the user's keystrokes from disrupting the flow of simulated keystrokes. When the Send finishes, input is re-enabled (unless still blocked by a previous use of BlockInput "On"
).
Mouse: The user's keyboard and mouse input is ignored while a Click, MouseMove, MouseClick, or MouseClickDrag is in progress (the traditional SendEvent mode only). This prevents the user's mouse movements and clicks from disrupting the simulated mouse events. When the mouse action finishes, input is re-enabled (unless still blocked by a previous use of BlockInput "On"
).
SendAndMouse: A combination of the above two modes.
37 |Default: Turns off both the Send and the Mouse modes, but does not change the current state of input blocking. For example, if BlockInput "On"
is currently in effect, using BlockInput "Default"
will not turn it off.
Type: String
42 |This mode only blocks the mouse cursor movement. Specify one of the following words:
43 |MouseMove: The mouse cursor will not move in response to the user's physical movement of the mouse (DirectInput applications are a possible exception). When a script first uses this function, the mouse hook is installed (if it is not already). The mouse hook will stay installed until the next use of the Suspend or Hotkey function, at which time it is removed if not required by any hotkeys or hotstrings (see #Hotstring NoMouse).
44 |MouseMoveOff: Allows the user to move the mouse cursor.
45 |All three BlockInput modes (OnOff, SendMouse and MouseMove) operate independently of each other. For example, BlockInput "On"
will continue to block input until BlockInput "Off"
is used, even if one of the words from SendMouse is also in effect. Another example is, if BlockInput "On"
and BlockInput "MouseMove"
are both in effect, mouse movement will be blocked until both are turned off.
Note: The OnOff and SendMouse modes might have no effect if UAC is enabled or the script has not been run as administrator. For more information, refer to the FAQ.
52 |In preference to BlockInput, it is often better to use the sending modes SendInput or SendPlay so that keystrokes and mouse clicks become uninterruptible. This is because unlike BlockInput, those modes do not discard what the user types during the send; instead, those keystrokes are buffered and sent afterward. Avoiding BlockInput also avoids the need to work around sticking keys as described in the next paragraph.
53 |If BlockInput becomes active while the user is holding down keys, it might cause those keys to become "stuck down". This can be avoided by waiting for the keys to be released prior to turning BlockInput on, as in this example:
54 |^!p:: 55 | { 56 | KeyWait "Control" ; Wait for the key to be released. Use one KeyWait for each of the hotkey's modifiers. 57 | KeyWait "Alt" 58 | BlockInput true 59 | ; ... send keystrokes and mouse clicks ... 60 | BlockInput false 61 | }62 |
When BlockInput is in effect, user input is blocked but AutoHotkey can simulate keystrokes and mouse clicks. However, pressing Ctrl+Alt+Del will re-enable input due to a Windows API feature.
63 |Certain types of hook hotkeys can still be triggered when BlockInput is on. Examples include MButton
(mouse hook) and LWin & Space
(keyboard hook with explicit prefix rather than modifiers $#
).
Input is automatically re-enabled when the script closes.
65 |SendMode, Send, Click, MouseMove, MouseClick, MouseClickDrag
67 |Opens Notepad and pastes time/date by sending F5 while BlockInput is turned on. Note that BlockInput may only work if the script has been run as administrator.
70 |BlockInput true 71 | Run "notepad" 72 | WinWaitActive "ahk_class Notepad" 73 | Send "{F5}" ; pastes time and date 74 | BlockInput false75 |
Exits (terminates) any type of loop statement.
15 |Break LoopLabel16 | 17 |
If omitted or 1, this statement applies to the innermost loop in which it is enclosed. Otherwise, specify which loop this statement should apply to; either by label name or numeric nesting level. If a label is specified, it must point directly at a loop statement.
22 |LoopLabel must be a constant value - variables and expressions are not supported, with the exception of a single literal number or quoted string enclosed in parentheses. For example: break("outer")
The use of Break and Continue are encouraged over Goto since they usually make scripts more readable and maintainable.
28 |Continue, Loop, While-loop, For-loop, Blocks, Labels
30 | 31 |Breaks the loop if var is greater than 25.
34 |Loop 35 | { 36 | ; ... 37 | if (var > 25) 38 | break 39 | ; ... 40 | if (var <= 5) 41 | continue 42 | }43 |
Breaks the outer loop from within a nested loop.
47 |outer: 48 | Loop 3 49 | { 50 | x := A_Index 51 | Loop 3 52 | { 53 | if (x*A_Index = 6) 54 | break outer ; Equivalent to break 2 or goto break_outer. 55 | MsgBox x "," A_Index 56 | } 57 | } 58 | break_outer: ; For goto. 59 |60 |
class Buffer extends Object16 | 17 |
Encapsulates a block of memory for use with advanced techniques such as DllCall, structures, StrPut and raw file I/O.
18 |Buffer objects are typically created by calling Buffer(), but can also be returned by FileRead with the "RAW" option.
19 |BufferObj := Buffer(ByteCount)20 |
ClipboardAll returns a sub-type of Buffer, also named ClipboardAll.
21 |class ClipboardAll extends Buffer22 | 23 |
"BufferObj" is used below as a placeholder for any Buffer object, as "Buffer" is the class itself.
24 |In addition to the methods and property inherited from Object, Buffer objects have the following predefined properties.
25 | 26 |Some built-in functions accept a Buffer object in place of an address - see the Related section for links. These functions also accept any other object which has Ptr and Size properties, but are optimized for the native Buffer object.
51 |In most cases, passing a Buffer object is safer than passing an address, as the function can read the buffer size to ensure that it does not attempt to access any memory location outside of the buffer. One exception is that DllCall calls functions outside of the program; in those cases, it may be necessary to explicitly pass the buffer size to the function.
52 | 53 |Creates a new Buffer object.
56 |BufferObj := Buffer(ByteCount, FillByte) 57 | BufferObj := Buffer.Call(ByteCount, FillByte)58 |
Type: Integer
63 |The number of bytes to allocate. Corresponds to Buffer.Size.
64 |If omitted, the Buffer is created with a null (zero) Ptr and zero Size.
65 |Type: Integer
69 |Specify a number between 0 and 255 to set each byte in the buffer to that number.
70 |This should generally be omitted in cases where the buffer will be written into without first being read, as it has a time-cost proportionate to the number of bytes. If omitted, the memory of the buffer is not initialized; the value of each byte is arbitrary.
71 |Type: Object
75 |This method or function returns a Buffer object.
76 |A MemoryError is thrown if the memory could not be allocated, such as if ByteCount is unexpectedly large or the system is low on virtual memory.
78 |Parameters are defined by __New.
79 |Allocates or reallocates the buffer and optionally fills it.
84 |BufferObj.__New(ByteCount, FillByte)85 |
This method exists to support Call, and is not usually called directly. See Construction and Destruction.
86 |Specify ByteCount to allocate, reallocate or free the buffer. This is equivalent to assigning Size.
87 |Specify FillByte to fill the buffer with the given numeric byte value, overwriting any existing content.
88 |If both parameters are omitted, this method has no effect.
89 |Retrieves the buffer's current memory address.
94 |CurrentPtr := BufferObj.Ptr
95 | CurrentPtr is an integer representing the buffer's current memory address. This address becomes invalid when the buffer is freed or reallocated. Invalid addresses must not be used. The buffer is not freed until the Buffer object's reference count reaches zero, but it is reallocated when its Size is changed.
96 |Retrieves or sets the buffer's size, in bytes.
100 |CurrentByteCount := BufferObj.Size
101 | BufferObj.Size := NewByteCount
102 | CurrentByteCount and NewByteCount are an integer representing the buffer's size, in bytes. The buffer's address typically changes whenever its size is changed. If the size is decreased, the data within the buffer is truncated, but the remaining bytes are preserved. If the size is increased, all data is preserved and the values of any new bytes are arbitrary (they are not initialized, for performance reasons).
103 |A MemoryError is thrown if the memory could not be allocated, such as if NewByteCount is unexpectedly large or the system is low on virtual memory.
104 |CurrentByteCount is always the exact value it was given either by __New or by a previous assignment.
105 |DllCall, NumPut, NumGet, StrPut, StrGet, File.RawRead, File.RawWrite, ClipboardAll
109 | 110 |Uses a Buffer to receive a string from an external function via DllCall.
113 |114 | max_chars := 11 115 | 116 | ; Allocate a buffer for use with the Unicode version of wsprintf. 117 | bufW := Buffer(max_chars*2) 118 | 119 | ; Print a UTF-16 string into the buffer with wsprintfW(). 120 | DllCall("wsprintfW", "Ptr", bufW, "Str", "0x%08x", "UInt", 4919, "CDecl") 121 | 122 | ; Retrieve the string from bufW and show it. 123 | MsgBox StrGet(bufW, "UTF-16") ; Or just StrGet(bufW). 124 | 125 | ; Allocate a buffer for use with the ANSI version of wsprintf. 126 | bufA := Buffer(max_chars) 127 | 128 | ; Print an ANSI string into the buffer with wsprintfA(). 129 | DllCall("wsprintfA", "Ptr", bufA, "AStr", "0x%08x", "UInt", 4919, "CDecl") 130 | 131 | ; Retrieve the string from bufA (converted to the native format), and show it. 132 | MsgBox StrGet(bufA, "CP0") 133 |134 |
Creates a machine-code address that when called, redirects the call to a function in the script.
17 | 18 |Address := CallbackCreate(Function , Options, ParamCount)19 |
Type: Function Object
25 |A function object to call automatically whenever Address is called. The function also receives the parameters that were passed to Address.
26 |A closure or bound function can be used to differentiate between multiple callbacks which all call the same script function.
27 |The callback retains a reference to the function object, and releases it when the script calls CallbackFree.
28 |Type: String
33 |If blank or omitted, a new thread will be started each time Function is called, the standard calling convention will be used, and the parameters will be passed individually to Function. Otherwise, specify one or more of the following options. Separate each option from the next with a space (e.g. "C Fast"
).
Fast or F: Avoids starting a new thread each time Function is called. Although this performs better, it must be avoided whenever the thread from which Address is called varies (e.g. when the callback is triggered by an incoming message). This is because Function will be able to change global settings such as A_LastError and the last-found window for whichever thread happens to be running at the time it is called. For more information, see Remarks.
35 |CDecl or C: Makes Address conform to the "C" calling convention. This is typically omitted because the standard calling convention is much more common for callbacks. This option is ignored by 64-bit versions of AutoHotkey, which use the x64 calling convention.
36 |&: Causes the address of the parameter list (a single integer) to be passed to Function instead of the individual parameters. Parameter values can be retrieved by using NumGet. When using the standard 32-bit calling convention, ParamCount must specify the size of the parameter list in DWORDs (the number of bytes divided by 4).
37 |Type: Integer
42 |If omitted, it defaults to Function.MinParams, which is usually the number of mandatory parameters in the definition of Function. Otherwise, specify the number of parameters that Address's caller will pass to it. In either case, ensure that the caller passes exactly this number of parameters.
43 |Type: Integer
49 |CallbackCreate returns a machine-code address. This address is typically passed to an external function via DllCall or placed in a struct using NumPut, but can also be called directly by DllCall. Passing the address to CallbackFree will delete the callback.
50 | 51 |This function fails and throws an exception under any of the following conditions:
53 |MinParams
property nor a Call
method.MinParams
property which exceeds the number of parameters that the callback will supply.MinParams
property; or 2) the &
option is used with the standard 32-bit calling convention.A function assigned to a callback address may accept up to 31 parameters. Optional parameters are permitted, which is useful when Function is called by more than one caller.
63 |Interpreting the parameters correctly requires some understanding of how the x86 calling conventions work. Since AutoHotkey does not have typed parameters, the callback's parameter list is assumed to consist of integers, and some reinterpretation may be required.
64 | 65 |AutoHotkey 32-bit: All incoming parameters are unsigned 32-bit integers. Smaller types are padded out to 32 bits, while larger types are split into a series of 32-bit parameters.
66 |If an incoming parameter is intended to be a signed integer, any negative numbers can be revealed by following either of the following methods:
67 |; Method #1 68 | if (wParam > 0x7FFFFFFF) 69 | wParam := -(~wParam) - 1 70 | 71 | ; Method #2: Relies on the fact that AutoHotkey natively uses signed 64-bit integers. 72 | wParam := wParam << 32 >> 3273 | 74 |
AutoHotkey 64-bit: All incoming parameters are signed 64-bit integers. AutoHotkey does not natively support unsigned 64-bit integers. Smaller types are padded out to 64 bits, while larger types are always passed by address.
75 | 76 |AutoHotkey 32-bit/64-bit: If an incoming parameter is intended to be 8-bit or 16-bit (or 32-bit on x64), the upper bits of the value might contain "garbage" which can be filtered out by using bitwise-and, as in the following examples:
77 |Callback(UCharParam, UShortParam, UIntParam) { 78 | UCharParam &= 0xFF 79 | UShortParam &= 0xFFFF 80 | UIntParam &= 0xFFFFFFFF 81 | ;... 82 | }83 |
If an incoming parameter is intended by its caller to be a string, what it actually receives is the address of the string. To retrieve the string itself, use StrGet:
84 |MyString := StrGet(MyParameter)85 |
If an incoming parameter is the address of a structure, the individual members may be extracted by following the steps at DllCall structures.
86 | 87 |Receiving parameters by address: If the &
option is used, Function receives the address of the first callback parameter. For example:
89 | callback := CallbackCreate(TheFunc, "F&", 3) ; Parameter list size must be specified for 32-bit. 90 | DllCall(callback, "float", 10.5, "int64", 42) 91 | TheFunc(params) { 92 | MsgBox NumGet(params, 0, "float") ", " NumGet(params, A_PtrSize, "int64") 93 | }94 |
Most callbacks in 32-bit programs use the stdcall calling convention, which requires a fixed number of parameters. In those cases, ParamCount must be set to the size of the parameter list, where Int64 and Double count as two 32-bit parameters. With Cdecl or the 64-bit calling convention, ParamCount has no effect.
95 | 96 | 97 |If Function uses Return without any parameters, or it specifies a blank value such as "" (or it never uses Return at all), 0 is returned to the caller of the callback. Otherwise, Function should return an integer, which is then returned to the caller. AutoHotkey 32-bit truncates return values to 32-bit, while AutoHotkey 64-bit supports 64-bit return values. Returning structs larger than this (by value) is not supported.
99 | 100 |The default/slow mode causes Function to start off fresh with the default values for settings such as SendMode and DetectHiddenWindows. These defaults can be changed during script startup.
102 |By contrast, the fast mode inherits global settings from whichever thread happens to be running at the time Function is called. Furthermore, any changes Function makes to global settings (including the last-found window) will go into effect for the current thread. Consequently, the fast mode should be used only when it is known exactly which thread(s) Function will be called from.
103 |To avoid being interrupted by itself (or any other thread), a callback may use Critical as its first line. However, this is not completely effective when Function is called indirectly via the arrival of a message less than 0x0312 (increasing Critical's interval may help). Furthermore, Critical does not prevent Function from doing something that might indirectly result in a call to itself, such as calling SendMessage or DllCall.
104 | 105 |Deletes a callback and releases its reference to the function object.
107 |CallbackFree(Address)
108 | Each use of CallbackCreate allocates a small amount of memory (32 or 48 bytes plus system overhead). Since the OS frees this memory automatically when the script exits, any script that allocates a small, fixed number of callbacks can get away with not explicitly freeing the memory.
109 |However, if the function object held by the callback is of a dynamic nature (such as a closure or bound function), it can be especially important to free the callback when it is no longer needed; otherwise, the function object will not be released.
110 | 111 |DllCall, OnMessage, OnExit, OnClipboardChange, Sort's callback, Critical, PostMessage, SendMessage, Functions, Windows Messages, Threads
113 | 114 |Displays a summary of all top-level windows.
117 |EnumAddress := CallbackCreate(EnumWindowsProc, "Fast") ; Fast-mode is okay because it will be called only from this thread. 118 | 119 | DetectHiddenWindows True ; Due to fast-mode, this setting will go into effect for the callback too. 120 | 121 | ; Pass control to EnumWindows(), which calls the callback repeatedly: 122 | DllCall("EnumWindows", "Ptr", EnumAddress, "Ptr", 0) 123 | MsgBox Output ; Display the information accumulated by the callback. 124 | 125 | EnumWindowsProc(hwnd, lParam) 126 | { 127 | global Output 128 | win_title := WinGetTitle(hwnd) 129 | win_class := WinGetClass(hwnd) 130 | if win_title 131 | Output .= "HWND: " hwnd "`tTitle: " win_title "`tClass: " win_class "`n" 132 | return true ; Tell EnumWindows() to continue until all windows have been enumerated. 133 | }134 |
Demonstrates how to subclass a GUI window by redirecting its WindowProc to a new WindowProc in the script. In this case, the background color of a text control is changed to a custom color.
138 |TextBackgroundColor := 0xFFBBBB ; A custom color in BGR format. 139 | TextBackgroundBrush := DllCall("CreateSolidBrush", "UInt", TextBackgroundColor) 140 | 141 | MyGui := Gui() 142 | Text := MyGui.Add("Text",, "Here is some text that is given`na custom background color.") 143 | 144 | ; 64-bit scripts must call SetWindowLongPtr instead of SetWindowLong: 145 | SetWindowLong := A_PtrSize=8 ? "SetWindowLongPtr" : "SetWindowLong" 146 | 147 | WindowProcNew := CallbackCreate(WindowProc) ; Avoid fast-mode for subclassing. 148 | WindowProcOld := DllCall(SetWindowLong, "Ptr", MyGui.Hwnd, "Int", -4 ; -4 is GWL_WNDPROC 149 | , "Ptr", WindowProcNew, "Ptr") ; Return value must be set to "Ptr" or "UPtr" vs. "Int". 150 | 151 | MyGui.Show() 152 | 153 | WindowProc(hwnd, uMsg, wParam, lParam) 154 | { 155 | Critical 156 | if (uMsg = 0x0138 && lParam = Text.Hwnd) ; 0x0138 is WM_CTLCOLORSTATIC. 157 | { 158 | DllCall("SetBkColor", "Ptr", wParam, "UInt", TextBackgroundColor) 159 | return TextBackgroundBrush ; Return the HBRUSH to notify the OS that we altered the HDC. 160 | } 161 | ; Otherwise (since above didn't return), pass all unhandled events to the original WindowProc. 162 | return DllCall("CallWindowProc", "Ptr", WindowProcOld, "Ptr", hwnd, "UInt", uMsg, "Ptr", wParam, "Ptr", lParam) 163 | }164 | 165 |
Retrieves the current position of the caret (text insertion point).
17 | 18 |CaretFound := CaretGetPos(&OutputVarX, &OutputVarY)19 |
Type: VarRef
24 |If omitted, the corresponding value will not be stored. Otherwise, specify references to the output variables in which to store the X and Y coordinates. The retrieved coordinates are relative to the active window's client area unless overridden by using CoordMode or A_CoordModeCaret.
25 |Type: Integer (boolean)
30 |If there is no active window or the caret position cannot be determined, the function returns 0 (false) and the output variables are made blank. The function returns 1 (true) if the system returned a caret position, but this does not necessarily mean a caret is visible.
31 | 32 |Any of the output variables may be omitted if the corresponding information is not needed.
34 |Note that some windows (e.g. certain versions of MS Word) report the same caret position regardless of its actual position.
35 | 36 |Allows the user to move the caret around to see its current position displayed in an auto-update tooltip.
42 |SetTimer WatchCaret, 100 43 | WatchCaret() { 44 | if CaretGetPos(&x, &y) 45 | ToolTip "X" x " Y" y, x, y - 20 46 | else 47 | ToolTip "No caret" 48 | }49 |
Specifies one or more statements to execute if a value or error is thrown during execution of a Try statement.
16 | 17 |Catch ErrorClass as OutputVar 18 | { 19 | Statements 20 | }21 |
Type: Class
27 |The class of value that should be caught, such as Error
, TimeoutError
or MyCustomError
. This can also be a comma-delimited list of classes. Classes must be specified by their exact full name and not an arbitrary expression, as the Prototype of each class is resolved at load time. Any built-in or user-defined class can be used, even if it does not derive from Error.
If no classes are specified, the default is Error
.
To catch anything at all, use catch Any
.
A load-time error is displayed if an invalid class name is used, or if a class is inaccessible due to the presence of a local variable with the same name.
31 |Type: Variable
36 |The output variable in which to store the thrown value, which is typically an Error object. This cannot be a dynamic variable.
37 |If omitted, the thrown value cannot be accessed directly, but can still be re-thrown by using Throw with no parameter.
38 |The statements to execute if a value or error is thrown.
43 |Braces are generally not required if only a single statement is used. For details, see {...} (block).
44 |Multiple Catch statements can be used one after the other, with each one specifying a different class (or multiple classes). If the value is not an instance of any of the listed classes, it is not caught by this Try-Catch, but might be caught by one further up the call stack.
50 |Every use of Catch must belong to (be associated with) a Try statement above it. A Catch always belongs to the nearest unclaimed Try statement above it unless a block is used to change that behavior.
51 |The parameter list may optionally be enclosed in parentheses, in which case the space or tab after catch
is optional.
Catch may optionally be followed by Else, which is executed if no exception was thrown within the associated Try block.
53 |The One True Brace (OTB) style may optionally be used. For example:
54 |try { 55 | ... 56 | } catch Error { 57 | ... 58 | }59 |
Load-time errors cannot be caught, since they occur before the try statement is executed.
60 | 61 |Try, Throw, Error Object, Else, Finally, Blocks, OnError
63 | 64 |See Try.
66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /docs/lib/Chr.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the string (usually a single character) corresponding to the character code indicated by the specified number.
16 | 17 |String := Chr(Number)
18 | Type: Integer
24 |A Unicode character code between 0 and 0x10FFFF.
25 |Type: String
31 |The string corresponding to Number. This is always a single Unicode character, but for practical reasons, Unicode supplementary characters (where Number is in the range 0x10000 to 0x10FFFF) are counted as two characters. That is, the length of the return value as reported by StrLen may be 1 or 2. For further explanation, see String Encoding.
32 |If Number is 0, the return value is a string containing a binary null character, not an empty (zero-length) string. This can be safely assigned to a variable, passed to a function or concatenated with another string. However, some built-in functions may "see" only the part of the string preceding the first null character.
33 | 34 |The range and meaning of character codes depends on which string encoding is in use. Currently all AutoHotkey v2 executables are built for Unicode, so this function always accepts a Unicode character code and returns a Unicode (UTF-16) string.
36 |Common character codes include 9 (tab), 10 (linefeed), 13 (carriage return), 32 (space), 48-57 (the digits 0-9), 65-90 (uppercase A-Z), and 97-122 (lowercase a-z).
37 | 38 |Reports the string corresponding to the character code 116.
44 |MsgBox Chr(116) ; Reports "t".45 |
class Class extends Object16 | 17 |
A Class object represents a class definition; it contains static methods and properties.
18 |Each class object is based on whatever class it extends, or Object if not specified. The global class object Object
is based on Class.Prototype
, which is based on Object.Prototype
, so classes can inherit methods and properties from any of these base objects.
"Static" methods and properties are any methods and properties which are owned by the class object itself (and therefore do not apply to a specific instance), while methods and properties for instances of the class are owned by the class's Prototype.
20 |"ClassObj" is used below as a placeholder for any class object, as "Class" is the Class class itself. Ordinarily, one refers to a class object by the name given in its class definition.
21 | 22 |Constructs a new instance of the class.
40 |Obj := ClassObj(Params*)
41 | Obj := ClassObj.Call(Params*)
42 | This static method is typically inherited from the Object, Array or Map class. It performs the following functions:
43 |Call can be overridden within a class definition by defining a static method, such as static Call()
. This allows classes to modify or prevent the construction of new instances.
Note that Class()
(literally using "Class" in this case) can be used to construct a new Class object based on Class.Prototype
. However, this new object initially has no Call method as it is not a subclass of Object. It can become a subclass of Object by assigning to Base, or the Call method can be reimplemented or copied from another class. A Prototype must also be created and assigned to the class before it can be instantiated with the standard Call method.
Retrieves or sets the object on which all instances of the class are based.
58 |Proto := ClassObj.Prototype
59 | ClassObj.Prototype := Proto
60 | By default, the class's Prototype contains all instance methods and dynamic properties defined within the class definition, and can be used to retrieve references to methods or property getters/setters or define new ones. The script can also define new value properties, which act as default property values for all instances.
61 |A class's Prototype is normally based on the Prototype of its base class, so ClassObj.Prototype.base == ClassObj.base.Prototype
.
Prototype is automatically defined as an own property of any class object created by a class definition.
63 |Clicks a mouse button at the specified coordinates. It can also hold down a mouse button, turn the mouse wheel, or move the mouse.
16 |Click Options17 | 18 |
Specify one or more of the following components: Coords, WhichButton, ClickCount, DownOrUp and/or Relative. If all components are omitted, a single left click is performed at the mouse cursor's current position.
23 |The components may be spread across multiple parameters or combined into one or more strings. Each parameter may be either a single numeric component or a string containing zero or more components, where each component is separated from the next with at least one space, tab and/or comma (all within the string). For example, Click 100, 200, "R D"
is equivalent to Click "100 200 R D"
and both are valid. Parameters that are blank or omitted are ignored, as are extra commas.
Warning: Click 100 200
would be equivalent to Click "100200"
, as the two numbers would be concatenated before the function is called.
The components can appear in any order except ClickCount, which must occur somewhere to the right of Coords, if present.
26 |Coords: If omitted, the cursor's current position is used. Otherwise, specify the X and Y coordinates to which the mouse cursor is moved prior to clicking. For example, Click "100 200"
clicks the left mouse button at a specific position. Coordinates are relative to the active window's client area unless CoordMode was used to change that.
WhichButton: If omitted, it defaults to Left (the left mouse button). Otherwise, specify Left, Right, Middle (or just the first letter of each of these); or X1 (fourth button) or X2 (fifth button). For example, Click "Right"
clicks the right mouse button at the mouse cursor's current position. Left and Right correspond to the primary button and secondary button. If the user swaps the buttons via system settings, the physical positions of the buttons are swapped but the effect stays the same.
WhichButton can also be WheelUp or WU to turn the wheel upward (away from you), or WheelDown or WD to turn the wheel downward (toward you). WheelLeft (or WL) or WheelRight (or WR) may also be specified. ClickCount is the number of notches to turn the wheel. However, some applications do not obey a ClickCount value higher than 1 for the mouse wheel. For them, use the Click function multiple times by means such as Loop.
29 |ClickCount: If omitted, it defaults to 1. Otherwise, specify the number of times to click the mouse button or turn the mouse wheel. For example, Click 2
performs a double-click at the mouse cursor's current position. If Coords is specified, ClickCount must appear after it. Specify zero (0) to move the mouse without clicking; for example, Click "100 200 0"
.
DownOrUp: If omitted, each click consists of a down-event followed by an up-event. Otherwise, specify the word Down (or the letter D) to press the mouse button down without releasing it. Later, use the word Up (or the letter U) to release the mouse button. For example, Click "Down"
presses down the left mouse button and holds it.
Relative: If omitted, the X and Y coordinates will be used for absolute positioning. Otherwise, specify the word Rel or Relative to treat the coordinates as offsets from the current mouse position. In other words, the cursor will be moved from its current position by X pixels to the right (left if negative) and Y pixels down (up if negative).
32 |The Click function uses the sending method set by SendMode. To override this mode for a particular click, use a specific Send function in combination with {Click}, as in this example: SendEvent "{Click 100 200}"
.
To perform a shift-click or control-click, clicking via Send is generally easiest. For example:
38 |Send "+{Click 100 200}" ; Shift+LeftClick 39 | Send "^{Click 100 200 Right}" ; Control+RightClick40 |
Unlike Send, the Click function does not automatically release the modifier keys (Ctrl, Alt, Shift, and Win). For example, if Ctrl is currently down, Click
would produce a control-click but Send "{Click}"
would produce a normal click.
The SendPlay mode is able to successfully generate mouse events in a broader variety of games than the other modes. In addition, some applications and games may have trouble tracking the mouse if it moves too quickly, in which case SetDefaultMouseSpeed can be used to reduce the speed (but only in SendEvent mode).
42 |The BlockInput function can be used to prevent any physical mouse activity by the user from disrupting the simulated mouse events produced by the mouse functions. However, this is generally not needed for the SendInput and SendPlay modes because they automatically postpone the user's physical mouse activity until afterward.
43 |There is an automatic delay after every click-down and click-up of the mouse (except for SendInput mode and for turning the mouse wheel). Use SetMouseDelay to change the length of the delay.
44 |Send "{Click}", SendMode, CoordMode, SetDefaultMouseSpeed, SetMouseDelay, MouseClick, MouseClickDrag, MouseMove, ControlClick, BlockInput
46 |Waits until the clipboard contains data.
16 | 17 |Boolean := ClipWait(Timeout, WaitFor)18 |
If omitted, the function will wait indefinitely. Otherwise, it will wait no longer than this many seconds. To wait for a fraction of a second, specify a floating-point number, for example, 0.25 to wait for a maximum of 250 milliseconds.
25 |Type: Integer
30 |If omitted, it defaults to 0 (wait only for text or files). Otherwise, specify one of the following numbers to indicate what to wait for:
31 |0: The function is more selective, waiting specifically for text or files to appear ("text" includes anything that would produce text when you paste into Notepad).
32 |1: The function waits for data of any kind to appear on the clipboard.
33 |Other values are reserved for future use.
34 |Type: Integer (boolean)
40 |This function returns 0 (false) if the function timed out or 1 (true) otherwise (i.e. the clipboard contains data).
41 | 42 |It's better to use this function than a loop of your own that checks to see if this clipboard is blank. This is because the clipboard is never opened by this function, and thus it performs better and avoids any chance of interfering with another application that may be using the clipboard.
44 |This function considers anything convertible to text (e.g. HTML) to be text. It also considers files, such as those copied in an Explorer window via Ctrl+C, to be text. Such files are automatically converted to their filenames (with full path) whenever the clipboard variable is referred to in the script. See A_Clipboard for details.
45 |When 1 is present as the last parameter, the function will be satisfied when any data appears on the clipboard. This can be used in conjunction with ClipboardAll to save non-textual items such as pictures.
46 |While the function is in a waiting state, new threads can be launched via hotkey, custom menu item, or timer.
47 | 48 |Empties the clipboard, copies the current selection into the clipboard and waits a maximum of 2 seconds until the clipboard contains data. If ClipWait times out, an error message is shown, otherwise the clipboard contents is shown.
53 |A_Clipboard := "" ; Empty the clipboard 54 | Send "^c" 55 | if !ClipWait(2) 56 | { 57 | MsgBox "The attempt to copy text onto the clipboard failed." 58 | return 59 | } 60 | MsgBox "clipboard = " A_Clipboard 61 | return62 |
Creates an object containing everything on the clipboard (such as pictures and formatting).
17 |ClipSaved := ClipboardAll(Data, Size)18 |
ClipboardAll
itself is a class derived from Buffer
.
Omit both parameters to retrieve the current contents of the clipboard. Otherwise, specify one or both parameters to create an object containing the given binary clipboard data.
22 |A Buffer-like object or a pure integer which is the address of the binary data. The data must be in a specific format, so typically originates from a previous call to ClipboardAll. See example #2 below.
27 |Type: Integer
31 |The number of bytes of data to use. This is optional when Data is an object.
32 |Type: Object
37 |This function returns a ClipboardAll object, which has two properties (inherited from Buffer):
38 |The built-in variable A_Clipboard reflects the current contents of the Windows clipboard expressed as plain text, but can be assigned a ClipboardAll object to restore its content to the clipboard.
45 |ClipboardAll is most commonly used to save the clipboard's contents so that the script can temporarily use the clipboard for an operation. When the operation is completed, the script restores the original clipboard contents as shown in example #1 and example #2.
46 |If ClipboardAll cannot retrieve one or more of the data objects (formats) on the clipboard, they will be omitted but all the remaining objects will be stored.
47 |ClipWait may be used to detect when the clipboard contains data (optionally including non-text data).
48 |The binary data contained by the object consists of a four-byte format type, followed by a four-byte data-block size, followed by the data-block for that format. If the clipboard contained more than one format (which is almost always the case), these three items are repeated until all the formats are included. The data ends with a four-byte format type of 0.
49 | 50 |A_Clipboard, ClipWait, OnClipboardChange, #ClipboardTimeout, Buffer
52 | 53 |Saves and restores everything on the clipboard using a variable.
57 |ClipSaved := ClipboardAll() ; Save the entire clipboard to a variable of your choice. 58 | ; ... here make temporary use of the clipboard, such as for quickly pasting large amounts of text ... 59 | A_Clipboard := ClipSaved ; Restore the original clipboard. Note the use of A_Clipboard (not ClipboardAll). 60 | ClipSaved := "" ; Free the memory in case the clipboard was very large.61 |
Saves and restores everything on the clipboard using a file.
65 |; Option 1: Delete any existing file and then use FileAppend. 66 | FileDelete "Company Logo.clip" 67 | FileAppend ClipboardAll(), "Company Logo.clip" ; The file extension does not matter. 68 | 69 | ; Option 2: Use FileOpen in overwrite mode and File.RawWrite. 70 | ClipData := ClipboardAll() 71 | FileOpen("Company Logo.clip", "w").RawWrite(ClipData)72 |
To later load the file back onto the clipboard (or into a variable), follow this example:
73 |ClipData := FileRead("Company Logo.clip", "RAW") ; In this case, FileRead returns a Buffer. 74 | A_Clipboard := ClipboardAll(ClipData) ; Convert the Buffer to a ClipboardAll and assign it.75 |
Calls a native COM interface method by index.
17 | 18 |Result := ComCall(Index, ComObj , Type1, Arg1, Type2, Arg2, ReturnType)19 |
Type: Integer
25 |The zero-based index of the method within the virtual function table.
26 |Index corresponds to the position of the method within the original interface definition. Microsoft documentation usually lists methods in alphabetical order, which is not relevant. In order to determine the correct index, locate the original interface definition. This may be in a header file or type library.
27 |It is important to take into account methods which are inherited from parent interfaces. Since all COM interfaces ultimately derive from IUnknown, the first three methods are always QueryInterface (0), AddRef (1) and Release (2). For example, IShellItem2 is an extension of IShellItem, which starts at index 3 and contains 5 methods, so IShellItem2's first method (GetPropertyStore) is at index 8.
28 |Tip: For COM interfaces defined by Microsoft, try searching the Internet or Windows SDK for "IInterfaceNameVtbl" - for example, "IUnknownVtbl". Microsoft's own interface definitions are accompanied by this plain-C definition of the interface's virtual function table, which lists all methods explicitly, in the correct order.
29 |Passing an invalid index may cause undefined behaviour, including (but not limited to) program termination.
30 |The target COM object; that is, a COM interface pointer. The pointer value can be passed directly or encapsulated within an object with the Ptr
property, such as a ComValue with variant type VT_UNKNOWN.
The interface pointer is used to locate the address of the virtual function which implements the interface method, and is also passed as a parameter. This parameter is generally not explicitly present in languages which natively support interfaces, but is shown in the C style "Vtbl" definition.
37 |Passing an invalid pointer may cause undefined behaviour, including (but not limited to) program termination.
38 |Type: String
43 |Each of these pairs represents a single parameter to be passed to the method. The number of pairs is unlimited. For Type, see the DllCall types table. For Arg, specify the value to be passed to the method.
44 |Type: String
49 |If omitted, the return type defaults to HRESULT, which is most the common return type for COM interface methods. Any result indicating failure causes an OSError to be thrown; therefore, the return type must not be omitted unless the actual return type is HRESULT.
50 |If the method is of a type that does not return a value (the void
return type in C), specify "Int" or any other numeric type without any suffix (except HRESULT), and ignore the return value. As the content of the return value register is arbitrary in such cases, an exception may or may not be thrown if ReturnType is omitted.
Otherwise, specify one of the argument types from the DllCall types table. The asterisk suffix is also supported.
52 |Although ComCall supports the Cdecl keyword as per DllCall, it is generally not used by COM interface methods.
53 |If ReturnType is HRESULT (or omitted) and the method returned an error value (as defined by the FAILED macro), an OSError is thrown.
60 |Otherwise, ComCall returns the actual value returned by the method. If the method is of a type that does not return a value (with return type defined in C as void
), the result is undefined and should be ignored.
The following DllCall topics are also applicable to ComCall:
64 |ComObject, ComObjQuery, ComValue, Buffer object, CallbackCreate
75 | 76 |Removes the active window from the taskbar for 3 seconds. Compare this to the equivalent DllCall example.
80 |/* 81 | Methods in ITaskbarList's VTable: 82 | IUnknown: 83 | 0 QueryInterface -- use ComObjQuery instead 84 | 1 AddRef -- use ObjAddRef instead 85 | 2 Release -- use ObjRelease instead 86 | ITaskbarList: 87 | 3 HrInit 88 | 4 AddTab 89 | 5 DeleteTab 90 | 6 ActivateTab 91 | 7 SetActiveAlt 92 | */ 93 | IID_ITaskbarList := "{56FDF342-FD6D-11d0-958A-006097C9A090}" 94 | CLSID_TaskbarList := "{56FDF344-FD6D-11d0-958A-006097C9A090}" 95 | 96 | ; Create the TaskbarList object. 97 | tbl := ComObject(CLSID_TaskbarList, IID_ITaskbarList) 98 | 99 | activeHwnd := WinExist("A") 100 | 101 | ComCall(3, tbl) ; tbl.HrInit() 102 | ComCall(5, tbl, "ptr", activeHwnd) ; tbl.DeleteTab(activeHwnd) 103 | Sleep 3000 104 | ComCall(4, tbl, "ptr", activeHwnd) ; tbl.AddTab(activeHwnd) 105 | 106 | ; When finished with the object, simply replace any references with 107 | ; some other value (or if its a local variable, just return): 108 | tbl := "" 109 |110 |
Demonstrates some techniques for wrapping COM interfaces. Equivalent to the previous example.
114 |115 | tbl := TaskbarList() 116 | 117 | activeHwnd := WinExist("A") 118 | 119 | tbl.DeleteTab(activeHwnd) 120 | Sleep 3000 121 | tbl.AddTab(activeHwnd) 122 | 123 | tbl := "" 124 | 125 | 126 | class TaskbarList { 127 | static IID := "{56FDF342-FD6D-11d0-958A-006097C9A090}" 128 | static CLSID := "{56FDF344-FD6D-11d0-958A-006097C9A090}" 129 | 130 | ; Called on startup to initialize the class. 131 | static __new() { 132 | ; Get the base object for all instances of TaskbarList. 133 | proto := this.Prototype 134 | 135 | ; Bound functions can be used to predefine parameters, making 136 | ; the methods more usable without requiring wrapper functions. 137 | ; HrInit itself has no parameters, so bind only the index, 138 | ; and the caller will implicitly provide 'this'. 139 | proto.HrInit := ComCall.Bind(3) 140 | 141 | ; Leave a parameter blank to let the caller provide a value. 142 | ; In this case, the blank parameter is 'this' (normally hidden). 143 | proto.AddTab := ComCall.Bind(4,, "ptr") 144 | 145 | ; An object or Map can be used to reduce repetition. 146 | for name, args in Map( 147 | "DeleteTab", [5,,"ptr"], 148 | "ActivateTab", [6,,"ptr"], 149 | "SetActiveAlt", [7,,"ptr"]) { 150 | proto.%name% := ComCall.Bind(args*) 151 | } 152 | } 153 | 154 | ; Called by TaskbarList() on the new instance. 155 | __new() { 156 | this.comobj := ComObject(TaskbarList.CLSID, TaskbarList.IID) 157 | this.ptr := this.comobj.ptr 158 | ; Request initialization via ITaskbarList. 159 | this.HrInit() 160 | } 161 | } 162 |163 |
Retrieves a registered COM object.
16 |ComObj := ComObjActive(CLSID)
17 |
18 | Type: String
24 |CLSID or human-readable Prog ID of the COM object to retrieve.
25 |Type: ComObject
31 |This function returns a new COM wrapper object with the variant type VT_DISPATCH (9).
32 | 33 |An exception is thrown on failure.
35 | 36 |ComValue, ComObject, ComObjGet, ComObjConnect, ComObjFlags, ObjAddRef/ObjRelease, ComObjQuery, GetActiveObject (Microsoft Docs)
38 | 39 |Displays the active document in Microsoft Word, if it is running. For details about the COM object and its properties used below, see Word.Application object (Microsoft Docs).
42 |43 | word := ComObjActive("Word.Application") 44 | if !word 45 | MsgBox "Word isn't open." 46 | else 47 | MsgBox word.ActiveDocument.FullName48 |
Creates a SafeArray for use with COM.
16 | 17 |ArrayObj := ComObjArray(VarType, Count1 , Count2, ... Count8)18 |
ComObjArray
itself is a class derived from ComValue
, but is used only to create or identify SafeArray wrapper objects.
Type: Integer
26 | The base type of the array (the VARTYPE of each element of the array). The VARTYPE is restricted to a subset of the variant types. Neither the VT_ARRAY nor the VT_BYREF flag can be set. VT_EMPTY and VT_NULL are not valid base types for the array. All other types are legal. 27 |See ComObjType for a list of possible values.
28 |Type: Integer
33 |The size of each dimension. Arrays containing up to 8 dimensions are supported.
34 |Type: ComObjArray
40 |This function returns a wrapper object containing a new SafeArray.
41 | 42 |ComObjArray objects support the following methods:
44 |.MaxIndex(n)
: Returns the upper bound of the nth dimension. If n is omitted, it defaults to 1..MinIndex(n)
: Returns the lower bound of the nth dimension. If n is omitted, it defaults to 1..Clone()
: Returns a copy of the array..__Enum()
: Not typically called by script; allows for-loops to be used with SafeArrays.ComObjArray objects may also be returned by COM methods and ComValue. Scripts may determine if a value is a ComObjArray as follows:
53 |; Check class 54 | if obj is ComObjArray 55 | MsgBox "Array subtype: " . ComObjType(obj) & 0xfff 56 | else 57 | MsgBox "Not an array." 58 | 59 | ; Check for VT_ARRAY 60 | if ComObjType(obj) & 0x2000 61 | MsgBox "obj is a ComObjArray" 62 | 63 | ; Check specific array type 64 | if ComObjType(obj) = 0x2008 65 | MsgBox "obj is a ComObjArray of strings"66 |
Arrays with up to 8 dimensions are supported.
67 |Since SafeArrays are not designed to support multiple references, when one SafeArray is assigned to an element of another SafeArray, a separate copy is created. However, this only occurs if the wrapper object has the F_OWNVALUE flag, which indicates it is responsible for destroying the array. This flag can be removed by using ComObjFlags.
68 |When a function or method called by a COM client returns a SafeArray with the F_OWNVALUE flag, a copy is created and returned instead, as the original SafeArray is automatically destroyed.
69 | 70 |ComValue, ComObjType, ComObjValue, ComObjActive, ComObjFlags, Array Manipulation Functions (Microsoft Docs)
72 | 73 |arr := ComObjArray(VT_VARIANT:=12, 3) 77 | arr[0] := "Auto" 78 | arr[1] := "Hot" 79 | arr[2] := "key" 80 | t := "" 81 | Loop arr.MaxIndex() + 1 82 | t .= arr[A_Index-1] 83 | MsgBox t 84 |85 |
arr := ComObjArray(VT_VARIANT:=12, 3, 4) 90 | 91 | ; Get the number of dimensions: 92 | dim := DllCall("oleaut32\SafeArrayGetDim", "ptr", ComObjValue(arr)) 93 | 94 | ; Get the bounds of each dimension: 95 | dims := "" 96 | Loop dim 97 | dims .= arr.MinIndex(A_Index) " .. " arr.MaxIndex(A_Index) "`n" 98 | MsgBox dims 99 | 100 | ; Simple usage: 101 | Loop 3 { 102 | x := A_Index-1 103 | Loop 4 { 104 | y := A_Index-1 105 | arr[x, y] := x * y 106 | } 107 | } 108 | MsgBox arr[2, 3] 109 |110 |
Connects a COM object's event source to the script, enabling events to be handled.
15 |ComObjConnect ComObj , PrefixOrSink16 | 17 |
Type: ComObject
23 |An object which raises events.
24 |If the object does not support the IConnectionPointContainer interface or type information about the object's class cannot be retrieved, an error message is shown. This can be suppressed or handled with try/catch.
25 |The IProvideClassInfo interface is used to retrieve type information about the object's class if the object supports it. Otherwise, ComObjConnect attempts to retrieve type information via the object's IDispatch interface, which may be unreliable.
26 |If omitted, the object is "disconnected"; that is, the script will no longer receive notification of its events. Otherwise, specify a string to prefix to the event name to determine which global function to call when an event occurs, or an event sink object defining a static method for each event to be handled.
32 |Note: Nested functions are not supported in this mode, as names may be resolved after the current function returns. To use nested functions or closures, attach them to an object and pass the object as described below.
33 |To make effective use of ComObjConnect, you must first write functions in the script to handle any events of interest. Such functions, or "event-handlers," have the following structure:
39 |PrefixEventName([Params..., ComObj]) 40 | { 41 | ... event-handling code ... 42 | return ReturnValue 43 | }44 |
Prefix should be the same as the PrefixOrSink parameter if it is a string; otherwise, it should be omitted. EventName should be replaced with the name of whatever event the function should handle.
45 |Params corresponds to whatever parameters the event has. If the event has no parameters, Params should be omitted entirely. ComObj is an additional parameter containing a reference to the original wrapper object which was passed to ComObjConnect; it is never included in the COM event's documentation. "ComObj" should be replaced with a name more meaningful in the context of your script.
46 |Note that event handlers may have return values. To return a COM-specific type of value, use ComValue. For example, return ComValue(0,0)
returns a variant of type VT_EMPTY, which is equivalent to returning undefined
(or not returning) from a JavaScript function.
Call ComObjConnect(yourObject, "Prefix")
to enable event-handling.
Call ComObjConnect(yourObject)
to disconnect the object (stop handling events).
If the number of parameters is not known, a variadic function can be used.
50 | 51 |If PrefixOrSink is an object, whenever an event is raised, the corresponding method of that object is called. Although the object can be constructed dynamically, it is more typical for PrefixOrSink to refer to a class or an instance of a class. In that case, methods are defined as shown above, but without Prefix.
53 |As with any call to a method, the method's (normally hidden) this
parameter contains a reference to the object through which the method was called; i.e. the event sink object, not the COM object. This can be used to provide context to the event handlers, or share values between them.
To catch all events without defining a method for each one, define a __Call meta-function.
55 |ComObject releases its reference to PrefixOrSink automatically if the COM object releases the connection. For example, Internet Explorer does this when it exits. If the script does not retain its own reference to PrefixOrSink, it can use __Delete to detect when this occurs. If the object is hosted by a remote process and the process terminates unexpectedly, it may take several minutes for the system to release the connection.
56 | 57 |The script must retain a reference to ComObj, otherwise it would be freed automatically and would disconnect from its COM object, preventing any further events from being detected. There is no standard way to detect when the connection is no longer required, so the script must disconnect manually by calling ComObjConnect.
59 |The Persistent function may be needed to keep the script running while it is listening for events.
60 |An exception is thrown on failure.
61 | 62 |ComObject, ComObjGet, ComObjActive, WScript.ConnectObject (Microsoft Docs)
64 | 65 |Launches an instance of Internet Explorer and connects events to corresponding script functions with the prefix "IE_". For details about the COM object and DocumentComplete event used below, see InternetExplorer object (Microsoft Docs).
68 |ie := ComObject("InternetExplorer.Application") 69 | 70 | ; Connects events to corresponding script functions with the prefix "IE_". 71 | ComObjConnect(ie, "IE_") 72 | 73 | ie.Visible := true ; This is known to work incorrectly on IE7. 74 | ie.Navigate("https://www.autohotkey.com/") 75 | Persistent 76 | 77 | IE_DocumentComplete(ieEventParam, &url, ieFinalParam) { 78 | ; IE passes url as a reference to a VARIANT, therefore &url is used above 79 | ; so that the code below can refer to it naturally rather than as %url%. 80 | s := "" 81 | if (ie != ieEventParam) 82 | s .= "First parameter is a new wrapper object.`n" 83 | if (ie == ieFinalParam) 84 | s .= "Final parameter is the original wrapper object.`n" 85 | if (ComObjValue(ieEventParam) == ComObjValue(ieFinalParam)) 86 | s .= "Both wrapper objects refer to the same IDispatch instance.`n" 87 | MsgBox s . "Finished loading " ie.Document.title " @ " url 88 | ie.Quit() 89 | ExitApp 90 | } 91 |92 |
Retrieves or changes flags which control a COM wrapper object's behaviour.
16 |Flags := ComObjFlags(ComObj , NewFlags, Mask)17 | 18 |
Type: Object
24 |A COM wrapper object. See ComValue for details.
25 |Type: Integer
30 |New values for the flags identified by Mask, or flags to add or remove.
31 |Type: Integer
36 |A bitmask of flags to change.
37 |Type: Integer
43 |This function returns the current flags of the specified COM object (after applying NewFlags, if specified).
44 | 45 |A TypeError is thrown if ComObj is not a COM wrapper object.
47 | 48 |Flag | 52 |Effect | 53 |
---|---|
1 | 56 |
57 | F_OWNVALUE 58 |SafeArray: If the flag is set, the SafeArray is destroyed when the wrapper object is freed. Since SafeArrays have no reference counting mechanism, if a SafeArray with this flag is assigned to an element of another SafeArray, a separate copy is created. 59 |BSTR: If the flag is set, the BSTR is freed when the wrapper object is freed. The flag is set automatically when a BSTR is allocated as a result of type conversion performed by ComValue, such as |
61 |
If Mask is omitted, NewFlags specifies the flags to add (if positive) or remove (if negative). For example, ComObjFlags(obj, -1)
removes the F_OWNVALUE flag. Do not specify any value for Mask other than 0 or 1; all other bits are reserved for future use.
ComValue, ComObjActive, ComObjArray
69 | 70 |Checks for the presence of the F_OWNVALUE flag.
73 |arr := ComObjArray(0xC, 1) 74 | if ComObjFlags(arr) & 1 75 | MsgBox "arr will be automatically destroyed." 76 | else 77 | MsgBox "arr will not be automatically destroyed." 78 |79 |
Changes array-in-array behaviour.
83 |arr1 := ComObjArray(0xC, 3) 84 | arr2 := ComObjArray(0xC, 1) 85 | arr2[0] := "original value" 86 | arr1[0] := arr2 ; Assign implicit copy. 87 | ComObjFlags(arr2, -1) ; Remove F_OWNVALUE. 88 | arr1[1] := arr2 ; Assign original array. 89 | arr1[2] := arr2.Clone() ; Assign explicit copy. 90 | arr2[0] := "new value" 91 | for arr in arr1 92 | MsgBox arr[0] 93 | 94 | arr1 := "" 95 | ; Not valid since arr2 == arr1[1], which has been destroyed: 96 | ; arr2[0] := "foo" 97 |98 |
Wraps a raw IDispatch pointer (COM object) for use by the script.
17 |ComObj := ComObjFromPtr(DispPtr)
18 |
19 | Type: Integer
25 |A non-null interface pointer for IDispatch or a derived interface.
26 |Type: ComObject
32 |Returns a wrapper object containing the variant type VT_DISPATCH and the given pointer.
33 |Wrapping a COM object enables the script to interact with it more naturally, using object syntax. However, the majority of scripts do not need to do this manually since a wrapper object is created automatically by ComObject, ComObjActive, ComObjGet and any COM method which returns an object.
34 | 35 |The wrapper object assumes responsibility for automatically releasing the pointer when appropriate. This function queries the object for its IDispatch interface; if one is returned, DispPtr is immediately released. Therefore, if the script intends to use the pointer after calling this function, it must call ObjAddRef(DispPtr)
first.
Known limitation: Each time a COM object is wrapped, a new wrapper object is created. Comparisons and assignments such as obj1 == obj2
and arr[obj1] := value
treat the two wrapper objects as unique, even when they contain the same COM object.
ComObject, ComValue, ComObjGet, ComObjConnect, ComObjFlags, ObjAddRef/ObjRelease, ComObjQuery, GetActiveObject (Microsoft Docs)
41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /docs/lib/ComObjGet.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns a reference to an object provided by a COM component.
15 |ComObj := ComObjGet(Name)
16 |
17 | Type: String
23 |The display name of the object to be retrieved. See MkParseDisplayName (Microsoft Docs) for more information.
24 |Type: ComObject
30 |This function returns a new COM wrapper object with the variant type VT_DISPATCH (9).
31 | 32 |An exception is thrown on failure.
34 | 35 |Press Shift+Esc to show the command line which was used to launch the active window's process. For Win32_Process, see Microsoft Docs.
41 |+Esc:: 42 | { 43 | pid := WinGetPID("A") 44 | ; Get WMI service object. 45 | wmi := ComObjGet("winmgmts:") 46 | ; Run query to retrieve matching process(es). 47 | queryEnum := wmi.ExecQuery("" 48 | . "Select * from Win32_Process where ProcessId=" . pid) 49 | ._NewEnum() 50 | ; Get first matching process. 51 | if queryEnum(&proc) 52 | MsgBox(proc.CommandLine, "Command line", 0) 53 | else 54 | MsgBox("Process not found!") 55 | }56 |
Queries a COM object for an interface or service.
15 |InterfaceComObj := ComObjQuery(ComObj, SID, IID) 16 | InterfaceComObj := ComObjQuery(ComObj, IID)17 | 18 |
A COM wrapper object, an interface pointer, or an object with a Ptr
property which returns an interface pointer. See ComValue for details.
Type: String
30 |An interface identifier (GUID) in the form "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}".
31 |Type: String
36 |A service identifier in the same form as IID.
37 |Type: Object
43 |This function returns a COM wrapper object of type dependent on the IID parameter.
44 |IID | Class | Variant Type | Description |
---|---|---|---|
IID_IDispatch | 48 |ComObject |
49 | VT_DISPATCH (9) | 50 |Allows the script to call properties and methods of the object using normal object syntax. | 51 |
Any other IID | 54 |ComValue |
55 | VT_UNKNOWN (13) | 56 |Provides only a Ptr property, which allows the object to be passed to DllCall or ComCall. |
57 |
An exception is thrown on failure, such as if the interface is not supported.
62 | 63 |In its two-parameter mode, this function is equivalent to IUnknown::QueryInterface. When SID and IID are both specified, it internally queries for the IServiceProvider interface, then calls IServiceProvider::QueryService.
65 |ComCall can be used to call native interface methods.
66 | 67 |ComCall, ComObject, ComObjGet, ComObjActive
69 | 70 |Determines the class name of an object.
73 |74 | obj := ComObject("Scripting.Dictionary") 75 | 76 | MsgBox "Interface name: " ComObjType(obj, "name") 77 | 78 | IID_IProvideClassInfo := "{B196B283-BAB4-101A-B69C-00AA00341D07}" 79 | 80 | ; Request the object's IProvideClassInfo interface. 81 | try 82 | pci := ComObjQuery(obj, IID_IProvideClassInfo) 83 | catch 84 | { 85 | MsgBox "IProvideClassInfo interface not supported." 86 | return 87 | } 88 | 89 | ; Call GetClassInfo to retrieve a pointer to the ITypeInfo interface. 90 | ComCall(3, pci, "ptr*", &ti := 0) 91 | 92 | ; Wrap ti to ensure automatic cleanup. 93 | ti := ComValue(13, ti) 94 | 95 | ; Call GetDocumentation to get the object's full type name. 96 | ComCall(12, ti, "int", -1, "ptr*", &pname := 0, "ptr", 0, "ptr", 0, "ptr", 0) 97 | 98 | ; Convert the BSTR pointer to a usable string. 99 | name := StrGet(pname, "UTF-16") 100 | 101 | ; Clean up. 102 | DllCall("oleaut32\SysFreeString", "ptr", pname) 103 | pci := ti := "" 104 | 105 | ; Display the type name! 106 | MsgBox "Class name: " name 107 |108 |
Automates an existing Internet Explorer window.
112 |113 | sURL := "https://www.autohotkey.com/boards/" 114 | if WebBrowser := GetWebBrowser() 115 | WebBrowser.Navigate(sURL) 116 | 117 | GetWebBrowser() 118 | { 119 | ; Get a raw pointer to the document object of the top-most IE window. 120 | static msg := DllCall("RegisterWindowMessage", "Str", "WM_HTML_GETOBJECT") 121 | lResult := SendMessage(msg, 0, 0, "Internet Explorer_Server1", "ahk_class IEFrame") 122 | if !lResult 123 | return ; IE not found. 124 | static IID_IHTMLDocument2 := GUID("{332C4425-26CB-11D0-B483-00C04FD90119}") 125 | static VT_UNKNOWN := 13 126 | DllCall("oleacc\ObjectFromLresult", "Ptr", lResult 127 | , "Ptr", IID_IHTMLDocument2, "Ptr", 0 128 | , "Ptr*", pdoc := ComValue(VT_UNKNOWN, 0)) 129 | 130 | ; Query for the WebBrowserApp service. In this particular case, 131 | ; the SID and IID are the same, but it isn't always this way. 132 | static IID_IWebBrowserApp := "{0002DF05-0000-0000-C000-000000000046}" 133 | static SID_SWebBrowserApp := IID_IWebBrowserApp 134 | pweb := ComObjQuery(pdoc, SID_SWebBrowserApp, IID_IWebBrowserApp) 135 | 136 | ; Return the WebBrowser object as IDispatch for usability. 137 | ; This works only because IWebBrowserApp is derived from IDispatch. 138 | ; pweb will release its ptr automatically, so AddRef to counter that. 139 | ObjAddRef(pweb.ptr) 140 | static VT_DISPATCH := 9 141 | return ComValue(VT_DISPATCH, pweb.ptr) 142 | } 143 | 144 | GUID(sGUID) ; Converts a string to a binary GUID and returns it in a Buffer. 145 | { 146 | GUID := Buffer(16, 0) 147 | if DllCall("ole32\CLSIDFromString", "WStr", sGUID, "Ptr", GUID) < 0 148 | throw ValueError("Invalid parameter #1", -1, sGUID) 149 | return GUID 150 | } 151 |152 |
Retrieves type information from a COM object.
16 | 17 |Info := ComObjType(ComObj , InfoType)18 | 19 |
Type: Object
25 |A wrapper object containing a COM object or typed value. See ComValue for details.
26 |Type: String
31 |If omitted, an integer variant type code indicating the type of value contained by the COM wrapper object will be retrieved. Otherwise, specify one of the following strings indicating the type information to retrieve:
32 |Name: The name of the object's default interface.
33 |IID: The globally unique identifier (GUID) of the object's default interface.
34 |Class: The object's class name. Note that this is not the same as a Prog ID (a Prog ID is a name used to identify the class in the system registry, or for ComObject).
35 |CLSID: The globally unique identifier (GUID) of the object's class. Classes are often registered by CLSID under the HKCR\CLSID
registry key.
The return value depends on the value of InfoType. An empty string is returned if either parameter is invalid or if the requested type information could not be retrieved.
43 | 44 |COM uses the following values to identify basic data types:
46 |47 | VT_EMPTY := 0 ; No value 48 | VT_NULL := 1 ; SQL-style Null 49 | VT_I2 := 2 ; 16-bit signed int 50 | VT_I4 := 3 ; 32-bit signed int 51 | VT_R4 := 4 ; 32-bit floating-point number 52 | VT_R8 := 5 ; 64-bit floating-point number 53 | VT_CY := 6 ; Currency 54 | VT_DATE := 7 ; Date 55 | VT_BSTR := 8 ; COM string (Unicode string with length prefix) 56 | VT_DISPATCH := 9 ; COM object 57 | VT_ERROR := 0xA ; Error code (32-bit integer) 58 | VT_BOOL := 0xB ; Boolean True (-1) or False (0) 59 | VT_VARIANT := 0xC ; VARIANT (must be combined with VT_ARRAY or VT_BYREF) 60 | VT_UNKNOWN := 0xD ; IUnknown interface pointer 61 | VT_DECIMAL := 0xE ; (not supported) 62 | VT_I1 := 0x10 ; 8-bit signed int 63 | VT_UI1 := 0x11 ; 8-bit unsigned int 64 | VT_UI2 := 0x12 ; 16-bit unsigned int 65 | VT_UI4 := 0x13 ; 32-bit unsigned int 66 | VT_I8 := 0x14 ; 64-bit signed int 67 | VT_UI8 := 0x15 ; 64-bit unsigned int 68 | VT_INT := 0x16 ; Signed machine int 69 | VT_UINT := 0x17 ; Unsigned machine int 70 | VT_RECORD := 0x24 ; User-defined type -- NOT SUPPORTED 71 | VT_ARRAY := 0x2000 ; SAFEARRAY 72 | VT_BYREF := 0x4000 ; Pointer to another type of value 73 | /* 74 | VT_ARRAY and VT_BYREF are combined with another value (using bitwise OR) 75 | to specify the exact type. For instance, 0x2003 identifies a SAFEARRAY 76 | of 32-bit signed integers and 0x400C identifies a pointer to a VARIANT. 77 | */ 78 |79 | 80 |
In most common cases, return values from methods or properties of COM objects are converted to an appropriate data type supported by AutoHotkey. Types which aren't specifically handled are coerced to strings via VariantChangeType; if this fails or if the variant type contains the VT_ARRAY or VT_BYREF flag, an object containing both the value and its type is returned instead.
82 |For any variable x, if ComObjType(x)
returns an integer, x contains a COM object wrapper.
If InfoType is "Name"
or "IID"
, type information is retrieved via the IDispatch::GetTypeInfo interface method. ComObj's variant type must be VT_DISPATCH.
If InfoType is "Class"
or "CLSID"
, type information is retrieved via the IProvideClassInfo::GetClassInfo interface method. ComObj's variant type must be VT_DISPATCH or VT_UNKNOWN, and the object must implement the IProvideClassInfo interface (some objects do not).
ComObjValue, ComValue, ComObject, ComObjGet, ComObjActive
88 | 89 |Reports various type information of a COM object.
92 |93 | d := ComObject("Scripting.Dictionary") 94 | MsgBox 95 | ( 96 | "Variant type:`t" ComObjType(d) " 97 | Interface name:`t" ComObjType(d, "Name") " 98 | Interface ID:`t" ComObjType(d, "IID") " 99 | Class name:`t" ComObjType(d, "Class") " 100 | Class ID (CLSID):`t" ComObjType(d, "CLSID") 101 | )102 |
Retrieves the value or pointer stored in a COM wrapper object.
16 | 17 |Value := ComObjValue(ComObj)
18 |
19 | Type: Object
25 |A wrapper object containing a COM object or typed value. See ComValue for details.
26 |Type: Integer
32 |This function returns a 64-bit signed integer.
33 | 34 |A TypeError is thrown if ComObj is not a COM wrapper object.
36 | 37 |This function is not intended for general use.
39 |Calling ComObjValue is equivalent to variant.llVal
, where ComObj is treated as a VARIANT structure. Any script which uses this function must be aware what type of value the wrapper object contains and how it should be treated. For instance, if an interface pointer is returned, Release should not be called, but AddRef may be required depending on what the script does with the pointer.
ComObjType, ComObject, ComObjGet, ComObjActive
43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /docs/lib/ComObject.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Creates a COM object.
16 |ComObj := ComObject(CLSID , IID)17 |
ComObject
itself is a class derived from ComValue
, but is used only to create or identify COM objects.
Type: String
25 |CLSID or human-readable Prog ID of the COM object to create.
26 |Type: String
31 |If omitted, it defaults to "{00020400-0000-0000-C000-000000000046}"
(IID_IDispatch). Otherwise, specify the identifier of the interface to return. In most cases this is omitted.
Type: Object
38 |This function returns a COM wrapper object of type dependent on the IID parameter.
39 |IID | Class | Variant Type | Description |
---|---|---|---|
IID_IDispatch | 43 |ComObject |
44 | VT_DISPATCH (9) | 45 |Allows the script to call properties and methods of the object using normal object syntax. | 46 |
Any other IID | 49 |ComValue |
50 | VT_UNKNOWN (13) | 51 |Provides only a Ptr property, which allows the object to be passed to DllCall or ComCall. |
52 |
An exception is thrown on failure, such as if a parameter is invalid or the object does not support the interface specified by IID.
57 | 58 |ComValue, ComObjGet, ComObjActive, ComObjConnect, ComObjArray, ComObjQuery, ComCall, CreateObject (Microsoft Docs)
60 | 61 |For a long list of v1.1 examples, see this archived forum thread.
63 |Launches an instance of Internet Explorer, makes it visible and navigates to a website.
65 |ie := ComObject("InternetExplorer.Application") 66 | ie.Visible := true ; This is known to work incorrectly on IE7. 67 | ie.Navigate("https://www.autohotkey.com/") 68 |69 |
Retrieves the path of the desktop's current wallpaper.
72 |73 | AD_GETWP_BMP := 0 74 | AD_GETWP_LAST_APPLIED := 0x00000002 75 | CLSID_ActiveDesktop := "{75048700-EF1F-11D0-9888-006097DEACF9}" 76 | IID_IActiveDesktop := "{F490EB00-1240-11D1-9888-006097DEACF9}" 77 | cchWallpaper := 260 78 | GetWallpaper := 4 79 | 80 | AD := ComObject(CLSID_ActiveDesktop, IID_IActiveDesktop) 81 | wszWallpaper := Buffer(cchWallpaper * 2) 82 | ComCall(GetWallpaper, AD, "ptr", wszWallpaper, "uint", cchWallpaper, "uint", AD_GETWP_LAST_APPLIED) 83 | Wallpaper := StrGet(wszWallpaper, "UTF-16") 84 | MsgBox "Wallpaper: " Wallpaper 85 |86 |
Wraps a value, SafeArray or COM object for use by the script or for passing to a COM method.
17 |ComObj := ComValue(VarType, Value , Flags)18 |
ComValue
itself is a class derived from Any
, but is used only to create or identify COM wrapper objects.
Type: Integer
26 |An integer indicating the type of value. See ComObjType for a list of types.
27 |Type: Any
32 |The value to wrap.
33 |If this is a pure integer and VarType is not VT_R4, VT_R8, VT_DATE or VT_CY, its value is used directly; in particular, VT_BSTR, VT_DISPATCH and VT_UNKNOWN can be initialized with a pointer value.
34 |In any other case, the value is copied into a temporary VARIANT using the same rules as normal COM methods calls. If the source variant type is not equal to VarType, conversion is attempted by calling VariantChangeType with a wFlags value of 0. An exception is thrown if conversion fails.
35 |Type: Integer
40 |Flags affecting the behaviour of the wrapper object; see ComObjFlags for details.
41 |Type: Object
47 |This function returns a wrapper object containing a variant type and value or pointer, specifically ComValue, ComValueRef, ComObjArray or ComObject.
48 |This object has multiple uses:
49 |ComValue(0xB, true)
creates an object which represents the COM boolean value true.If a wrapper object's VarType is VT_UNKNOWN (13) or includes the VT_BYREF (0x4000) flag or VT_ARRAY (0x2000) flag, the Ptr
property can be used to retrieve the address of the object, typed variable or SafeArray. This allows the ComObject itself to be passed to any DllCall or ComCall parameter which has the "Ptr"
type, but can also be used explicitly. For example, ComObj.Ptr
is equivalent to ComObjValue(ComObj)
in these cases.
If a wrapper object's VarType is VT_UNKNOWN (13) or VT_DISPATCH (9) and the wrapped pointer is null (0), the Ptr
property can be used to retrieve the current null value or to assign a pointer to the wrapper object. Once assigned (if non-null), the pointer will be released automatically when the wrapper object is freed. This can be used with DllCall or ComCall output parameters of type "Ptr*"
or "PtrP"
to ensure the pointer will be released automatically, such as if an error occurs. For an example, see ComObjQuery.
When a wrapper object with VarType VT_DISPATCH (9) and a null (0) pointer value is assigned a non-null pointer value, its type changes from ComValue
to ComObject
. The properties and methods of the wrapped object become available and the Ptr
property becomes unavailable.
If a wrapper object's VarType includes the VT_BYREF (0x4000) flag, empty brackets []
can be used to read or write the referenced value.
When creating a reference, Value must be the memory address of a variable or buffer with sufficient capacity to store a value of the given type. For example, the following can be used to create a variable which a VBScript function can write into:
63 |vbuf := Buffer(24, 0) 64 | vref := ComValue(0x400C, vbuf.ptr) ; 0x400C is a combination of VT_BYREF and VT_VARIANT. 65 | 66 | vref[] := "in value" 67 | sc.Run("Example", vref) ; sc should be initialized as in the example below. 68 | MsgBox vref[]69 |
Note that although any previous value is freed when a new value is assigned by vref[]
or the COM method, the final value is not freed automatically. Freeing the value requires knowing which type it is. Because it is VT_VARIANT in this case, it can be freed by calling VariantClear with DllCall or by using a simpler method: assign an integer, such as vref[] := 0
.
If the method accepts a combination of VT_BYREF and VT_VARIANT as shown above, a VarRef can be used instead. For example:
71 |some_var := "in value" 72 | sc.Run("Example", &some_var) 73 | MsgBox some_var74 |
However, some methods require a more specific variant type, such as VT_BYREF | VT_I4
. In such cases, the first approach shown above must be used, replacing 0x400C with the appropriate variant type.
When this function is used to wrap an IDispatch or IUnknown interface pointer (passed as an integer), the wrapper object assumes responsibility for automatically releasing the pointer when appropriate. Therefore, if the script intends to use the pointer after calling this function, it must call ObjAddRef(DispPtr)
first. By contrast, this is not necessary if Value is itself a ComValue or ComObject.
Conversion from VT_UNKNOWN to VT_DISPATCH results in a call to IUnknown::QueryInterface, which may produce an interface pointer different to the original, and will throw an exception if the object does not implement IDispatch. By contrast, if Value is an integer and VarType is VT_DISPATCH, the value is used directly, and therefore must be an IDispatch-compatible interface pointer.
79 |The VarType of a wrapper object can be retrieved using ComObjType.
80 |The Value of a wrapper object can be retrieved using ComObjValue.
81 |Known limitation: Each time a COM object is wrapped, a new wrapper object is created. Comparisons and assignments such as obj1 == obj2
and arr[obj1] := value
treat the two wrapper objects as unique, even when they contain the same variant type and value.
ComObjFromPtr, ComObject, ComObjGet, ComObjConnect, ComObjFlags, ObjAddRef/ObjRelease, ComObjQuery, GetActiveObject (Microsoft Docs)
85 | 86 |Passes a VARIANT ByRef to a COM function.
89 |90 | #Requires AutoHotkey v2 32-bit ; 32-bit for ScriptControl. 91 | code := " 92 | ( 93 | Sub Example(Var) 94 | MsgBox Var 95 | Var = "out value!" 96 | End Sub 97 | )" 98 | sc := ComObject("ScriptControl"), sc.Language := "VBScript", sc.AddCode(code) 99 | 100 | 101 | ; Example: Pass a VARIANT ByRef to a COM method. 102 | var := ComVar() 103 | var[] := "in value" 104 | sc.Run("Example", var.ref) 105 | MsgBox var[] 106 | 107 | ; The same thing again, but more direct: 108 | variant_buf := Buffer(24, 0) ; Make a buffer big enough for a VARIANT. 109 | var := ComValue(0x400C, variant_buf.ptr) ; Make a reference to a VARIANT. 110 | var[] := "in value" 111 | sc.Run("Example", var) ; Pass the VT_BYREF ComValue itself, no [] or .ref. 112 | MsgBox var[] 113 | ; If a VARIANT contains a string or object, it must be explicitly freed 114 | ; by calling VariantClear or assigning a pure numeric value: 115 | var[] := 0 116 | 117 | ; The simplest way when the method accepts VT_BYREF|VT_VARIANT: 118 | var := "in value" 119 | sc.Run("Example", &var) 120 | MsgBox var 121 | 122 | 123 | ; ComVar: An object which can be used to pass a value ByRef. 124 | ; this[] retrieves the value. 125 | ; this[] := Val sets the value. 126 | ; this.ref retrieves a ByRef object for passing to a COM method. 127 | class ComVar { 128 | __new(vType := 0xC) { 129 | ; Allocate memory for a VARIANT to hold our value. VARIANT is used even 130 | ; when vType != VT_VARIANT so that VariantClear can be used by __delete. 131 | this.var := Buffer(24, 0) 132 | ; Create an object which can be used to pass the variable ByRef. 133 | this.ref := ComValue(0x4000|vType, this.var.ptr + (vType=0xC ? 0 : 8)) 134 | ; Store the variant type for VariantClear (if not VT_VARIANT). 135 | if vType != 0xC 136 | NumPut "ushort", vType, this.var 137 | } 138 | __item { 139 | get => this.ref[] 140 | set => this.ref[] := value 141 | } 142 | __delete() { 143 | DllCall("oleaut32\VariantClear", "ptr", this.var) 144 | } 145 | } 146 |147 |
Skips the rest of a loop statement's current iteration and begins a new one.
15 |Continue LoopLabel16 | 17 |
If omitted or 1, this statement applies to the innermost loop in which it is enclosed. Otherwise, specify which loop this statement should apply to; either by label name or numeric nesting level. If a label is specified, it must point directly at a loop statement.
22 |LoopLabel must be a constant value - variables and expressions are not supported, with the exception of a single literal number or quoted string enclosed in parentheses. For example: continue("outer")
Continue behaves the same as reaching the loop's closing brace:
28 |The use of Break and Continue are encouraged over Goto since they usually make scripts more readable and maintainable.
34 | 35 |Break, Loop, Until, While-loop, For-loop, Blocks, Labels
37 | 38 |Displays 5 message boxes, one for each number between 6 and 10. Note that in the first 5 iterations of the loop, the Continue statement causes the loop to start over before it reaches the MsgBox line.
41 |42 | Loop 10 43 | { 44 | if (A_Index <= 5) 45 | continue 46 | MsgBox A_Index 47 | }48 |
Continues the outer loop from within a nested loop.
52 |outer: 53 | Loop 3 54 | { 55 | x := A_Index 56 | Loop 3 57 | { 58 | if (x*A_Index = 4) 59 | continue outer ; Equivalent to continue 2 or goto continue_outer. 60 | MsgBox x "," A_Index 61 | } 62 | continue_outer: ; For goto. 63 | }64 |
Functions for retrieving information about a control or for performing various operations on a control. Click on a function name for details.
16 |Function | 19 |Description | 20 |
---|---|
ControlAddItem | 23 |Adds the specified string as a new entry at the bottom of a ListBox or ComboBox. | 24 |
ControlChooseIndex | 27 |Sets the selection in a ListBox, ComboBox or Tab control to be the Nth item. | 28 |
ControlChooseString | 31 |Sets the selection in a ListBox or ComboBox to be the first entry whose leading part matches the specified string. | 32 |
ControlClick | 35 |Sends a mouse button or mouse wheel event to a control. | 36 |
ControlDeleteItem | 39 |Deletes the specified entry number from a ListBox or ComboBox. | 40 |
ControlFindItem | 43 |Returns the entry number of a ListBox or ComboBox that is a complete match for the specified string. | 44 |
ControlFocus | 47 |Sets input focus to a given control on a window. | 48 |
ControlGetChecked | 51 |Returns a non-zero value if the checkbox or radio button is checked. | 52 |
ControlGetChoice | 55 |Returns the name of the currently selected entry in a ListBox or ComboBox. | 56 |
ControlGetClassNN | 59 |Returns the ClassNN (class name and sequence number) of the specified control. | 60 |
ControlGetEnabled | 63 |Returns a non-zero value if the specified control is enabled. | 64 |
ControlGetFocus | 67 |Retrieves which control of the target window has keyboard focus, if any. | 68 |
ControlGetHwnd | 71 |Returns the unique ID number of the specified control. | 72 |
ControlGetIndex | 75 |Returns the index of the currently selected entry or tab in a ListBox, ComboBox or Tab control. | 76 |
ControlGetItems | 79 |Returns an array of items/rows from a ListBox, ComboBox, or DropDownList. | 80 |
ControlGetPos | 83 |Retrieves the position and size of a control. | 84 |
ControlGetStyle ControlGetExStyle |
87 | Returns an integer representing the style or extended style of the specified control. | 88 |
ControlGetText | 91 |Retrieves text from a control. | 92 |
ControlGetVisible | 95 |Returns a non-zero value if the specified control is visible. | 96 |
ControlHide | 99 |Hides the specified control. | 100 |
ControlHideDropDown | 103 |Hides the drop-down list of a ComboBox control. | 104 |
ControlMove | 107 |Moves or resizes a control. | 108 |
ControlSend ControlSendText |
111 | Sends simulated keystrokes or text to a window or control. | 112 |
ControlSetChecked | 115 |Turns on (checks) or turns off (unchecks) a checkbox or radio button. | 116 |
ControlSetEnabled | 119 |Enables or disables the specified control. | 120 |
ControlSetStyle ControlSetExStyle |
123 | Changes the style or extended style of the specified control, respectively. | 124 |
ControlSetText | 127 |Changes the text of a control. | 128 |
ControlShow | 131 |Shows the specified control if it was previously hidden. | 132 |
ControlShowDropDown | 135 |Shows the drop-down list of a ComboBox control. | 136 |
EditGetCurrentCol | 139 |Returns the column number in an Edit control where the caret (text insertion point) resides. | 140 |
EditGetCurrentLine | 143 |Returns the line number in an Edit control where the caret (text insert point) resides. | 144 |
EditGetLine | 147 |Returns the text of the specified line in an Edit control. | 148 |
EditGetLineCount | 151 |Returns the number of lines in an Edit control. | 152 |
EditGetSelectedText | 155 |Returns the selected text in an Edit control. | 156 |
EditPaste | 159 |Pastes the specified string at the caret (text insertion point) in an Edit control. | 160 |
ListViewGetContent | 163 |Returns a list of items/rows from a ListView. | 164 |
Functions which operate on individual controls have a parameter named Control which supports a few different ways to identify the control. The Control parameter can be one of the following:
169 |ClassNN (String): The ClassNN (classname and instance number) of the control, which can be determined via Window Spy. For example "Edit1" is the first control with classname "Edit".
170 |Text (String): The control's text. The matching behavior is determined by SetTitleMatchMode.
171 |HWND (Integer): The control's HWND, which is typically retrieved via ControlGetHwnd, MouseGetPos, or DllCall. This also works on hidden controls even when DetectHiddenWindows is Off. Any subsequent window parameters are ignored.
172 |Object: An object of any type with a Hwnd
property, such as a GuiControl. A PropertyError is thrown if the object has no Hwnd
property, or TypeError if it does not return a pure integer. Any subsequent window parameters are ignored.
Omitted: A few functions are able to operate on either a control or a top-level window. Omitting the Control parameter causes the function to use the target window (specified by WinTitle) instead of one of its controls. For example, ControlSend can send keyboard messages directly to the window.
174 | 175 |Typically one of the following errors may be thrown:
177 |To improve reliability, a delay is done automatically after each use of a Control function that changes a control (except for ControlSetStyle and ControlSetExStyle). That delay can be changed via SetControlDelay or by assigning a value to A_ControlDelay. For details, see SetControlDelay remarks.
185 |To discover the ClassNN or HWND of the control that the mouse is currently hovering over, use MouseGetPos.
186 |To retrieve an array of all controls in a window, use WinGetControls or WinGetControlsHwnd.
187 | 188 |SetControlDelay, Win functions, GuiControl object (for controls created by the script)
190 | 191 | 192 | 193 | -------------------------------------------------------------------------------- /docs/lib/ControlAddItem.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Adds the specified string as a new entry at the bottom of a ListBox or ComboBox.
17 | 18 |ControlAddItem String, Control , WinTitle, WinText, ExcludeTitle, ExcludeText19 | 20 |
Type: String
25 |The string to add.
26 |Type: String, Integer or Object
30 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
35 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
36 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
37 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
38 |Type: Integer
43 |This function returns the index of the new item, where 1 is the first item, 2 is the second, etc.
44 | 45 |A TargetError is thrown if the window or control could not be found, or if the control's class name does not contain "Combo" or "List".
47 |An Error or OSError is thrown if the item could not be added.
48 | 49 |To improve reliability, a delay is done automatically after each use of this function. That delay can be changed via SetControlDelay or by assigning a value to A_ControlDelay. For details, see SetControlDelay remarks.
51 | 52 |ControlDeleteItem, ControlFindItem, Add method (GuiControl object), Control functions
54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /docs/lib/ControlChooseIndex.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Sets the selection in a ListBox, ComboBox or Tab control to be the Nth item.
17 | 18 |ControlChooseIndex N, Control , WinTitle, WinText, ExcludeTitle, ExcludeText19 | 20 |
Type: Integer
25 |The index of the item, where 1 is the first item, 2 is the second, etc. To deselect all entries in a ListBox or ComboBox, specify 0.
26 |Type: String, Integer or Object
30 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
35 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
36 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
37 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
38 |A TargetError is thrown if the window or control could not be found, or if the control's class name does not contain "Combo", "List" or "Tab".
43 |An Error or OSError is thrown if the change could not be applied.
44 | 45 |To select all items in a multi-select listbox, follow this example:
47 |PostMessage(0x0185, 1, -1, "ListBox1", WinTitle) ; Select all listbox items. 0x0185 is LB_SETSEL.48 |
Unlike GuiControl.Choose(), this function raises a Change or DoubleClick event.
49 |To improve reliability, a delay is done automatically after each use of this function. That delay can be changed via SetControlDelay or by assigning a value to A_ControlDelay. For details, see SetControlDelay remarks.
50 | 51 |ControlGetIndex, ControlChooseString, Choose method (GuiControl object), Control functions
53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /docs/lib/ControlChooseString.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Sets the selection in a ListBox or ComboBox to be the first entry whose leading part matches the specified string.
17 | 18 |ControlChooseString String, Control , WinTitle, WinText, ExcludeTitle, ExcludeText19 | 20 |
Type: String
25 |The string to choose. The search is not case-sensitive. For example, if a ListBox/ComboBox contains the item "UNIX Text", specifying the word unix (lowercase) would be enough to select it.
26 |Type: String, Integer or Object
30 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
35 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
36 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
37 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
38 |Type: Integer
43 |This function returns the index of the chosen item, where 1 is the first item, 2 is the second, etc.
44 | 45 |A TargetError is thrown if the window or control could not be found, or if the control's class name does not contain "Combo" or "List".
47 |An Error or OSError is thrown if the change could not be applied.
48 | 49 |Unlike GuiControl.Choose(), this function raises a Change or DoubleClick event.
51 |To improve reliability, a delay is done automatically after each use of this function. That delay can be changed via SetControlDelay or by assigning a value to A_ControlDelay. For details, see SetControlDelay remarks.
52 | 53 |ControlChooseIndex, ControlGetChoice, Choose method (GuiControl object), Control functions
55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /docs/lib/ControlClick.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Sends a mouse button or mouse wheel event to a control.
16 | 17 |ControlClick Control-or-Pos, WinTitle, WinText, WhichButton, ClickCount, Options, ExcludeTitle, ExcludeText18 |
Type: String, Integer or Object
24 |If omitted, the target window itself will be clicked. Otherwise, use one of the following modes.
25 |Mode 1 (Position): Specify the X and Y coordinates relative to the upper left corner of the target window's client area. The X coordinate must precede the Y coordinate and there must be at least one space or tab between them. For example: "X55 Y33"
. If there is a control at the specified coordinates, it will be sent the click-event at those exact coordinates. If there is no control, the target window itself will be sent the event (which might have no effect depending on the nature of the window).
Note: In mode 1, the X and Y option letters of the Options parameter are ignored.
27 |Mode 2 (Control): Specify the control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
By default, mode 2 takes precedence over mode 1. For example, in the unlikely event that there is a control whose text or ClassNN has the format "Xnnn Ynnn", it would be acted upon by mode 2. To override this and use mode 1 unconditionally, specify the word Pos in Options as in the following example: ControlClick "x255 y152", WinTitle,,,, "Pos"
.
Type: String, Integer or Object
34 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
35 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
36 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
37 |Type: String
42 |If blank or omitted, it defaults to Left (the left mouse button). Otherwise, specify the button to click or the rotate/push direction of the mouse wheel.
43 |Button: Left, Right, Middle (or just the first letter of each of these); or X1 (fourth button) or X2 (fifth button).
44 |Mouse wheel: Specify WheelUp or WU to turn the wheel upward (away from you); specify WheelDown or WD to turn the wheel downward (toward you). Specify WheelLeft (or WL) or WheelRight (or WR) to push the wheel left or right, respectively. ClickCount is the number of notches to turn the wheel.
45 |Type: Integer
50 |If omitted, it defaults to 1. Otherwise, specify the number of times to click the mouse button or turn the mouse wheel.
51 |Type: String
56 |If blank or omitted, each click consists of a down-event followed by an up-event, and occurs at the center of the control when mode 2 is in effect. Otherwise, specify a series of one or more of the following options. For example: "d x50 y25"
.
NA: May improve reliability. See reliability below.
58 |D: Press the mouse button down but do not release it (i.e. generate a down-event). If both the D and U options are absent, a complete click (down and up) will be sent.
59 |U: Release the mouse button (i.e. generate an up-event). This option should not be present if the D option is already present (and vice versa).
60 |Pos: Specify the word Pos anywhere in Options to unconditionally use the X/Y positioning mode as described in the Control-or-Pos parameter above.
61 |Xn: Specify for n the X position to click at, relative to the control's upper left corner. If unspecified, the click will occur at the horizontal-center of the control.
62 |Yn: Specify for n the Y position to click at, relative to the control's upper left corner. If unspecified, the click will occur at the vertical-center of the control.
63 |Use decimal (not hexadecimal) numbers for the X and Y options.
64 |An exception is thrown in the following cases:
70 |To improve reliability -- especially during times when the user is physically moving the mouse during the ControlClick -- one or both of the following may help:
79 |1) Use SetControlDelay -1
prior to ControlClick. This avoids holding the mouse button down during the click, which in turn reduces interference from the user's physical movement of the mouse.
2) Specify the string NA anywhere in the sixth parameter (Options) as shown below:
81 |SetControlDelay -1 82 | ControlClick "Toolbar321", WinTitle,,,, "NA"83 |
The NA option avoids marking the target window as active and avoids merging its input processing with that of the script, which may prevent physical movement of the mouse from interfering (but usually only when the target window is not active). However, this method might not work for all types of windows and controls.
84 |Not all applications obey a ClickCount higher than 1 for turning the mouse wheel. For those applications, use a loop to turn the wheel more than one notch as in this example, which turns it 5 notches:
86 |Loop 5 87 | ControlClick Control, WinTitle, WinText, "WheelUp"88 | 89 |
SetControlDelay, Control functions, Click
91 |Clicks at a set of coordinates. Note the lack of a comma between X and Y.
99 |ControlClick "x55 y77", "Some Window Title"100 |
Clicks in NA mode at coordinates that are relative to a named control.
104 |SetControlDelay -1 ; May improve reliability and reduce side effects. 105 | ControlClick "Toolbar321", "Some Window Title",,,, "NA x192 y10"106 |
Deletes the specified entry number from a ListBox or ComboBox.
17 | 18 |ControlDeleteItem N, Control , WinTitle, WinText, ExcludeTitle, ExcludeText19 | 20 |
Type: Integer
25 |The index of the item, where 1 is the first entry, 2 is the second, etc.
26 |Type: String, Integer or Object
30 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
35 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
36 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
37 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
38 |A TargetError is thrown if the window or control could not be found, or if the control's class name does not contain "Combo" or "List".
43 |An Error or OSError is thrown if the item could not be deleted.
44 | 45 |To improve reliability, a delay is done automatically after each use of this function. That delay can be changed via SetControlDelay or by assigning a value to A_ControlDelay. For details, see SetControlDelay remarks.
47 | 48 |ControlAddItem, ControlFindItem, Delete method (GuiControl object), Control functions
50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /docs/lib/ControlFindItem.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the entry number of a ListBox or ComboBox that is a complete match for the specified string.
17 | 18 |FoundItem := ControlFindItem(String, Control , WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String
25 |The string to find. The search is case-insensitive. Unlike ControlChooseString, the entry's entire text must match, not just the leading part.
26 |Type: String, Integer or Object
30 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
35 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
36 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
37 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
38 |Type: Integer
43 |This function returns the entry number of a ListBox or ComboBox that is a complete match for String. The first entry in the control is 1, the second 2, and so on. If no match is found, an exception is thrown.
44 | 45 |A TargetError is thrown if the window or control could not be found, or if the control's class name does not contain "Combo" or "List".
47 |An Error is thrown if the item could not be found.
48 | 49 |To improve reliability, a delay is done automatically after each use of this function. That delay can be changed via SetControlDelay or by assigning a value to A_ControlDelay. For details, see SetControlDelay remarks.
51 | 52 |ControlAddItem, ControlDeleteItem, Control functions
54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /docs/lib/ControlFocus.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Sets input focus to a given control on a window.
16 | 17 |ControlFocus Control , WinTitle, WinText, ExcludeTitle, ExcludeText18 | 19 |
Type: String, Integer or Object
24 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
29 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
30 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
31 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
32 |A TargetError is thrown if the window or control could not be found.
38 | 39 |To be effective, the control's window generally must not be minimized or hidden.
41 |To improve reliability, a delay is done automatically after each use of this function. That delay can be changed via SetControlDelay or by assigning a value to A_ControlDelay. For details, see SetControlDelay remarks.
42 |When a control is focused in response to user input (such as pressing the Tab key), the dialog manager applies additional effects which are independent of the control having focus. These effects are not applied by ControlFocus, and therefore the following limitations apply:
43 |The WM_NEXTDLGCTL message can be used to focus the control and apply these additional effects. For example:
49 |WinExist("A") ; Set the Last Found Window to the active window 50 | hWndControl := ControlGetHwnd("Button1") ; Get HWND of first Button 51 | SendMessage 0x0028, hWndControl, True ; 0x0028 is WM_NEXTDLGCTL52 | 53 |
SetControlDelay, ControlGetFocus, Control functions
55 |Returns a non-zero value if the checkbox or radio button is checked.
17 | 18 |IsChecked := ControlGetChecked(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
30 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
33 |Type: Integer (boolean)
38 |This function returns 1 (true) if the checkbox or radio button is checked, or 0 (false) if not.
39 | 40 |A TargetError is thrown if the window or control could not be found.
42 |An OSError is thrown if a message could not be sent to the control.
43 | 44 |ControlSetChecked, Value property (GuiControl object), Control functions
46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /docs/lib/ControlGetChoice.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the name of the currently selected entry in a ListBox or ComboBox.
17 | 18 |Choice := ControlGetChoice(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
30 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
33 |Type: String
38 |This function returns the name of the currently selected entry in a ListBox or ComboBox.
39 | 40 |A TargetError is thrown if the window or control could not be found, or if the control's class name does not contain "Combo" or "List".
42 |An Error is thrown on failure.
43 | 44 |To instead retrieve the position of the selected item, follow this example (use only one of the first two lines):
46 |ChoicePos := SendMessage(0x0188, 0, 0, "ListBox1", WinTitle) ; 0x0188 is LB_GETCURSEL (for a ListBox). 47 | ChoicePos := SendMessage(0x0147, 0, 0, "ComboBox1", WinTitle) ; 0x0147 is CB_GETCURSEL (for a DropDownList or ComboBox). 48 | ChoicePos += 1 ; Convert from 0-based to 1-based, i.e. so that the first item is known as 1, not 0. 49 | ; ChoicePos is now 0 if there is no item selected.50 | 51 |
ControlChooseIndex, ControlChooseString, Value property (GuiControl object), Choose method (GuiControl object), Control functions
53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /docs/lib/ControlGetClassNN.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the ClassNN (class name and sequence number) of the specified control.
17 | 18 |ClassNN := ControlGetClassNN(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
30 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
33 |Type: String
38 |This function returns the ClassNN (class name and sequence number) of the specified control.
39 | 40 |A TargetError is thrown if there is a problem determining the target window or control.
42 |An Error or OSError is thrown if the ClassNN could not be determined.
43 | 44 |A control's ClassNN is the name of its window class followed by its sequence number within the top-level window which contains it. For example, "Edit1" is the first Edit control on a window and "Button12" is the twelth button.
46 |A control's ClassNN can also be determined via Window Spy, MouseGetPos or WinGetControls.
47 |Some class names include digits which are not part of the control's sequence number. For example, "SysListView321" is the window's first ListView control, not its 321st. To retrieve the class name without the sequence number, pass the control's HWND to WinGetClass.
48 | 49 |WinGetClass, WinGetControls, ClassNN property (GuiControl object), MouseGetPos, Control functions
51 | 52 |Retrieves the ClassNN of the currently focused control.
55 |classNN := ControlGetClassNN(ControlGetFocus("A"))56 |
Returns a non-zero value if the specified control is enabled.
17 | 18 |IsEnabled := ControlGetEnabled(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
30 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
33 |Type: Integer (boolean)
38 |This function returns 1 (true) if the specified control is enabled, or 0 (false) if disabled.
39 | 40 |A TargetError is thrown if the window or control could not be found.
42 | 43 |ControlSetEnabled, WinSetEnabled, Enabled property (GuiControl object), Control functions
45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/lib/ControlGetFocus.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Retrieves which control of the target window has keyboard focus, if any.
16 | 17 |HWND := ControlGetFocus(WinTitle, WinText, ExcludeTitle, ExcludeText)18 |
Type: String, Integer or Object
24 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
25 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
26 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
27 |Type: Integer
33 |This function returns the window handle (HWND) of the focused control.
34 |If none of the target window's controls has focus, the return value is 0.
35 | 36 |A TargetError is thrown if there is a problem determining the target window or control.
38 |An OSError is thrown if there is a problem determining the focus.
39 | 40 |The control retrieved by this function is the one that has keyboard focus, that is, the one that would receive keystrokes if the user were to type any.
42 |The target window must be active to have a focused control, but even the active window may lack a focused control.
43 | 44 |ControlFocus, Control functions
46 |Reports the HWND and ClassNN of the active window's focused control.
49 |50 | FocusedHwnd := ControlGetFocus("A") 51 | FocusedClassNN := ControlGetClassNN(FocusedHwnd) 52 | MsgBox 'Control with focus = {Hwnd: ' FocusedHwnd ', ClassNN: "' FocusedClassNN '"}'53 |
Returns the unique ID number of the specified control.
17 | 18 |Hwnd := ControlGetHwnd(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
30 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
33 |Type: Integer
38 |This function returns the window handle (HWND) of the specified control.
39 | 40 |A TargetError is thrown if the window or control could not be found.
42 | 43 |A control's HWND is often used with PostMessage, SendMessage, and DllCall. On a related note, a control's HWND can also be retrieved via MouseGetPos. Finally, a control's HWND can be used directly in a WinTitle parameter. This also works on hidden controls even when DetectHiddenWindows is Off.
45 | 46 |WinGetID, Hwnd property (GuiControl object), Control functions
48 | 49 |Retrieves the unique ID number of the Notepad's Edit control.
52 |editHwnd := ControlGetHwnd("Edit1", "ahk_class Notepad")53 |
Returns the index of the currently selected entry or tab in a ListBox, ComboBox or Tab control.
17 | 18 |Index := ControlGetIndex(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
30 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
33 |Type: Integer
38 |This function returns the index of the currently selected entry or tab. The first entry or tab is 1, the second is 2, etc. If no entry or tab is selected, the return value is 0.
39 | 40 |A TargetError is thrown if the window or control could not be found, or if the control's class name does not contain "Combo", "List" or "Tab".
42 |An OSError is thrown if a message could not be sent to the control.
43 | 44 |To instead discover how many tabs (pages) exist in a tab control, follow this example:
46 |TabCount := SendMessage(0x1304,,, "SysTabControl321", WinTitle) ; 0x1304 is TCM_GETITEMCOUNT.47 | 48 |
ControlChooseIndex, ControlGetChoice, ControlChooseString, Value property (GuiControl object), Choose method (GuiControl object), Control functions
50 | 51 |Retrieves the active tab number of the first Tab control.
55 |56 | WhichTab := ControlGetIndex("SysTabControl321", "Some Window Title") 57 | MsgBox "Tab #" WhichTab " is active." 58 |59 |
Returns an array of items/rows from a ListBox, ComboBox, or DropDownList.
17 | 18 |Items := ControlGetItems(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
30 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
33 |Type: Array
38 |This function returns an array containing the text of each item or row.
39 | 40 |A TargetError is thrown if the window or control could not be found, or if the control's class name does not contain "Combo" or "List".
42 |An Error is thrown on failure, such as if a message returned a failure code or could not be sent.
43 | 44 |Some applications store their item data privately, which prevents their text from being retrieved. In these cases, an exception will usually not be thrown, but all the retrieved fields will be empty.
46 | 47 |ListViewGetContent, WinGetList, Control functions
49 | 50 |Accesses the items one by one.
53 |for item in ControlGetItems("ComboBox1", WinTitle) 54 | MsgBox "Item number " A_Index " is " item55 |
Accesses a specific item by index.
59 |items := ControlGetItems("ListBox1", WinTitle) 60 | MsgBox "The first item is " items[1] 61 | MsgBox "The last item is " items[-1]62 |
Retrieves the position and size of a control.
16 | 17 |ControlGetPos &OutX, &OutY, &OutWidth, &OutHeight, Control, WinTitle, WinText, ExcludeTitle, ExcludeText18 |
Type: VarRef
24 |If omitted, the corresponding value will not be stored. Otherwise, specify references to the output variables in which to store the X and Y coordinates (in pixels) of the control's upper left corner. These coordinates are relative to the upper-left corner of the target window's client area and thus are the same as those used by ControlMove.
25 |Type: VarRef
30 |If omitted, the corresponding value will not be stored. Otherwise, specify references to the output variables in which to store the control's width and height (in pixels).
31 |Type: String, Integer or Object
36 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
42 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
43 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
44 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
45 |A TargetError is thrown if the window or control could not be found.
51 | 52 |Unlike functions that change a control, ControlGetPos does not have an automatic delay (SetControlDelay does not affect it).
54 | 55 |ControlMove, WinGetPos, Control functions
57 |Continuously updates and displays the name and position of the control currently under the mouse cursor.
60 |Loop 61 | { 62 | Sleep 100 63 | MouseGetPos ,, &WhichWindow, &WhichControl 64 | try ControlGetPos &x, &y, &w, &h, WhichControl, WhichWindow 65 | ToolTip WhichControl "`nX" X "`tY" Y "`nW" W "`t" H 66 | }67 |
Returns an integer representing the style or extended style of the specified control.
17 | 18 |Style := ControlGetStyle(Control , WinTitle, WinText, ExcludeTitle, ExcludeText) 19 | ExStyle := ControlGetExStyle(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)20 | 21 |
Type: String, Integer or Object
26 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
31 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
32 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
33 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
34 |Type: Integer
39 |These functions return the style or extended style of the specified control.
40 | 41 |A TargetError is thrown if the window or control could not be found.
43 | 44 |See the styles table for a partial listing of styles.
46 | 47 |ControlSetStyle / ControlSetExStyle, WinGetStyle / WinGetExStyle, styles table, Control functions
49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /docs/lib/ControlGetText.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Retrieves text from a control.
16 | 17 |Text := ControlGetText(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)18 |
Type: String, Integer or Object
24 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
30 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
33 |Type: String
39 |This function returns the text of the specified control.
40 | 41 |A TargetError is thrown if the window or control could not be found.
43 | 44 |Note: To retrieve text from a ListView, ListBox, or ComboBox, use ListViewGetContent or ControlGetItems instead.
46 |If the retrieved text appears to be truncated (incomplete), it may be necessary to retrieve the text by sending the WM_GETTEXT message via SendMessage instead. This is because some applications do not respond properly to the WM_GETTEXTLENGTH message, which causes AutoHotkey to make the return value too small to fit all the text.
47 |This function might use a large amount of RAM if the target control (e.g. an editor with a large document open) contains a large quantity of text. However, a variable's memory can be freed after use by assigning it to nothing, i.e. Text := ""
.
Text retrieved from most control types uses carriage return and linefeed (`r`n) rather than a solitary linefeed (`n) to mark the end of each line.
49 |It is not necessary to do SetTitleMatchMode "Slow"
because ControlGetText always retrieves the text using the slow mode (since it works on a broader range of control types).
To retrieve an array of all controls in a window, use WinGetControls or WinGetControlsHwnd.
51 | 52 |ControlSetText, WinGetText, Control functions
54 |Retrieves the current text from Notepad's edit control and stores it in Text. This example may fail on Windows 11 or later, as it requires the classic version of Notepad.
57 |Text := ControlGetText("Edit1", "Untitled -")58 |
Retrieves and reports the current text from the main window's edit control.
61 |ListVars 62 | WinWaitActive "ahk_class AutoHotkey" 63 | MsgBox ControlGetText("Edit1") ; Use the window found above.64 |
Returns a non-zero value if the specified control is visible.
17 | 18 |IsVisible := ControlGetVisible(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
30 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
33 |Type: Integer (boolean)
38 |This function returns 1 (true) if the specified control is visible, or 0 (false) if hidden.
39 | 40 |A TargetError is thrown if the window or control could not be found.
42 | 43 |ControlHide, ControlShow, Visible property (GuiControl object), Control functions
45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/lib/ControlHide.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Hides the specified control.
17 | 18 |ControlHide Control , WinTitle, WinText, ExcludeTitle, ExcludeText19 | 20 |
Type: String, Integer or Object
25 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
30 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
33 |A TargetError is thrown if the window or control could not be found.
38 | 39 |If you additionally want to prevent a control's shortcut key (underlined letter) from working, disable the control via ControlSetEnabled.
41 |To improve reliability, a delay is done automatically after each use of this function. That delay can be changed via SetControlDelay or by assigning a value to A_ControlDelay. For details, see SetControlDelay remarks.
42 | 43 |ControlShow, ControlGetVisible, WinHide, Visible property (GuiControl object), Control functions
45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/lib/ControlHideDropDown.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Hides the drop-down list of a ComboBox control.
17 | 18 |ControlHideDropDown Control , WinTitle, WinText, ExcludeTitle, ExcludeText19 | 20 |
Type: String, Integer or Object
25 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
30 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
33 |A TargetError is thrown if the window or control could not be found.
38 |An OSError is thrown if a message could not be sent to the control.
39 | 40 |To improve reliability, a delay is done automatically after each use of this function. That delay can be changed via SetControlDelay or by assigning a value to A_ControlDelay. For details, see SetControlDelay remarks.
42 | 43 |ControlShowDropDown, Control functions
45 | 46 |See example #1 on the ControlShowDropDown page.
48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /docs/lib/ControlMove.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Moves or resizes a control.
16 | 17 |ControlMove X, Y, Width, Height, Control, WinTitle, WinText, ExcludeTitle, ExcludeText18 | 19 |
Type: Integer
24 |If either is omitted, the control's position in that dimension will not be changed. Otherwise, specify the X and Y coordinates (in pixels) of the upper left corner of the control's new location. The coordinates are relative to the upper-left corner of the target window's client area; ControlGetPos can be used to determine them.
25 |Type: Integer
30 |If either is omitted, the control's size in that dimension will not be changed. Otherwise, specify the new width and height of the control (in pixels).
31 |Type: String, Integer or Object
36 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
42 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
43 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
44 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
45 |A TargetError is thrown if the window or control could not be found.
50 |An OSError is thrown if the control's current position could not be determined.
51 | 52 | 53 |To improve reliability, a delay is done automatically after each use of this function. That delay can be changed via SetControlDelay or by assigning a value to A_ControlDelay. For details, see SetControlDelay remarks.
55 | 56 |ControlGetPos, WinMove, SetControlDelay, Control functions
58 | 59 |Demonstrates how to manipulate the OK button of an input box while the script is waiting for user input.
62 |SetTimer ControlMoveTimer 63 | IB := InputBox(, "My Input Box") 64 | 65 | ControlMoveTimer() 66 | { 67 | if !WinExist("My Input Box") 68 | return 69 | ; Otherwise the above set the "last found" window for us: 70 | SetTimer , 0 71 | WinActivate 72 | ControlMove 10,, 200,, "OK" ; Move the OK button to the left and increase its width. 73 | }74 |
Sends simulated keystrokes or text to a window or control.
16 | 17 |ControlSend Keys , Control, WinTitle, WinText, ExcludeTitle, ExcludeText 18 | ControlSendText Keys , Control, WinTitle, WinText, ExcludeTitle, ExcludeText19 |
Type: String
25 |The sequence of keys to send (see the Send function for details). The rate at which characters are sent is determined by SetKeyDelay.
26 |Unlike the Send function, mouse clicks cannot be sent by ControlSend. Use ControlClick for that.
27 |Type: String, Integer or Object
32 |If omitted, the keystrokes will be sent directly to the target window instead of one of its controls (see Automating Winamp for an example). Otherwise, specify the control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
38 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
39 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
40 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
41 |A TargetError is thrown if the window or control could not be found.
47 | 48 |ControlSendText sends the individual characters of the Keys parameter without translating {Enter}
to Enter, ^c
to Ctrl+C, etc. For details, see Text mode. It is also valid to use {Raw} or {Text} with ControlSend.
If the Control parameter is omitted, this function will attempt to send directly to the target window by sending to its topmost control (which is often the correct one) or the window itself if there are no controls. This is useful if a window does not appear to have any controls at all, or just for the convenience of not having to worry about which control to send to.
51 |By default, modifier keystrokes (Ctrl, Alt, Shift, and Win) are sent as they normally would be by the Send function. This allows command prompt and other console windows to properly detect uppercase letters, control characters, etc. It may also improve reliability in other ways.
52 |However, in some cases these modifier events may interfere with the active window, especially if the user is actively typing during a ControlSend or if Alt is being sent (since Alt activates the active window's menu bar). This can be avoided by explicitly sending modifier up and down events as in this example:
53 |ControlSend "{Alt down}f{Alt up}", "Edit1", "Untitled - Notepad"54 |
The method above also allows the sending of modifier keystrokes (Ctrl, Alt, Shift, and Win) while the workstation is locked (protected by logon prompt).
55 |BlockInput should be avoided when using ControlSend against a console window such as command prompt. This is because it might prevent capitalization and modifier keys such as Ctrl from working properly.
56 |The value of SetKeyDelay determines the speed at which keys are sent. If the target window does not receive the keystrokes reliably, try increasing the press duration via the second parameter of SetKeyDelay as in these examples:
57 |SetKeyDelay 10, 10 58 | SetKeyDelay 0, 10 59 | SetKeyDelay -1, 060 |
If the target control is an Edit control (or something similar), the following are usually more reliable and faster than ControlSend:
61 |EditPaste("This text will be inserted at the caret position.", ControlName, WinTitle)62 |
ControlSetText("This text will entirely replace any current text.", ControlName, WinTitle)63 |
ControlSend is generally not capable of manipulating a window's menu bar. To work around this, use MenuSelect. If that is not possible due to the nature of the menu bar, you could try to discover the message that corresponds to the desired menu item by following the SendMessage Tutorial.
64 | 65 |SetKeyDelay, Escape sequences (e.g. `n) , Control functions, Send, Automating Winamp
67 |Opens Notepad minimized and send it some text. This example may fail on Windows 11 or later, as it requires the classic version of Notepad.
70 |Run "Notepad",, "Min", &PID ; Run Notepad minimized. 71 | WinWait "ahk_pid " PID ; Wait for it to appear. 72 | ; Send the text to the inactive Notepad edit control. 73 | ; The third parameter is omitted so the last found window is used. 74 | ControlSend "This is a line of text in the notepad window.{Enter}", "Edit1" 75 | ControlSendText "Notice that {Enter} is not sent as an Enter keystroke with ControlSendText.", "Edit1" 76 | 77 | Msgbox "Press OK to activate the window to see the result." 78 | WinActivate "ahk_pid " PID ; Show the result.79 |
Opens the command prompt and sent it some text. This example may fail on Windows 11 or later, as it requires the classic version of the command prompt.
83 |SetTitleMatchMode 2 84 | Run A_ComSpec,,, &PID ; Run command prompt. 85 | WinWait "ahk_pid " PID ; Wait for it to appear. 86 | ControlSend "ipconfig{Enter}",, "cmd.exe" ; Send directly to the command prompt window.87 |
Creates a GUI with an edit control and sent it some text.
90 |MyGui := Gui() 91 | MyGui.Add("Edit", "r10 w500") 92 | MyGui.Show() 93 | ControlSend "This is a line of text in the edit control.{Enter}", "Edit1", MyGui 94 | ControlSendText "Notice that {Enter} is not sent as an Enter keystroke with ControlSendText.", "Edit1", MyGui 95 |96 |
Turns on (checks) or turns off (unchecks) a checkbox or radio button.
17 | 18 |ControlSetChecked NewSetting, Control , WinTitle, WinText, ExcludeTitle, ExcludeText19 | 20 |
Type: Integer
26 |One of the following values:
27 |1
or True
turns on the setting0
or False
turns off the setting-1
toggles the setting (sets it to the opposite of its current state)Type: String, Integer or Object
36 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
41 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
42 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
43 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
44 |A TargetError is thrown if the window or control could not be found.
49 |An OSError is thrown if a message could not be sent to the control.
50 | 51 |To ensure correct functionality, this function also sets the input focus to the control.
53 |To improve reliability, a delay is done automatically after each use of this function. That delay can be changed via SetControlDelay or by assigning a value to A_ControlDelay. For details, see SetControlDelay remarks.
54 | 55 |ControlGetChecked, Value property (GuiControl object), Control functions
57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /docs/lib/ControlSetEnabled.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Enables or disables the specified control.
17 | 18 |ControlSetEnabled NewSetting, Control , WinTitle, WinText, ExcludeTitle, ExcludeText19 | 20 |
Type: Integer
26 |One of the following values:
27 |1
or True
turns on the setting0
or False
turns off the setting-1
toggles the setting (sets it to the opposite of its current state)Type: String, Integer or Object
36 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
41 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
42 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
43 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
44 |A TargetError is thrown if the window or control could not be found.
49 | 50 |To improve reliability, a delay is done automatically after each use of this function. That delay can be changed via SetControlDelay or by assigning a value to A_ControlDelay. For details, see SetControlDelay remarks.
52 | 53 |ControlGetEnabled, WinSetEnabled, Enabled property (GuiControl object), Control functions
55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /docs/lib/ControlSetStyle.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Changes the style or extended style of the specified control, respectively.
17 | 18 |ControlSetStyle Value, Control , WinTitle, WinText, ExcludeTitle, ExcludeText 19 | ControlSetExStyle Value, Control , WinTitle, WinText, ExcludeTitle, ExcludeText20 | 21 |
Pass a positive integer to completely overwrite the window's style; that is, to set it to Value.
27 |To easily add, remove or toggle styles, pass a numeric string prefixed with a plus sign (+), minus sign (-) or caret (^), respectively. The new style value is calculated as shown below (where CurrentStyle could be retrieved with ControlGetStyle, ControlGetExStyle, WinGetStyle or WinGetExStyle):
28 |Operation | 31 |Prefix | 32 |Example | 33 |Formula | 34 |
---|---|---|---|
Add | 37 |+ | 38 |"+0x80" |
39 | NewStyle := CurrentStyle | Value |
40 |
Remove | 43 |- | 44 |"-0x80" |
45 | NewStyle := CurrentStyle & ~Value |
46 |
Toggle | 49 |^ | 50 |"^0x80" |
51 | NewStyle := CurrentStyle ^ Value |
52 |
If Value is a negative integer, it is treated the same as the corresponding numeric string.
55 |To use the + or ^ prefix literally in an expression, the prefix or value must be enclosed in quote marks. For example: ControlSetStyle("+0x80")
or ControlSetStyle("^" StylesToToggle)
. This is because the expression +123
produces 123 (without a prefix) and ^123
is a syntax error.
Type: String, Integer or Object
60 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
65 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
66 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
67 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
68 |A TargetError is thrown if the window or control could not be found.
73 |An OSError is thrown if the style could not be changed. Partial change is considered a success.
74 | 75 |See the styles table for a partial listing of styles.
77 |Certain style changes require that the entire window be redrawn using WinRedraw.
78 | 79 |ControlGetStyle / ControlGetExStyle, WinSetStyle / WinSetExStyle, styles table, Control functions
81 | 82 |Sets the WS_BORDER style of the Notepad's Edit control to its opposite state.
85 |ControlSetStyle("^0x800000", "Edit1", "ahk_class Notepad")86 |
Changes the text of a control.
16 | 17 |ControlSetText NewText, Control , WinTitle, WinText, ExcludeTitle, ExcludeText18 |
Type: String
24 |The new text to set into the control.
25 |Type: String, Integer or Object
30 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
36 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
37 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
38 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
39 |A TargetError is thrown if the window or control could not be found.
45 | 46 |Most control types use carriage return and linefeed (`r`n) rather than a solitary linefeed (`n) to mark the end of each line. To translate a block of text containing `n characters, follow this example:
48 |MyVar := StrReplace(MyVar, "`n", "`r`n")49 |
To improve reliability, a delay is done automatically after each use of this function. That delay can be changed via SetControlDelay or by assigning a value to A_ControlDelay. For details, see SetControlDelay remarks.
50 | 51 |SetControlDelay, ControlGetText, Control functions
53 |Changes the text of Notepad's edit control. This example may fail on Windows 11 or later, as it requires the classic version of Notepad.
56 |ControlSetText("New Text Here", "Edit1", "Untitled -")57 |
Changes the text of the main window's edit control.
60 |ListVars 61 | WinWaitActive "ahk_class AutoHotkey" 62 | ControlSetText "New Text Here", "Edit1" ; Use the window found above.63 |
Shows the specified control if it was previously hidden.
17 | 18 |ControlShow Control , WinTitle, WinText, ExcludeTitle, ExcludeText19 | 20 |
Type: String, Integer or Object
25 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
30 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
33 |A TargetError is thrown if the window or control could not be found.
38 | 39 |To improve reliability, a delay is done automatically after each use of this function. That delay can be changed via SetControlDelay or by assigning a value to A_ControlDelay. For details, see SetControlDelay remarks.
41 | 42 |ControlHide, ControlGetVisible, WinShow, Visible property (GuiControl object), Control functions
44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /docs/lib/ControlShowDropDown.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Shows the drop-down list of a ComboBox control.
17 | 18 |ControlShowDropDown Control , WinTitle, WinText, ExcludeTitle, ExcludeText19 | 20 |
Type: String, Integer or Object
25 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
30 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
33 |A TargetError is thrown if the window or control could not be found.
38 |An OSError is thrown if a message could not be sent to the control.
39 | 40 |To improve reliability, a delay is done automatically after each use of this function. That delay can be changed via SetControlDelay or by assigning a value to A_ControlDelay. For details, see SetControlDelay remarks.
42 | 43 |ControlHideDropDown, Control functions
45 | 46 |Opens the Run dialog, shows its drop-down list for 2 seconds and closes the dialog.
49 |Send "#r" ; Open the Run dialog. 50 | WinWaitActive "ahk_class #32770" ; Wait for the dialog to appear. 51 | ControlShowDropDown "ComboBox1" ; Show the drop-down list. The second parameter is omitted so that the last found window is used. 52 | Sleep 2000 53 | ControlHideDropDown "ComboBox1" ; Hide the drop-down list. 54 | Sleep 1000 55 | Send "{Esc}" ; Close the Run dialog.56 |
Sets coordinate mode for various built-in functions to be relative to either the active window or the screen.
16 | 17 |CoordMode TargetType , RelativeTo18 |
Type: String
24 |Specify one of the following words to indicate the type of target to affect:
25 |ToolTip: Affects ToolTip.
26 |Pixel: Affects PixelGetColor, PixelSearch, and ImageSearch.
27 |Mouse: Affects MouseGetPos, Click, MouseMove, MouseClick, and MouseClickDrag.
28 |Caret: Affects CaretGetPos.
29 |Menu: Affects the Menu.Show method when coordinates are specified for it.
30 |Type: String
35 |If omitted, it defaults to Screen. Otherwise, specify one of the following words to indicate the area to which TargetType should be relative:
36 |Screen: Coordinates are relative to the desktop (entire screen).
37 |Window: Coordinates are relative to the active window.
38 |Client: Coordinates are relative to the active window's client area, which excludes the window's title bar, menu (if it has a standard one) and borders. Client coordinates are less dependent on OS version and theme.
39 |Type: String
45 |This function returns the previous setting; either Screen, Window or Client.
46 | 47 |If CoordMode is not used, the default mode is Client; that is, all built-in functions except those documented otherwise (e.g. WinMove and InputBox) use coordinates that are relative to the active window's client area.
49 |Every newly launched thread (such as a hotkey, custom menu item, or timed subroutine) starts off fresh with the default setting for this function. That default may be changed by using this function during script startup.
50 |The built-in A_CoordMode variables contain the current settings.
51 |Click, MouseMove, MouseClick, MouseClickDrag, MouseGetPos, PixelGetColor, PixelSearch, ToolTip, Menu.Show
53 |Prevents the current thread from being interrupted by other threads, or enables it to be interrupted.
16 | 17 |18 | Critical OnOffNumeric19 | 20 |
If blank or omitted, it defaults to On. Otherwise, specify one of the following:
26 |On: The current thread is made critical, meaning that it cannot be interrupted by another thread.
27 |Off: The current thread immediately becomes interruptible, regardless of the settings of Thread Interrupt. See Critical Off for details.
28 |(Numeric): Specify a positive number to turn on Critical but also change the number of milliseconds between checks of the internal message queue. See Message Check Interval for details. Specifying 0 turns off Critical. Specifying -1 turns on Critical but disables message checks.
29 |Type: Integer
34 |This function returns the previous setting (the value A_IsCritical would return prior to calling the function); 0 if Critical is off, otherwise an integer greater than zero.
35 | 36 |Critical threads are uninterruptible; for details, see Threads.
38 |A critical thread becomes interruptible when a message box or other dialog is displayed. However, unlike Thread Interrupt, the thread becomes critical again after the user dismisses the dialog.
39 | 40 |When buffered events are waiting to start new threads, using Critical "Off"
will not result in an immediate interruption of the current thread. Instead, an average of 5 milliseconds will pass before an interruption occurs. This makes it more than 99.999 % likely that at least one line after Critical "Off"
will execute before an interruption. You can force interruptions to occur immediately by means of a delay such as a Sleep -1
or a WinWait for a window that does not yet exist.
Critical "Off"
cancels the current thread's period of uninterruptibility even if the thread was not Critical, thereby letting events such as Size be processed sooner or more predictably.
See A_IsCritical for how to save and restore the current setting of Critical. However, since Critical is a thread-specific setting, when a critical thread ends, the underlying/resumed thread (if any) will be automatically noncritical. Consequently there is no need to do Critical "Off"
right before ending a thread.
If Critical is not used by the auto-execute thread, all threads start off as noncritical (though the settings of Thread Interrupt will still apply). By contrast, if the auto-execute thread turns on Critical but never turns it off, every newly launched thread (such as a hotkey, custom menu item, or timed subroutine) starts off critical.
47 |Thread NoTimers is similar to Critical except that it only prevents interruptions from timers.
48 | 49 |Specifying a positive number as the first parameter (e.g. Critical 30
) turns on Critical but also changes the minimum number of milliseconds between checks of the internal message queue. If unspecified, the default is 16 milliseconds while Critical is On, and 5 ms while Critical is Off. Increasing the interval postpones the arrival of messages/events, which gives the current thread more time to finish. This reduces the possibility that certain OnMessage callbacks and GUI events will be lost due to "thread already running". However, functions that wait such as Sleep and WinWait will check messages regardless of this setting (a workaround is DllCall("Sleep", "UInt", 500)
).
This setting affects the following:
52 |It does not affect the frequency of message checks while the script is paused or waiting.
57 |Because the system tick count generally has a granularity of 15.6 milliseconds, the minimum delta value is generally at least 15 or 16. The duration since the last check must exceed the interval setting in order for another check to occur. For example, a setting of 16 requires the tick count to change by 17 or greater. As a message check could occur at any time within the 15.6 millisecond window, any setting between 1 and 16 could permit two message checks within a single interval.
58 |Note: Increasing the message-check interval too much may reduce the responsiveness of various events such as GUI window repainting.
59 |Critical -1
turns on Critical but disables message checks. This does not prevent the program from checking for messages while performing a sleep, delay or wait. It is useful in cases where dispatching messages could interfere with the code currently executing, such as while handling certain types of messages during an OnMessage callback.
Thread (function), Threads, #MaxThreadsPerHotkey, #MaxThreadsBuffer, OnMessage, CallbackCreate, Hotkey, Menu object, SetTimer
63 | 64 |Press a hotkey to display a tooltip for 3 seconds. Due to Critical, any new thread that is launched during this time (e.g. by pressing the hotkey again) will be postponed until the tooltip disappears.
67 |#space:: ; Win+Space hotkey. 68 | { 69 | Critical 70 | ToolTip "No new threads will launch until after this ToolTip disappears." 71 | Sleep 3000 72 | ToolTip ; Turn off the tip. 73 | return ; Returning from a hotkey function ends the thread. Any underlying thread to be resumed is noncritical by definition. 74 | }75 |
Adds or subtracts time from a date-time value.
17 | 18 |Result := DateAdd(DateTime, Time, TimeUnits)
19 | Type: String
25 |A date-time stamp in the YYYYMMDDHH24MISS format.
26 |The amount of time to add, as an integer or floating-point number. Specify a negative number to perform subtraction.
32 |Type: String
37 |The meaning of the Time parameter. TimeUnits may be one of the following strings (or just the first letter): Seconds, Minutes, Hours or Days.
Type: String
43 |This function returns a string of digits in the YYYYMMDDHH24MISS format. This string should not be treated as a number, i.e. one should not perform math on it or compare it numerically.
44 | 45 |The built-in variable A_Now contains the current local time in YYYYMMDDHH24MISS format.
47 |To calculate the amount of time between two timestamps, use DateDiff.
48 |If DateTime contains an invalid timestamp or a year prior to 1601, a ValueError is thrown.
49 | 50 |DateDiff, FileGetTime, FormatTime
52 | 53 |Calculates the date 31 days from now and reports the result in human-readable form.
56 |57 | later := DateAdd(A_Now, 31, "days") 58 | MsgBox FormatTime(later) 59 |60 |
Compares two date-time values and returns the difference.
17 | 18 |Result := DateDiff(DateTime1, DateTime2, TimeUnits)
19 | Type: String
25 |Date-time stamps in the YYYYMMDDHH24MISS format.
26 |If either is an empty string, the current local date and time (A_Now) is used.
27 |Type: String
32 |Units to measure the difference in. TimeUnits may be one of the following strings (or just the first letter): Seconds, Minutes, Hours or Days.
33 |Type: Integer
39 |This function returns the difference between the two timestamps, in the units specified by TimeUnits. If DateTime1 is earlier than DateTime2, a negative number is returned.
40 |The result is always rounded down to the nearest integer. For example, if the actual difference between two timestamps is 1.999 days, it will be reported as 1 day. If higher precision is needed, specify Seconds for TimeUnits and divide the result by 60.0, 3600.0, or 86400.0.
41 | 42 |The built-in variable A_Now contains the current local time in YYYYMMDDHH24MISS format.
44 |To precisely determine the elapsed time between two events, use the A_TickCount method because it provides millisecond precision.
45 |To add or subtract a certain number of seconds, minutes, hours, or days from a timestamp, use DateAdd (subtraction is achieved by adding a negative number).
46 |If DateTime contains an invalid timestamp or a year prior to 1601, a ValueError is thrown.
47 | 48 |DateAdd, FileGetTime, FormatTime
50 |Calculates the number of days between two timestamps and reports the result.
53 |var1 := "20050126" 54 | var2 := "20040126" 55 | MsgBox DateDiff(var1, var2, "days") ; The answer will be 366 since 2004 is a leap year. 56 |57 |
Determines whether invisible text in a window is "seen" for the purpose of finding the window. This affects windowing functions such as WinExist and WinActivate.
16 | 17 |DetectHiddenText Mode
18 | Type: Boolean
24 |If true, hidden text is detected.
25 |If false, hidden text is not detected.
26 |Type: Integer (boolean)
32 |This function returns the previous setting; either 0 (false) or 1 (true).
33 | 34 |If DetectHiddenText is not used, the default setting is 1 (true).
36 |"Hidden text" is a term that refers to those controls of a window that are not visible. Their text is thus considered "hidden". Turning off DetectHiddenText can be useful in cases where you want to detect the difference between the different panes of a multi-pane window or multi-tabbed dialog. Use Window Spy to determine which text of the currently-active window is hidden. All built-in functions that accept a WinText parameter are affected by this setting, including WinActivate, WinActive, WinWait, and WinExist.
37 |The built-in variable A_DetectHiddenText contains the current setting (1 or 0).
38 |Every newly launched thread (such as a hotkey, custom menu item, or timed subroutine) starts off fresh with the default setting for this function. That default may be changed by using this function during script startup.
39 |Determines whether invisible windows are "seen" by the script.
16 | 17 |DetectHiddenWindows Mode
18 | Type: Boolean
24 |If true, hidden windows are detected.
25 |If false, hidden windows are not detected, except by the WinShow function.
26 |Type: Integer (boolean)
32 |This function returns the previous setting; either 0 (false) or 1 (true).
33 | 34 |If DetectHiddenWindows is not used, the default setting is 0 (false).
36 |Turning on DetectHiddenWindows can make scripting harder in some cases since some hidden system windows might accidentally match the title or text of another window you're trying to work with. So most scripts should leave this setting turned off. However, turning it on may be useful if you wish to work with hidden windows directly without first using WinShow to unhide them.
37 |All windowing functions except WinShow are affected by this setting, including WinActivate, WinActive, WinWait and WinExist. By contrast, WinShow will always unhide a hidden window even if hidden windows are not being detected.
38 |Turning on DetectHiddenWindows is not necessary in the following cases:
39 |WinShow(A_ScriptHwnd)
or WinMoveTop(myGui)
, except with WinWait or WinWaitClose.Cloaked windows are also considered hidden. Cloaked windows, introduced with Windows 8, are windows on a non-active virtual desktop or UWP apps which have been suspended to improve performance, or more precisely to reduce their memory consumption. On Windows 10, the processes of those are indicated with a green leaf in the Task Manager. Such windows are hidden from view, but might still have the WS_VISIBLE window style.
45 |The built-in variable A_DetectHiddenWindows contains the current setting (1 or 0).
46 |Every newly launched thread (such as a hotkey, custom menu item, or timed subroutine) starts off fresh with the default setting for this function. That default may be changed by using this function during script startup.
47 |Copies a folder along with all its sub-folders and files (similar to xcopy) or the entire contents of an archive file such as ZIP.
17 | 18 |DirCopy Source, Dest , Overwrite19 |
Type: String
25 |Name of the source directory (with no trailing backslash), which is assumed to be in A_WorkingDir if an absolute path isn't specified. For example: C:\My Folder
26 |If supported by the OS, Source can also be the path of an archive file, in which case its contents will be copied to the destination directory. ZIP files are always supported. TAR files require at least Windows 10 (1803) build 17063. RAR, 7z, gz and others require at least Windows 11 23H2 (which uses libarchive, where all supported formats are listed).
27 |Type: String
32 |Name of the destination directory (with no trailing baskslash), which is assumed to be in A_WorkingDir if an absolute path isn't specified. For example: C:\Copy of My Folder
33 |Type: Integer
38 |If omitted, it defaults to 0. Otherwise, specify one of the following numbers to indicate whether to overwrite files if they already exist:
39 |0: Do not overwrite existing files. The operation will fail and have no effect if Dest already exists as a file or directory.
40 |1: Overwrite existing files. However, any files or subfolders inside Dest that do not have a counterpart in Source will not be deleted.
41 |Other values are reserved for future use.
42 |An exception is thrown if an error occurs.
48 |If the source directory contains any saved webpages consisting of a PageName.htm file and a corresponding directory named PageName_files, an exception may be thrown even when the copy is successful.
49 | 50 |If the destination directory structure doesn't exist it will be created if possible.
52 |Since the operation will recursively copy a folder along with all its subfolders and files, the result of copying a folder to a destination somewhere inside itself is undefined. To work around this, first copy it to a destination outside itself, then use DirMove to move that copy to the desired location.
53 |DirCopy copies a single folder. To instead copy the contents of a folder (all its files and subfolders), see the examples section of FileCopy.
54 |DirMove, FileCopy, FileMove, FileDelete, file loops, DirSelect, SplitPath
56 |Prompts the user to copy a folder.
64 |SourceFolder := DirSelect(, 3, "Select the folder to copy") 65 | if SourceFolder = "" 66 | return 67 | ; Otherwise, continue. 68 | TargetFolder := DirSelect(, 3, "Select the folder IN WHICH to create the duplicate folder.") 69 | if TargetFolder = "" 70 | return 71 | ; Otherwise, continue. 72 | Result := MsgBox("A copy of the folder '" SourceFolder "' will be put into '" TargetFolder "'. Continue?",, 4) 73 | if Result = "No" 74 | return 75 | SplitPath SourceFolder, &SourceFolderName ; Extract only the folder name from its full path. 76 | try 77 | DirCopy SourceFolder, TargetFolder "\" SourceFolderName 78 | catch 79 | MsgBox "The folder could not be copied, perhaps because a folder of that name already exists in '" TargetFolder "'." 80 | return81 |
Creates a folder.
17 | 18 |DirCreate DirName
19 | Type: String
25 |Name of the directory to create, which is assumed to be in A_WorkingDir if an absolute path isn't specified.
26 |An OSError is thrown if an error occurs.
32 |A_LastError is set to the result of the operating system's GetLastError() function.
33 | 34 |This function will also create all parent directories given in DirName if they do not already exist.
36 |Creates a new directory, including its parent directories if necessary.
41 |DirCreate "C:\Test1\My Images\Folder2"42 |
Deletes a folder.
17 | 18 |DirDelete DirName , Recurse19 |
Type: String
25 |Name of the directory to delete, which is assumed to be in A_WorkingDir if an absolute path isn't specified.
26 |Type: Boolean
31 |If omitted, it defaults to false.
32 |If false, files and subdirectories contained in DirName are not removed. In this case, if DirName is not empty, no action is taken and an exception is thrown.
33 |If true, all files and subdirectories are removed (like the Windows command "rmdir /S").
34 |An exception is thrown if an error occurs.
40 | 41 |Removes the directory including its files and subdirectories.
51 |DirDelete "C:\Download Temp", true52 |
Checks for the existence of a folder and returns its attributes.
17 | 18 |AttributeString := DirExist(FilePattern)
19 | Type: String
25 |The name of a single folder or a wildcard pattern such as "C:\Program*"
. FilePattern is assumed to be in A_WorkingDir if an absolute path isn't specified.
Both asterisks (*
) and question marks (?
) are supported as wildcards. *
matches zero or more characters and ?
matches any single character. Usage examples:
*
matches all folders.gr?y
matches e.g. gray and grey.*report*
matches any folder name containing the word "report".Type: String
38 |This function returns the attributes of the first matching folder. This string is a subset of RASHDOC
, where each letter means the following:
Since this function only checks for the existence of a folder, "D" is always present in the return value. If no folder is found, an empty string is returned.
49 | 50 |Note that searches such as DirExist("MyFolder\*")
with MyFolder containing files and subfolders will only tell you whether a folder exists. If you want to check for the existence of files and folders, use FileExist instead.
Unlike FileGetAttrib, DirExist supports wildcard patterns and always returns a non-empty value if a matching folder exists.
53 |Since an empty string is seen as "false", the function's return value can always be used as a quasi-boolean value. For example, the statement if DirExist("C:\MyFolder")
would be true if the folder exists and false otherwise.
Since FilePattern may contain wildcards, DirExist may be unsuitable for validating a folder path which is to be used with another function or program. For example, DirExist("Program*")
may return attributes even though "Program*" is not a valid folder name. In such cases, FileGetAttrib is preferred.
FileExist, FileGetAttrib, file loops
58 | 59 |Shows a message box if a folder does exist.
62 |if DirExist("C:\Windows") 63 | MsgBox "The target folder does exist."64 |
Shows a message box if at least one program folder does exist.
68 |if DirExist("C:\Program*") 69 | MsgBox "At least one program folder exists."70 |
Shows a message box if a folder does not exist.
74 |if not DirExist("C:\Temp") 75 | MsgBox "The target folder does not exist."76 |
Demonstrates how to check a folder for a specific attribute.
80 |if InStr(DirExist("C:\System Volume Information"), "H") 81 | MsgBox "The folder is hidden."82 |
Moves a folder along with all its sub-folders and files. It can also rename a folder.
17 | 18 |DirMove Source, Dest , OverwriteOrRename19 |
Type: String
25 |Name of the source directory (with no trailing backslash), which is assumed to be in A_WorkingDir if an absolute path isn't specified. For example: C:\My Folder
26 |Type: String
31 |The new path and name of the directory (with no trailing baskslash), which is assumed to be in A_WorkingDir if an absolute path isn't specified. For example: D:\My Folder.
32 |Note: Dest is the actual path and name that the directory will have after it is moved; it is not the directory into which Source is moved (except for the known limitation mentioned below).
33 |Type: String
38 |If omitted, it defaults to 0. Otherwise, specify one of the following values to indicate whether to overwrite or rename existing files:
39 |0: Do not overwrite existing files. The operation will fail if Dest already exists as a file or directory.
40 |1: Overwrite existing files. However, any files or subfolders inside Dest that do not have a counterpart in Source will not be deleted. Known limitation: If Dest already exists as a folder and it is on the same volume as Source, Source will be moved into it rather than overwriting it. To avoid this, see the next option.
41 |2: The same as mode 1 above except that the limitation is absent.
42 |R: Rename the directory rather than moving it. Although renaming normally has the same effect as moving, it is helpful in cases where you want "all or none" behavior; that is, when you don't want the operation to be only partially successful when Source or one of its files is locked (in use). Although this method cannot move Source onto a different volume, it can move it to any other directory on its own volume. The operation will fail if Dest already exists as a file or directory.
43 |An exception is thrown if an error occurs.
49 | 50 |DirMove moves a single folder to a new location. To instead move the contents of a folder (all its files and subfolders), see the examples section of FileMove.
52 |If the source and destination are on different volumes or UNC paths, a copy/delete operation will be performed rather than a move.
53 |DirCopy, FileCopy, FileMove, FileDelete, file loops, DirSelect, SplitPath
55 |Directories can be "renamed into" another location as long as it's on the same volume.
68 |DirMove "C:\My Folder", "C:\New Location\My Folder", "R"69 |
Displays a standard dialog that allows the user to select a folder.
17 | 18 |SelectedFolder := DirSelect(StartingFolder, Options, Prompt)19 |
Type: String
25 |If blank or omitted, the dialog's initial selection will be the user's My Documents folder or possibly This PC (formerly My Computer or Computer). A CLSID folder such as "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
(i.e. This PC) may be specified start navigation at a specific special folder.
Otherwise, the most common usage of this parameter is an asterisk followed immediately by the absolute path of the drive or folder to be initially selected. For example, "*C:\"
would initially select the C drive. Similarly, "*C:\My Folder"
would initially select that particular folder.
The asterisk indicates that the user is permitted to navigate upward (closer to the root) from the starting folder. Without the asterisk, the user would be forced to select a folder inside StartingFolder (or StartingFolder itself). One benefit of omitting the asterisk is that StartingFolder is initially shown in a tree-expanded state, which may save the user from having to click the first plus sign.
28 |If the asterisk is present, upward navigation may optionally be restricted to a folder other than Desktop. This is done by preceding the asterisk with the absolute path of the uppermost folder followed by exactly one space or tab. For example, "C:\My Folder *C:\My Folder\Projects"
would not allow the user to navigate any higher than C:\My Folder (but the initial selection would be C:\My Folder\Projects).
Type: Integer
34 |If omitted, it defaults to 1. Otherwise, specify one of the following numbers:
35 |0: The options below are all disabled.
36 |1: A button is provided that allows the user to create new folders.
37 |Add 2 to the above number to provide an edit field that allows the user to type the name of a folder. For example, a value of 3 for this parameter provides both an edit field and a "make new folder" button.
38 |Add 4 to the above number to omit the BIF_NEWDIALOGSTYLE property. Adding 4 ensures that DirSelect will work properly even in a Preinstallation Environment like WinPE or BartPE. However, this prevents the appearance of a "make new folder" button.
39 |If the user types an invalid folder name in the edit field, SelectedFolder will be set to the folder selected in the navigation tree rather than what the user entered.
40 |Type: String
45 |If blank or omitted, it defaults to "Select Folder - " A_ScriptName
(i.e. the name of the current script). Otherwise, specify the text displayed in the window to instruct the user what to do.
Type: String
52 |This function returns the full path and name of the folder chosen by the user. If the user cancels the dialog (i.e. does not wish to select a folder), an empty string is returned. If the user selects a root directory (such as C:\), the return value will contain a trailing backslash. If this is undesirable, remove it as follows:
53 |Folder := RegExReplace(DirSelect(), "\\$") ; Removes the trailing backslash, if present.54 |
An empty string is also returned if the system refused to show the dialog, but this is very rare.
55 | 56 |A folder-selection dialog usually looks like this:
58 | 59 |A GUI window may display a modal folder-selection dialog by means of the +OwnDialogs option. A modal dialog prevents the user from interacting with the GUI window until the dialog is dismissed.
60 | 61 |FileSelect, MsgBox, InputBox, ToolTip, GUI, CLSID List, DirCopy, DirMove, SplitPath
63 |Also, the operating system offers standard dialog boxes that prompt the user to pick a font, color, or icon. These dialogs can be displayed via DllCall in combination with comdlg32\ChooseFont, comdlg32\ChooseColor, or shell32\PickIconDlg. Search the forums for examples.
64 |Allows the user to select a folder and provides both an edit field and a "make new folder" button.
67 |SelectedFolder := DirSelect(, 3) 68 | if SelectedFolder = "" 69 | MsgBox "You didn't select a folder." 70 | else 71 | MsgBox "You selected folder '" SelectedFolder "'."72 |
A CLSID example. Allows the user to select a folder in This PC (formerly My Computer or Computer).
76 |SelectedFolder := DirSelect("::{20D04FE0-3AEA-1069-A2D8-08002B30309D}")77 |
Calls a function inside a DLL, such as a standard Windows API function.
16 | 17 |Result := DllCall("DllFile\Function" , Type1, Arg1, Type2, Arg2, "Cdecl ReturnType")18 |
The DLL or EXE file name followed by a backslash and the name of the function. For example: "MyDLL\MyFunction"
(the file extension ".dll" is the default when omitted). If an absolute path isn't specified, DllFile is assumed to be in the system's PATH or A_WorkingDir. Note that DllCall expects a path with backslashes (\). Forward slashes (/) are not supported.
DllFile may be omitted when calling a function that resides in User32.dll, Kernel32.dll, ComCtl32.dll, or Gdi32.dll. For example, "User32\IsWindowVisible"
produces the same result as "IsWindowVisible"
.
If no function can be found by the given name, a "W" (Unicode) suffix is automatically appended. For example, "MessageBox"
is the same as "MessageBoxW"
.
Performance can be dramatically improved when making repeated calls to a DLL by loading it beforehand.
28 |This parameter may also consist solely of an integer, which is interpreted as the address of the function to call. Sources of such addresses include COM and CallbackCreate.
29 |If this parameter is an object, the value of the object's Ptr
property is used. If no such property exists, a PropertyError is thrown.
Type: String
35 |Each of these pairs represents a single parameter to be passed to the function. The number of pairs is unlimited. For Type, see the types table below. For Arg, specify the value to be passed to the function.
36 |Type: String
41 |The word Cdecl is normally omitted because most functions use the standard calling convention rather than the "C" calling convention (functions such as wsprintf that accept a varying number of arguments are one exception to this). Note that most object-oriented C++ functions use the thiscall convention, which is not supported.
42 |If present, the word Cdecl should be listed before the return type (if any). Separate each word from the next with a space or tab. For example: "Cdecl Str"
.
Since a separate "C" calling convention does not exist in 64-bit code, Cdecl may be specified but has no effect on 64-bit builds of AutoHotkey.
44 |ReturnType: If the function returns a 32-bit signed integer (Int), BOOL, or nothing at all, ReturnType may be omitted. Otherwise, specify one of the argument types from the types table below. The asterisk suffix is also supported.
45 |DllCall returns the actual value returned by Function. If Function is of a type that does not return a value, the result is an undefined value of the specified return type (integer by default).
52 | 53 |Type | 57 |Description | 58 |
---|---|
Str | 61 |
62 | A string such as If the function is designed to store a string longer than the parameter's input value (or if the parameter is for output only), the recommended approach is to create a Buffer, use the Ptr type to pass it, and use StrGet to retrieve the string after the function returns, as in the wsprintf example. 64 |Otherwise, ensure that the variable is large enough before calling the function. This can be achieved by calling A Str argument must not be an expression that evaluates to a number (such as The rarely-used Str* arg type passes the address of a temporary variable containing the address of the string. If the function writes a new address into the temporary variable, the new string is copied into the script's variable, if a VarRef was passed. This can be used with functions that expect something like "TCHAR **" or "LPTSTR *". However, if the function allocates memory and expects the caller to free it (such as by calling CoTaskMemFree), the Note: When passing a string to a function, be aware what type of string the function expects. |
68 |
WStr | 71 |Since AutoHotkey uses UTF-16 natively, WStr (wide character string) is equivalent to Str. | 72 |
AStr | 75 |
76 | AStr causes the input value to be automatically converted to ANSI. Since the temporary memory used for this conversion is only large enough for the converted input string, any value written to it by the function is discarded. To receive an ANSI string as an output parameter, follow this example: 77 |buf := Buffer(length) ; Allocate temporary buffer. 78 | DllCall("Function", "ptr", buf) ; Pass buffer to function. 79 | str := StrGet(buf, "cp0") ; Retrieve ANSI string from buffer. 80 |81 | The rarely-used AStr* arg type is also supported and behaves similarly to the Str* type, except that any new string is converted from ANSI to the native format, UTF-16. 82 |See Binary Compatibility for equivalent Win32 types and other details. 83 | |
84 |
Int64 | 87 |A 64-bit integer, whose range is -9223372036854775808 (-0x8000000000000000) to 9223372036854775807 (0x7FFFFFFFFFFFFFFF). | 88 |
Int | 91 |A 32-bit integer (the most common integer type), whose range is -2147483648 (-0x80000000) to 2147483647 (0x7FFFFFFF). An Int is sometimes called a "Long". 92 |An Int should also be used for each BOOL argument expected by a function (a BOOL value should be either 1 or 0). 93 |An unsigned Int (UInt) is also used quite frequently, such as for DWORD. |
94 |
Short | 97 |A 16-bit integer, whose range is -32768 (-0x8000) to 32767 (0x7FFF). An unsigned Short (UShort) can be used with functions that expect a WORD. | 98 |
Char | 101 |An 8-bit integer, whose range is -128 (-0x80) to 127 (0x7F). An unsigned character (UChar) can be used with functions that expect a BYTE. | 102 |
Float | 105 |A 32-bit floating point number, which provides 6 digits of precision. | 106 |
Double | 109 |A 64-bit floating point number, which provides 15 digits of precision. | 110 |
Ptr | 113 |A pointer-sized integer, equivalent to Int or Int64 depending on whether the exe running the script is 32-bit or 64-bit. Ptr should be used for pointers to arrays or structures (such as RECT* or LPPOINT) and almost all handles (such as HWND, HBRUSH or HBITMAP). If the parameter is a pointer to a single numeric value such as LPDWORD or int*, generally the * or P suffix should be used instead of "Ptr". 114 |If an object is passed to a Ptr parameter, the value of the object's If an object is passed to a Ptr* parameter, the value of the object's Ptr can also be used with the * or P suffix; it should be used with functions that output a pointer via LPVOID* or similar. 117 |UPtr is also valid, with the following limitations: 118 |
Note: To pass a NULL handle or pointer, pass the integer 0. |
123 |
* or P 126 | (suffix) |
127 | Append an asterisk (with optional preceding space) to any of the above types to cause the address of the argument to be passed rather than the value itself (the called function must be designed to accept it). Since the value of such an argument might be modified by the function, whenever a VarRef is passed as the argument, the variable's contents will be updated after the function returns. For example, the following call would pass the contents of MyVar to MyFunction by address, but would also update MyVar to reflect any changes made to it by MyFunction: In general, an asterisk is used whenever a function has an argument type or return type that starts with "LP". The most common example is LPDWORD, which is a pointer to a DWORD. Since a DWORD is an unsigned 32-bit integer, use "UInt*" or "UIntP" to represent LPDWORD. An asterisk should not be used for string types such as LPTSTR, pointers to structures such as LPRECT, or arrays; for these, "Str" or "Ptr" should be used, depending on whether you pass a string, address or Buffer. 129 |Note: "Char*" is not the same as "Str" because "Char*" passes the address of an 8-bit number, whereas "Str" passes the address of a series of characters, which may be either 16-bit (Unicode) or 8-bit (for "AStr"), depending on the version of AutoHotkey. Similarly, "UInt*" passes the address of a 32-bit number, so should not be used if the function expects an array of values or a structure larger than 32 bits. 130 |Since variables in AutoHotkey have no fixed type, the address passed to the function points to temporary memory rather than the caller's variable. 131 | |
132 |
U (prefix) | 135 |Prepend the letter U to any of the integer types above to interpret it as an unsigned integer (UInt64, UInt, UShort, and UChar). Strictly speaking, this is necessary only for return values and asterisk variables because it does not matter whether an argument passed by value is unsigned or signed (except for Int64). 136 |If a negative integer is specified for an unsigned argument, the integer wraps around into the unsigned domain. For example, when -1 is sent as a UInt, it would become 0xFFFFFFFF. 137 |Unsigned 64-bit integers produced by a function are not supported. Therefore, to work with numbers greater or equal to 0x8000000000000000, omit the U prefix and interpret any negative values received from the function as large integers. For example, a function that yields -1 as an Int64 is really yielding 0xFFFFFFFFFFFFFFFF if it is designed to yield a UInt64. 138 | |
139 |
HRESULT | 142 |
143 | A 32-bit integer. This is generally used with COM functions and is valid only as a return type without any prefix or suffix. Error values (as defined by the FAILED macro) are never returned; instead, an OSError is thrown. Therefore, the return value is a success code in the range 0 to 2147483647. 144 |HRESULT is the default return type for ComCall. 145 | |
146 |
DllCall throws an Error under any of the following conditions:
151 |Exception.Extra
contains the hexadecimal error code.Exception.Extra
contains the exception code. For example, 0xC0000005 means "access violation". In such cases, the thread is aborted (if try is not used), but any asterisk variables are still updated. An example of a fatal exception is dereferencing an invalid pointer such as NULL (0). Since a Cdecl function never produces the error described in the next paragraph, it may generate an exception when too few arguments are passed to it.Exception.Extra
contains the number of bytes by which the argument list was incorrect. If it is positive, too many arguments (or arguments that were too large) were passed, or the call requires CDecl. If it is negative, too few arguments were passed. This situation should be corrected to ensure reliable operation of the function. The presence of this error may also indicate that an exception occurred. Note that due to the x64 calling convention, 64-bit builds never raise this error.In spite of the built-in exception handling, it is still possible to crash a script with DllCall. This can happen when a function does not directly generate an exception but yields something inappropriate, such as a bad pointer or a string that is not terminated. This might not be the function's fault if the script passed it an unsuitable value such as a bad pointer or a "str" with insufficient capacity. A script can also crash when it specifies an inappropriate argument type or return type, such as claiming that an ordinary integer yielded by a function is an asterisk variable or str.
164 |The built-in variable A_LastError contains the result of the operating system's GetLastError() function.
165 | 166 |When making repeated calls to a DLL, performance can be dramatically improved by loading it explicitly (this is not necessary for a standard DLL such as User32 because it is always resident). This practice avoids the need for DllCall to internally call LoadLibrary and FreeLibrary each time. For example:
168 |hModule := DllCall("LoadLibrary", "Str", "MyFunctions.dll", "Ptr") ; Avoids the need for DllCall in the loop to load the library. 169 | Loop Files, "C:\My Documents\*.*", "R" 170 | result := DllCall("MyFunctions\BackupFile", "Str", A_LoopFilePath) 171 | DllCall("FreeLibrary", "Ptr", hModule) ; To conserve memory, the DLL may be unloaded after using it.172 |
Even faster performance can be achieved by looking up the function's address beforehand. For example:
173 |; In the following example, if the DLL isn't yet loaded, use LoadLibrary in place of GetModuleHandle. 174 | MulDivProc := DllCall("GetProcAddress", "Ptr", DllCall("GetModuleHandle", "Str", "kernel32", "Ptr"), "AStr", "MulDiv", "Ptr") 175 | Loop 500 176 | DllCall(MulDivProc, "Int", 3, "Int", 4, "Int", 3)177 |
If DllCall's first parameter is a literal string such as "MulDiv"
and the DLL containing the function is ordinarily loaded before the script starts, or has been successfully loaded with #DllLoad, the string is automatically resolved to a function address. This built-in optimization is more effective than the example shown above.
Finally, when passing a string-variable to a function that will not change the length of the string, performance is improved by passing the variable by address (e.g. StrPtr(MyVar)
) rather than as a "str" (especially when the string is very long). The following example converts a string to uppercase: DllCall("CharUpper", "Ptr", StrPtr(MyVar), "Ptr")
.
A structure is a collection of members (fields) stored adjacently in memory. Most members tend to be integers.
182 |Functions that accept the address of a structure (or a memory-block array) can be called by allocating memory by some means and passing the memory address to the function. The Buffer object is recommended for this purpose. The following steps are generally used:
183 |1) Call MyStruct := Buffer(123, 0)
to allocate a buffer to hold the structure's data. Replace 123
with a number that is at least as large as the size of the structure, in bytes. Specifying zero as the last parameter is optional; it initializes all members to be binary zero, which is typically used to avoid calling NumPut as often in the next step.
2) If the target function uses the values initially in the structure, call NumPut("UInt", 123, MyStruct, 4)
to initialize any members that should be non-zero. Replace 123
with the integer to be put into the target member (or specify StrPtr(Var)
to store the address of a string). Replace 4
with the offset of the target member (see step #4 for description of "offset"). Replace "UInt"
with the appropriate type, such as "Ptr"
if the member is a pointer or handle.
3) Call the target function, passing MyStruct as a Ptr argument. For example, DllCall("MyDll\MyFunc", "Ptr", MyStruct)
. The function will examine and/or change some of the members. DllCall automatically uses the address of the buffer, which is normally retrieved by using MyStruct.Ptr
.
4) Use MyInteger := NumGet(MyStruct, 4, "UInt")
to retrieve any desired integers from the structure. Replace 4
with the offset of the target member in the structure. The first member is always at offset 0. The second member is at offset 0 plus the size of the first member (typically 4). Members beyond the second are at the offset of the previous member plus the size of the previous member. Most members -- such as DWORD, Int, and other types of 32-bit integers -- are 4 bytes in size. Replace "UInt"
with the appropriate type or omit it if the member is a pointer or handle.
See Structure Examples for actual usages.
188 | 189 |When a variable's string address (e.g. StrPtr(MyVar)
) is passed to a function and that function alters the length of the variable's contents, subsequent uses of the variable may behave incorrectly. To fix this, do one of the following: 1) Pass MyVar as a "Str" argument rather than as a Ptr/address; 2) Call VarSetStrCapacity(&MyVar, -1)
to update the variable's internally-stored length after calling DllCall.
Any binary zero stored in a variable by a function may act as a terminator, preventing all data to the right of the zero from being accessed or changed by most built-in functions. However, such data can be manipulated by retrieving the string's address with StrPtr and passing it to other functions, such as NumPut, NumGet, StrGet, StrPut, and DllCall itself.
192 |A function that returns the address of one of the strings that was passed into it might return an identical string in a different memory address than expected. For example calling CharLower(CharUpper(MyVar))
in a programming language would convert MyVar's contents to lowercase. But when the same is done with DllCall, MyVar would be uppercase after the following call because CharLower would have operated on a different/temporary string whose contents were identical to MyVar:
MyVar := "ABC" 194 | result := DllCall("CharLower", "Str", DllCall("CharUpper", "Str", MyVar, "Str"), "Str")195 |
To work around this, change the two underlined "Str" values above to Ptr. This interprets CharUpper's return value as a pure address that will get passed as an integer to CharLower.
196 |Certain limitations may be encountered when dealing with strings. For details, see Binary Compatibility.
197 | 198 |COM objects which are accessible to VBScript and similar languages are typically also accessible to AutoHotkey via ComObject, ComObjGet or ComObjActive and the built-in object syntax.
200 |COM objects which don't support IDispatch can be used with DllCall by retrieving the address of a function from the virtual function table of the object's interface. For more details, see the example further below. However, it is usually better to use ComCall, which streamlines this process.
201 | 202 |.NET Framework libraries are executed by a "virtual machine" known as the Common Language Runtime, or CLR. That being the case, .NET DLL files are formatted differently to normal DLL files, and generally do not contain any functions which DllCall is capable of calling.
204 |However, AutoHotkey can utilize the CLR through COM callable wrappers. Unless the library is also registered as a general COM component, the CLR itself must first be manually initialized via DllCall. For details, see .NET Framework Interop.
205 | 206 |Binary Compatibility, Buffer object, ComCall, PostMessage, OnMessage, CallbackCreate, Run, VarSetStrCapacity, Functions, SysGet, #DllLoad, Windows API Index
208 | 209 |Calls the Windows API function "MessageBox" and reports which button the user presses.
212 |WhichButton := DllCall("MessageBox", "Int", 0, "Str", "Press Yes or No", "Str", "Title of box", "Int", 4) 213 | MsgBox "You pressed button #" WhichButton214 |
Changes the desktop wallpaper to the specified bitmap (.bmp) file.
218 |DllCall("SystemParametersInfo", "UInt", 0x14, "UInt", 0, "Str", A_WinDir . "\winnt.bmp", "UInt", 1)219 |
Calls the API function "IsWindowVisible" to find out if a Notepad window is visible.
223 |DetectHiddenWindows True 224 | if not DllCall("IsWindowVisible", "Ptr", WinExist("Untitled - Notepad")) ; WinExist returns an HWND. 225 | MsgBox "The window is not visible."226 |
Calls the API's wsprintf() to pad the number 432 with leading zeros to make it 10 characters wide (0000000432).
230 |ZeroPaddedNumber := Buffer(20) ; Ensure the buffer is large enough to accept the new string. 231 | DllCall("wsprintf", "Ptr", ZeroPaddedNumber, "Str", "%010d", "Int", 432, "Cdecl") ; Requires the Cdecl calling convention. 232 | MsgBox StrGet(ZeroPaddedNumber) 233 | 234 | ; Alternatively, use the Format function in conjunction with the zero flag: 235 | MsgBox Format("{:010}", 432) 236 |237 |
Demonstrates QueryPerformanceCounter(), which gives more precision than A_TickCount's 10 ms.
241 |DllCall("QueryPerformanceFrequency", "Int64*", &freq := 0) 242 | DllCall("QueryPerformanceCounter", "Int64*", &CounterBefore := 0) 243 | Sleep 1000 244 | DllCall("QueryPerformanceCounter", "Int64*", &CounterAfter := 0) 245 | MsgBox "Elapsed QPC time is " . (CounterAfter - CounterBefore) / freq * 1000 " ms"246 |
Press a hotkey to temporarily reduce the mouse cursor's speed, which facilitates precise positioning. Hold down F1 to slow down the cursor. Release it to return to original speed.
250 | 251 |252 | F1:: 253 | F1 up:: 254 | { 255 | static SPI_GETMOUSESPEED := 0x70 256 | static SPI_SETMOUSESPEED := 0x71 257 | static OrigMouseSpeed := 0 258 | 259 | switch ThisHotkey 260 | { 261 | case "F1": 262 | ; Retrieve the current speed so that it can be restored later: 263 | DllCall("SystemParametersInfo", "UInt", SPI_GETMOUSESPEED, "UInt", 0, "Ptr*", &OrigMouseSpeed, "UInt", 0) 264 | ; Now set the mouse to the slower speed specified in the next-to-last parameter (the range is 1-20, 10 is default): 265 | DllCall("SystemParametersInfo", "UInt", SPI_SETMOUSESPEED, "UInt", 0, "Ptr", 3, "UInt", 0) 266 | KeyWait "F1" ; This prevents keyboard auto-repeat from doing the DllCall repeatedly. 267 | 268 | case "F1 up": 269 | DllCall("SystemParametersInfo", "UInt", SPI_SETMOUSESPEED, "UInt", 0, "Ptr", OrigMouseSpeed, "UInt", 0) ; Restore the original speed. 270 | } 271 | }272 |
Monitors the active window and displays the position of its vertical scroll bar in its focused control (with real-time updates).
276 |SetTimer WatchScrollBar, 100 277 | 278 | WatchScrollBar() 279 | { 280 | FocusedHwnd := 0 281 | try FocusedHwnd := ControlGetFocus("A") 282 | if !FocusedHwnd ; No focused control. 283 | return 284 | ; Display the vertical or horizontal scroll bar's position in a tooltip: 285 | ToolTip DllCall("GetScrollPos", "Ptr", FocusedHwnd, "Int", 1) ; Last parameter is 1 for SB_VERT, 0 for SB_HORZ. 286 | }287 |
Writes some text to a file then reads it back into memory. This method can be used to help performance in cases where multiple files are being read or written simultaneously. Alternatively, FileOpen can be used to achieve the same effect.
291 |292 | FileName := FileSelect("S16",, "Create a new file:") 293 | if FileName = "" 294 | return 295 | GENERIC_WRITE := 0x40000000 ; Open the file for writing rather than reading. 296 | CREATE_ALWAYS := 2 ; Create new file (overwriting any existing file). 297 | hFile := DllCall("CreateFile", "Str", FileName, "UInt", GENERIC_WRITE, "UInt", 0, "Ptr", 0, "UInt", CREATE_ALWAYS, "UInt", 0, "Ptr", 0, "Ptr") 298 | if !hFile 299 | { 300 | MsgBox "Can't open '" FileName "' for writing." 301 | return 302 | } 303 | 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. 304 | StrSize := StrLen(TestString) * 2 305 | DllCall("WriteFile", "Ptr", hFile, "Str", TestString, "UInt", StrSize, "UIntP", &BytesActuallyWritten := 0, "Ptr", 0) 306 | DllCall("CloseHandle", "Ptr", hFile) ; Close the file. 307 | 308 | ; Now that the file was written, read its contents back into memory. 309 | GENERIC_READ := 0x80000000 ; Open the file for reading rather than writing. 310 | OPEN_EXISTING := 3 ; This mode indicates that the file to be opened must already exist. 311 | FILE_SHARE_READ := 0x1 ; This and the next are whether other processes can open the file while we have it open. 312 | FILE_SHARE_WRITE := 0x2 313 | hFile := DllCall("CreateFile", "Str", FileName, "UInt", GENERIC_READ, "UInt", FILE_SHARE_READ|FILE_SHARE_WRITE, "Ptr", 0, "UInt", OPEN_EXISTING, "UInt", 0, "Ptr", 0) 314 | if !hFile 315 | { 316 | MsgBox "Can't open '" FileName "' for reading." 317 | return 318 | } 319 | ; Allocate a block of memory for the string to read: 320 | Buf := Buffer(StrSize) 321 | DllCall("ReadFile", "Ptr", hFile, "Ptr", Buf, "UInt", Buf.Size, "UIntP", &BytesActuallyRead := 0, "Ptr", 0) 322 | DllCall("CloseHandle", "Ptr", hFile) ; Close the file. 323 | MsgBox "The following string was read from the file: " StrGet(Buf)324 |
Hides the mouse cursor when you press Win+C. To later show the cursor, press this hotkey again.
328 |OnExit (*) => SystemCursor("Show") ; Ensure the cursor is made visible when the script exits.
329 |
330 | #c::SystemCursor("Toggle") ; Win+C hotkey to toggle the cursor on and off.
331 |
332 | SystemCursor(cmd) ; cmd = "Show|Hide|Toggle|Reload"
333 | {
334 | static visible := true, c := Map()
335 | static sys_cursors := [32512, 32513, 32514, 32515, 32516, 32642
336 | , 32643, 32644, 32645, 32646, 32648, 32649, 32650]
337 | if (cmd = "Reload" or !c.Count) ; Reload when requested or at first call.
338 | {
339 | for i, id in sys_cursors
340 | {
341 | h_cursor := DllCall("LoadCursor", "Ptr", 0, "Ptr", id)
342 | h_default := DllCall("CopyImage", "Ptr", h_cursor, "UInt", 2
343 | , "Int", 0, "Int", 0, "UInt", 0)
344 | h_blank := DllCall("CreateCursor", "Ptr", 0, "Int", 0, "Int", 0
345 | , "Int", 32, "Int", 32
346 | , "Ptr", Buffer(32*4, 0xFF)
347 | , "Ptr", Buffer(32*4, 0))
348 | c[id] := {default: h_default, blank: h_blank}
349 | }
350 | }
351 | switch cmd
352 | {
353 | case "Show": visible := true
354 | case "Hide": visible := false
355 | case "Toggle": visible := !visible
356 | default: return
357 | }
358 | for id, handles in c
359 | {
360 | h_cursor := DllCall("CopyImage"
361 | , "Ptr", visible ? handles.default : handles.blank
362 | , "UInt", 2, "Int", 0, "Int", 0, "UInt", 0)
363 | DllCall("SetSystemCursor", "Ptr", h_cursor, "UInt", id)
364 | }
365 | }
366 | Structure example. Pass the address of a RECT structure to GetWindowRect(), which sets the structure's members to the positions of the left, top, right, and bottom sides of a window (relative to the screen).
370 |Run "Notepad" 371 | WinWait "Untitled - Notepad" ; This also sets the "last found window" for use with WinExist below. 372 | Rect := Buffer(16) ; A RECT is a struct consisting of four 32-bit integers (i.e. 4*4=16). 373 | DllCall("GetWindowRect", "Ptr", WinExist(), "Ptr", Rect) ; WinExist returns an HWND. 374 | L := NumGet(Rect, 0, "Int"), T := NumGet(Rect, 4, "Int") 375 | R := NumGet(Rect, 8, "Int"), B := NumGet(Rect, 12, "Int") 376 | MsgBox Format("Left {1} Top {2} Right {3} Bottom {4}", L, T, R, B)377 |
Structure example. Pass to FillRect() the address of a RECT structure that indicates a part of the screen to temporarily paint red.
381 |Rect := Buffer(16) ; Set capacity to hold four 4-byte integers. 382 | NumPut( "Int", 0 ; left 383 | , "Int", 0 ; top 384 | , "Int", A_ScreenWidth//2 ; right 385 | , "Int", A_ScreenHeight//2 ; bottom 386 | , Rect) 387 | hDC := DllCall("GetDC", "Ptr", 0, "Ptr") ; Pass zero to get the desktop's device context. 388 | hBrush := DllCall("CreateSolidBrush", "UInt", 0x0000FF, "Ptr") ; Create a red brush (0x0000FF is in BGR format). 389 | DllCall("FillRect", "Ptr", hDC, "Ptr", Rect, "Ptr", hBrush) ; Fill the specified rectangle using the brush above. 390 | DllCall("ReleaseDC", "Ptr", 0, "Ptr", hDC) ; Clean-up. 391 | DllCall("DeleteObject", "Ptr", hBrush) ; Clean-up.392 |
Structure example. Changes the system's clock to the specified date and time. Use caution when changing to a date in the future as it may cause scheduled tasks to run prematurely!
396 |SetSystemTime("20051008142211") ; Pass it a timestamp (local, not UTC). 397 | 398 | SetSystemTime(YYYYMMDDHHMISS) 399 | ; Sets the system clock to the specified date and time. 400 | ; Caller must ensure that the incoming parameter is a valid date-time stamp 401 | ; (local time, not UTC). Returns non-zero upon success and zero otherwise. 402 | { 403 | ; Convert the parameter from local time to UTC for use with SetSystemTime(). 404 | UTC_Delta := DateDiff(A_Now, A_NowUTC, "Seconds") ; Seconds is more accurate due to rounding issue. 405 | UTC_Delta := Round(-UTC_Delta/60) ; Round to nearest minute to ensure accuracy. 406 | YYYYMMDDHHMISS := DateAdd(YYYYMMDDHHMISS, UTC_Delta, "Minutes") ; Apply offset to convert to UTC. 407 | 408 | SystemTime := Buffer(16) ; This struct consists of 8 UShorts (i.e. 8*2=16). 409 | 410 | NumPut( "UShort", SubStr(YYYYMMDDHHMISS, 1, 4) ; YYYY (year) 411 | , "UShort", SubStr(YYYYMMDDHHMISS, 5, 2) ; MM (month of year, 1-12) 412 | , "UShort", 0 ; Unused (day of week) 413 | , "UShort", SubStr(YYYYMMDDHHMISS, 7, 2) ; DD (day of month) 414 | , "UShort", SubStr(YYYYMMDDHHMISS, 9, 2) ; HH (hour in 24-hour time) 415 | , "UShort", SubStr(YYYYMMDDHHMISS, 11, 2) ; MI (minute) 416 | , "UShort", SubStr(YYYYMMDDHHMISS, 13, 2) ; SS (second) 417 | , "UShort", 0 ; Unused (millisecond) 418 | , SystemTime) 419 | 420 | return DllCall("SetSystemTime", "Ptr", SystemTime) 421 | }422 |
More structure examples:
423 |Removes the active window from the taskbar for 3 seconds. Compare this to the equivalent ComCall example.
431 |/* 432 | Methods in ITaskbarList's VTable: 433 | IUnknown: 434 | 0 QueryInterface -- use ComObjQuery instead 435 | 1 AddRef -- use ObjAddRef instead 436 | 2 Release -- use ObjRelease instead 437 | ITaskbarList: 438 | 3 HrInit 439 | 4 AddTab 440 | 5 DeleteTab 441 | 6 ActivateTab 442 | 7 SetActiveAlt 443 | */ 444 | IID_ITaskbarList := "{56FDF342-FD6D-11d0-958A-006097C9A090}" 445 | CLSID_TaskbarList := "{56FDF344-FD6D-11d0-958A-006097C9A090}" 446 | 447 | ; Create the TaskbarList object. 448 | tbl := ComObject(CLSID_TaskbarList, IID_ITaskbarList) 449 | 450 | activeHwnd := WinExist("A") 451 | 452 | DllCall(vtable(tbl.ptr,3), "ptr", tbl) ; tbl.HrInit() 453 | DllCall(vtable(tbl.ptr,5), "ptr", tbl, "ptr", activeHwnd) ; tbl.DeleteTab(activeHwnd) 454 | Sleep 3000 455 | DllCall(vtable(tbl.ptr,4), "ptr", tbl, "ptr", activeHwnd) ; tbl.AddTab(activeHwnd) 456 | 457 | ; Interface pointer will be freed automatically. 458 | 459 | vtable(ptr, n) { 460 | ; NumGet(ptr, "ptr") returns the address of the object's virtual function 461 | ; table (vtable for short). The remainder of the expression retrieves 462 | ; the address of the nth function's address from the vtable. 463 | return NumGet(NumGet(ptr, "ptr"), n*A_PtrSize, "ptr") 464 | } 465 |466 |
Downloads a file from the Internet.
17 | 18 |Download URL, Filename
19 | Type: String
25 |URL of the file to download. For example, "https://someorg.org"
might retrieve the welcome page for that organization.
Type: String
31 |Specify the name of the file to be created locally, which is assumed to be in A_WorkingDir if an absolute path isn't specified. Any existing file will be overwritten by the new file.
32 |This function downloads to a file. To download to a variable instead, see the example below.
33 |An exception is thrown on failure.
39 | 40 |The download might appear to succeed even when the remote file doesn't exist. This is because many web servers send an error page instead of the missing file. This error page is what will be saved in place of Filename.
42 |Firewalls or the presence of multiple network adapters may cause this function to fail. Also, some websites may block such downloads.
43 |Caching: By default, the URL is retrieved directly from the remote server (that is, never from Internet Explorer's cache). To permit caching, precede the URL with *0 followed by a space; for example: "*0 https://someorg.org"
. The zero following the asterisk may be replaced by any valid dwFlags number; for details, search www.microsoft.com for InternetOpenUrl.
Proxies: If a proxy server has been configured in Microsoft Internet Explorer's settings, it will be used.
45 |FTP and Gopher URLS are also supported. For example:
46 |Download "ftp://example.com/home/My File.zip", "C:\My Folder\My File.zip" ; Log in anonymously. 47 | Download "ftp://user:pass@example.com:21/home/My File.zip", "C:\My Folder\My File.zip" ; Log in as a specific user. 48 | Download "ftp://user:pass@example.com/My Directory", "C:\Dir Listing.html" ; Gets a directory listing in HTML format.49 | 50 |
Download "https://www.autohotkey.com/download/2.0/version.txt", "C:\AutoHotkey Latest Version.txt"57 |
Download "https://someorg.org/archive.zip", "C:\SomeOrg's Archive.zip"62 |
whr := ComObject("WinHttp.WinHttpRequest.5.1") 67 | whr.Open("GET", "https://www.autohotkey.com/download/2.0/version.txt", true) 68 | whr.Send() 69 | ; Using 'true' above and the call below allows the script to remain responsive. 70 | whr.WaitForResponse() 71 | version := whr.ResponseText 72 | MsgBox version 73 |74 |
Makes an asynchronous HTTP request.
78 |req := ComObject("Msxml2.XMLHTTP") 79 | ; Open a request with async enabled. 80 | req.open("GET", "https://www.autohotkey.com/download/2.0/version.txt", true) 81 | ; Set our callback function. 82 | req.onreadystatechange := Ready 83 | ; Send the request. Ready() will be called when it's complete. 84 | req.send() 85 | /* 86 | ; If you're going to wait, there's no need for onreadystatechange. 87 | ; Setting async=true and waiting like this allows the script to remain 88 | ; responsive while the download is taking place, whereas async=false 89 | ; will make the script unresponsive. 90 | while req.readyState != 4 91 | sleep 100 92 | */ 93 | Persistent 94 | 95 | Ready() { 96 | if (req.readyState != 4) ; Not done yet. 97 | return 98 | if (req.status == 200) ; OK. 99 | MsgBox "Latest AutoHotkey version: " req.responseText 100 | else 101 | MsgBox "Status " req.status,, 16 102 | ExitApp 103 | }104 |
Functions for retrieving information about the computer's drive(s) or for performing various operations on a drive. Click on a function name for details.
16 |Function | 19 |Description | 20 |
---|---|
DriveEject | 23 |Ejects the tray of the specified CD/DVD drive, or ejects a removable drive. | 24 |
DriveGetCapacity | 27 |Returns the total capacity of the drive which contains the specified path, in megabytes. | 28 |
DriveGetFileSystem | 31 |Returns the type of the specified drive's file system. | 32 |
DriveGetLabel | 35 |Returns the volume label of the specified drive. | 36 |
DriveGetList | 39 |Returns a string of letters, one character for each drive letter in the system. | 40 |
DriveGetSerial | 43 |Returns the volume serial number of the specified drive. | 44 |
DriveGetSpaceFree | 47 |Returns the free disk space of the drive which contains the specified path, in megabytes. | 48 |
DriveGetStatus | 51 |Returns the status of the drive which contains the specified path. | 52 |
DriveGetStatusCD | 55 |Returns the media status of the specified CD/DVD drive. | 56 |
DriveGetType | 59 |Returns the type of the drive which contains the specified path. | 60 |
DriveLock | 63 |Prevents the eject feature of the specified drive from working. | 64 |
DriveRetract | 67 |Retracts the tray of the specified CD/DVD drive. | 68 |
DriveSetLabel | 71 |Changes the volume label of the specified drive. | 72 |
DriveUnlock | 75 |Restores the eject feature of the specified drive. | 76 |
An exception is thrown on failure.
81 | 82 |Allows the user to select a drive in order to analyze it.
89 |folder := DirSelect( , 3, "Pick a drive to analyze:") 90 | if not folder 91 | return 92 | MsgBox 93 | ( 94 | "All Drives: " DriveGetList() " 95 | Selected Drive: " folder " 96 | Drive Type: " DriveGetType(folder) " 97 | Status: " DriveGetStatus(folder) " 98 | Capacity: " DriveGetCapacity(folder) " MB 99 | Free Space: " DriveGetSpaceFree(folder) " MB 100 | Filesystem: " DriveGetFilesystem(folder) " 101 | Volume Label: " DriveGetLabel(folder) " 102 | Serial Number: " DriveGetSerial(folder) 103 | )104 |
Ejects or retracts the tray of the specified CD/DVD drive. DriveEject can also eject a removable drive.
17 | 18 |DriveEject Drive 19 | DriveRetract Drive20 | 21 |
Type: String
27 |If omitted, it defaults to the first CD/DVD drive found by iterating from A to Z (an exception is thrown if no drive is found). Otherwise, specify the drive letter optionally followed by a colon or a colon and backslash. For example, "D"
, "D:"
or "D:\"
.
This can also be a device path in the form "\\?\Volume{...}"
, which can be discovered by running mountvol at the command line. In this case the drive is not required to be assigned a drive letter.
An exception is thrown on failure, if detected.
34 |These functions will probably not work on a network drive or any drive lacking the "Eject" option in Explorer. The underlying system functions do not always report failure, so an exception may or may not be thrown.
35 | 36 |This function waits for the ejection or retraction to complete before allowing the script to continue.
38 |It may be possible to detect the previous tray state by measuring the time the function takes to complete, as in the example below.
39 |Ejecting a removable drive is generally equivalent to using the "Eject" context menu option in Explorer, except that no warning is shown if files are in use. Unlike the Safely Remove Hardware option, this only dismounts the volume identified by the Drive parameter, not the overall device.
40 |DriveEject and DriveRetract correspond to the IOCTL_STORAGE_EJECT_MEDIA and IOCTL_STORAGE_LOAD_MEDIA control codes, which may also have an effect on drive types other than CD/DVD, such as tape drives.
41 | 42 | 43 |DriveGetStatusCD, Drive functions
45 | 46 |Ejects all removable drives (except CD/DVD drives).
60 |Loop Parse DriveGetList("REMOVABLE") 61 | { 62 | if MsgBox("Eject " A_LoopField ":, even if files are open?",, "y/n") = "yes" 63 | DriveEject(A_LoopField) 64 | } 65 | else 66 | MsgBox "No removable drives found."67 |
Defines a hotkey which toggles the tray to the opposite state (open or closed), based on the time the function takes to complete.
71 |#c:: 72 | { 73 | DriveEject 74 | ; If the function completed quickly, the tray was probably already ejected. 75 | ; In that case, retract it: 76 | if (A_TimeSinceThisHotkey < 1000) ; Adjust this time if needed. 77 | DriveRetract 78 | }79 |
Returns the total capacity of the drive which contains the specified path, in megabytes.
17 | 18 |Capacity := DriveGetCapacity(Path)
19 |
20 | Type: String
25 |Any path contained by the drive (might also work on UNC paths and mapped drives).
26 |Type: Integer
31 |This function returns the total capacity of the drive which contains Path, in megabytes.
32 | 33 |An exception is thrown on failure.
35 | 36 |In general, Path can be any path. Since NTFS supports mounted volumes and directory junctions, different paths with the same drive letter can produce different amounts of capacity.
38 | 39 |DriveGetSpaceFree, Drive functions
41 | 42 |See example #1 on the Drive Functions page for a demonstration of this function.
44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /docs/lib/DriveGetFileSystem.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the type of the specified drive's file system.
17 | 18 |FileSystem := DriveGetFileSystem(Drive)
19 |
20 | Type: String
25 |The drive letter followed by a colon and an optional backslash, or a UNC name such as "\server1\share1"
.
Type: String
31 |This function returns the type of Drive's file system. The possible values are defined by the system; they include (but are not limited to) the following: NTFS, FAT32, FAT, CDFS (typically indicates a CD), or UDF (typically indicates a DVD).
32 | 33 |An exception is thrown on failure, such as if the drive does not contain formatted media.
35 | 36 |See example #1 on the Drive Functions page for a demonstration of this function.
41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /docs/lib/DriveGetLabel.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the volume label of the specified drive.
17 | 18 |Label := DriveGetLabel(Drive)
19 |
20 | Type: String
25 |The drive letter followed by a colon and an optional backslash, or a UNC name such as "\server1\share1"
.
Type: String
31 |This function returns the Drive's volume label.
32 | 33 |An exception is thrown on failure.
35 | 36 |DriveSetLabel, Drive functions
38 | 39 |See example #1 on the Drive Functions page for a demonstration of this function.
41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /docs/lib/DriveGetList.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns a string of letters, one character for each drive letter in the system.
17 | 18 |List := DriveGetList(DriveType)19 | 20 |
Type: String
25 |If omitted, all drive types are retrieved. Otherwise, specify one of the following words to retrieve only a specific type of drive: CDROM, REMOVABLE, FIXED, NETWORK, RAMDISK, UNKNOWN.
26 |Type: String
31 |This function returns the drive letters in the system, depending on DriveType. For example: ACDEZ.
32 | 33 |See example #1 on the Drive Functions page for a demonstration of this function.
38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /docs/lib/DriveGetSerial.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the volume serial number of the specified drive.
17 | 18 |Serial := DriveGetSerial(Drive)
19 |
20 | Type: String
25 |The drive letter followed by a colon and an optional backslash, or a UNC name such as "\server1\share1"
.
Type: Integer
31 |This function returns the Drive's volume serial number. See Format for how to convert it to hexadecimal.
32 | 33 |An exception is thrown on failure.
35 | 36 |See example #1 on the Drive Functions page for a demonstration of this function.
41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /docs/lib/DriveGetSpaceFree.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the free disk space of the drive which contains the specified path, in megabytes.
17 | 18 |FreeSpace := DriveGetSpaceFree(Path)
19 |
20 | Type: String
25 |Any path contained by the drive (might also work on UNC paths and mapped drives).
26 |Type: Integer
31 |This function returns the free disk space of the drive which contains Path, in megabytes (rounded down to the nearest megabyte).
32 | 33 |An exception is thrown on failure.
35 | 36 |In general, Path can be any path. Since NTFS supports mounted volumes and directory junctions, different paths with the same drive letter can produce different amounts of free space.
38 | 39 |DriveGetCapacity, Drive functions
41 | 42 |Retrieves and reports the free disk space of the drive which contains A_MyDocuments.
45 |FreeSpace := DriveGetSpaceFree(A_MyDocuments) 46 | MsgBox FreeSpace " MB"47 |
See example #1 on the Drive Functions page for another demonstration of this function.
49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /docs/lib/DriveGetStatus.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the status of the drive which contains the specified path.
17 | 18 |Status := DriveGetStatus(Path)
19 |
20 | Type: String
25 |Any path contained by the drive (might also work on UNC paths and mapped drives).
26 |Type: String
31 |This function returns the status of the drive which contains Path:
32 |Status | 35 |Notes | 36 |
---|---|
Unknown | 39 |Might indicate unformatted/RAW file system. | 40 |
Ready | 43 |This is the most common. | 44 |
NotReady | 47 |Typical for removable drives that don't contain media. | 48 |
Invalid | 51 |Path does not exist or is a network drive that is presently inaccessible, etc. | 52 |
An exception is thrown on failure.
57 | 58 |In general, Path can be any path. Since NTFS supports mounted volumes and directory junctions, different paths with the same drive letter can produce different results.
60 | 61 |See example #1 on the Drive Functions page for a demonstration of this function.
66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /docs/lib/DriveGetStatusCD.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the media status of the specified CD/DVD drive.
17 | 18 |CDStatus := DriveGetStatusCD(Drive)19 | 20 |
Type: String
25 |If omitted, the default CD/DVD drive will be used. Otherwise, specify the drive letter followed by a colon.
26 |Type: String
31 |This function returns the Drive's media status:
32 |Status | 35 |Meaning | 36 |
---|---|
not ready | 39 |The drive is not ready to be accessed, perhaps due to being engaged in a write operation. Known limitation: "not ready" also occurs when the drive contains a DVD rather than a CD. | 40 |
open | 43 |The drive contains no disc, or the tray is ejected. | 44 |
playing | 47 |The drive is playing a disc. | 48 |
paused | 51 |The previously playing audio or video is now paused. | 52 |
seeking | 55 |The drive is seeking. | 56 |
stopped | 59 |The drive contains a CD but is not currently accessing it. | 60 |
An exception is thrown on failure.
65 | 66 |This function will probably not work on a network drive or non-CD/DVD drive. If it fails in such cases or for any other reason, an exception is thrown.
68 |If the tray was recently closed, there may be a delay before the function completes.
69 | 70 |See example #1 on the Drive Functions page for a demonstration of this function.
75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /docs/lib/DriveGetType.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the type of the drive which contains the specified path.
17 | 18 |DriveType := DriveGetType(Path)
19 |
20 | Type: String
25 |Any path contained by the drive (might also work on UNC paths and mapped drives).
26 |Type: String
31 |This function returns the type of the drive which contains Path: Unknown, Removable, Fixed, Network, CDROM, or RAMDisk. If Path is invalid (e.g. because the drive does not exist), the return value is an empty string.
32 | 33 |In general, Path can be any path. Since NTFS supports mounted volumes and directory junctions, different paths with the same drive letter can produce different results.
35 | 36 |See example #1 on the Drive Functions page for a demonstration of this function.
41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /docs/lib/DriveLock.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Prevents the eject feature of the specified drive from working.
17 | 18 |DriveLock Drive
19 |
20 | Type: String
25 |The drive letter followed by a colon and an optional backslash (might also work on UNC paths and mapped drives).
26 |An exception is thrown on failure, such as if Drive does not exist or does not support the locking feature.
31 | 32 |Most drives cannot be "locked open". However, locking the drive while it is open will probably result in it becoming locked the moment it is closed.
34 |This function has no effect on drives that do not support locking (such as most read-only drives).
35 |To unlock a drive, call DriveUnlock. If a drive is locked by a script and that script exits, the drive will stay locked until another script or program unlocks it, or the system is restarted.
36 | 37 |Changes the volume label of the specified drive.
17 | 18 |DriveSetLabel Drive , NewLabel19 | 20 |
Type: String
25 |The drive letter followed by a colon and an optional backslash (might also work on UNC paths and mapped drives).
26 |Type: String
30 |If omitted, the drive will have no label. Otherwise, specify the new label to set.
31 |An exception is thrown on failure.
36 | 37 |DriveGetLabel, Drive functions
39 | 40 |Restores the eject feature of the specified drive.
17 | 18 |DriveUnlock Drive
19 |
20 | Type: String
25 |The drive letter followed by a colon and an optional backslash (might also work on UNC paths and mapped drives).
26 |An exception is thrown on failure.
31 | 32 |This function needs to be called multiple times if the drive was locked multiple times (at least for some drives). For example, if DriveLock("D:")
was called three times, DriveUnlock("D:")
might need to be called three times to unlock it. Because of this and the fact that there is no way to determine whether a drive is currently locked, it is often useful to keep track of its lock-state in a variable.
Opens the current script for editing in the default editor.
16 | 17 |Edit
18 | The Edit function opens the current script for editing using the associated "edit" verb in the registry (or Notepad if no verb). However, if an editor window appears to have the script already open (based on its window title), that window is activated instead of opening a new instance of the editor.
19 |The default program, script or command line executed by the "edit" verb can be changed via Editor settings in the Dash.
20 |This function has no effect when operating from within a compiled script.
21 |On a related note, AutoHotkey syntax highlighting can be enabled for various editors. In addition, context sensitive help for AutoHotkey functions can be enabled in any editor via this example. Finally, your productivity may be improved by using an auto-completion utility like the script by boiler or the script by Helgef, which works in almost any editor. It watches what you type and displays menus and parameter lists, which does some of the typing for you and reminds you of the order of parameters.
22 | 23 |Reload, How to edit a script, Editors with AutoHotkey support
25 | 26 | If your editor's command-line usage is something like Editor.exe "Full path of script.ahk"
, the following can be used to set it as the default editor for ahk files. When you run the script, it will prompt you to select the executable file of your editor.
Editor := FileSelect(2,, "Select your editor", "Programs (*.exe)") 35 | if Editor = "" 36 | ExitApp 37 | RegWrite Format('"{1}" "%L"', Editor), "REG_SZ", "HKCR\AutoHotkeyScript\Shell\Edit\Command"38 |
Returns the column number in an Edit control where the caret (text insertion point) resides.
17 | 18 |CurrentCol := EditGetCurrentCol(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
30 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
33 |Type: Integer
38 |This function returns the column number in an Edit control where the caret (text insertion point) resides. The first column is 1. If there is text selected in the control, the return value is the column number where the selection begins.
39 | 40 |An exception is thrown on failure, or if the window or control could not be found.
42 | 43 |EditGetCurrentLine, EditGetLineCount, EditGetLine, EditGetSelectedText, EditPaste, Control functions
45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/lib/EditGetCurrentLine.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the line number in an Edit control where the caret (text insert point) resides.
17 | 18 |CurrentLine := EditGetCurrentLine(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
30 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
33 |Type: Integer
38 |This function returns the line number in an Edit control where the caret (text insertion point) resides. The first line is 1. If there is text selected in the control, the return value is the line number where the selection begins.
39 | 40 |An exception is thrown on failure, or if the window or control could not be found.
42 | 43 |EditGetCurrentCol, EditGetLineCount, EditGetLine, EditGetSelectedText, EditPaste, Control functions
45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/lib/EditGetLine.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the text of the specified line in an Edit control.
17 | 18 |Line := EditGetLine(N, Control , WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: Integer
25 |The line number. Line 1 is the first line.
26 |Type: String, Integer or Object
30 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
35 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
36 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
37 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
38 |Type: String
43 |This function returns the text of line N in an Edit control. Depending on the nature of the control, the string might end in a carriage return (`r) or a carriage return + linefeed (`r`n).
44 | 45 |A TargetError is thrown if the window or control could not be found.
47 |A ValueError is thrown if N is out of range or otherwise invalid.
48 |An OSError is thrown if a message could not be sent to the control.
49 | 50 |EditGetCurrentCol, EditGetCurrentLine, EditGetLineCount, EditGetSelectedText, EditPaste, Control functions
52 | 53 |Retrieves the first line of the Notepad's Edit control.
56 |line1 := EditGetLine(1, "Edit1", "ahk_class Notepad")57 |
Returns the number of lines in an Edit control.
17 | 18 |LineCount := EditGetLineCount(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
30 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
33 |Type: Integer
38 |This function returns the number of lines in an Edit control. All Edit controls have at least 1 line, even if the control is empty.
39 | 40 |A TargetError is thrown if the window or control could not be found.
42 |An OSError is thrown if a message could not be sent to the control.
43 | 44 |EditGetCurrentCol, EditGetCurrentLine, EditGetLine, EditGetSelectedText, EditPaste, Control functions
46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /docs/lib/EditGetSelectedText.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the selected text in an Edit control.
17 | 18 |SelectedText := EditGetSelectedText(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
30 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
33 |Type: String
38 |This function returns the selected text in an Edit control. If no text is selected, an empty string is returned. Certain types of controls, such as RichEdit20A, might not produce the correct text in some cases (e.g. Metapad).
39 | 40 |A TargetError is thrown if the window or control could not be found.
42 |An Error or OSError is thrown if there was a problem retrieving the text.
43 | 44 |EditGetCurrentCol, EditGetCurrentLine, EditGetLineCount, EditGetLine, EditPaste, Control functions
46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /docs/lib/EditPaste.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Pastes the specified string at the caret (text insertion point) in an Edit control.
17 | 18 |EditPaste String, Control , WinTitle, WinText, ExcludeTitle, ExcludeText19 | 20 |
Type: String
25 |The string to paste.
26 |Type: String, Integer or Object
30 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
35 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
36 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
37 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
38 |A TargetError is thrown if the window or control could not be found.
43 |An OSError may be thrown if a message could not be sent to the control.
44 | 45 |The effect is similar to pasting by pressing Ctrl+V, but this function does not affect the contents of the clipboard or require the control to have the keyboard focus.
47 |To improve reliability, a delay is done automatically after each use of this function. That delay can be changed via SetControlDelay or by assigning a value to A_ControlDelay. For details, see SetControlDelay remarks.
48 | 49 |ControlSetText, Control functions
51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /docs/lib/Else.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Specifies one or more statements to execute if the associated statement's body did not execute.
15 |Else Statement
16 | Else
17 | {
18 | Statements
19 | }
20 |
21 | Every use of Else must belong to (be associated with) an If, Catch, For, Loop or While statement above it. An Else always belongs to the nearest applicable unclaimed statement above it unless a block is used to change that behavior. The condition for an Else statement executing depends on the associated statement:
23 |An Else can be followed immediately by any other single statement on the same line. This is most often used for "else if" ladders (see examples at the bottom).
30 |If an Else owns more than one line, those lines must be enclosed in braces (to create a block). However, if only one line belongs to an Else, the braces are optional. For example:
31 |if (count > 0) ; No braces are required around the next line because it's only a single line. 32 | MsgBox "Press OK to begin the process." 33 | else ; Braces must be used around the section below because it consists of more than one line. 34 | { 35 | WinClose "Untitled - Notepad" 36 | MsgBox "There are no items present." 37 | }38 |
The One True Brace (OTB) style may optionally be used around an Else. For example:
39 |if IsDone { 40 | ; ... 41 | } else if (x < y) { 42 | ; ... 43 | } else { 44 | ; ... 45 | }46 | 47 |
Blocks, If, Control Flow Statements
49 | 50 |Common usage of an Else statement. This example is executed as follows:
53 |if WinExist("Untitled - Notepad") 68 | { 69 | WinActivate 70 | Send "This is a test.{Enter}" 71 | } 72 | else 73 | { 74 | WinActivate "Some Other Window" 75 | MouseClick "Left", 100, 200 76 | }77 |
Demonstrates different styles of how the Else statement can be used too.
81 |if (x = 1) 82 | firstFunction() 83 | else if (x = 2) ; "else if" style 84 | secondFunction() 85 | else if x = 3 86 | { 87 | thirdFunction() 88 | Sleep 1 89 | } 90 | else defaultFunction() ; i.e. Any single statement can be on the same line with an Else.91 |
Executes some code if a loop had zero iterations.
95 |96 | ; Show File/Internet Explorer windows/tabs. 97 | for window in ComObject("Shell.Application").Windows 98 | MsgBox "Window #" A_Index ": " window.LocationName 99 | else 100 | MsgBox "No shell windows found." 101 |102 |
An enumerator is a type of function object which is called repeatedly to enumerate a sequence of values.
16 |Enumerators exist primarily to support For-loops, and are not usually called directly. The for-loop documentation details the process by which an enumerator is called. The script may implement an enumerator to control which values are assigned to the for-loop's variables on each iteration of the loop.
17 |Built-in enumerators are instances of the Enumerator
class (which is derived from Func), but any function object can potentially be used with a for-loop.
Retrieves the next item or items in an enumeration.
33 |Boolean := Enum.Call(&OutputVar1 , &OutputVar2)34 |
Boolean := EnumFunction(&OutputVar1 , &OutputVar2)
35 | Type: VarRef
40 |One or more references to output variables for the enumerator to assign values.
41 |Type: Integer (boolean)
45 |This method returns 1 (true) if successful or 0 (false) if there were no items remaining.
46 |A simple function definition can be used to create an enumerator; in that case, the Call method is implied.
48 |When defining your own enumerator, the number of parameters should match the number of variables expected to be passed to the for-loop (before the "in" keyword). This is usually either 1 or 2, but a for-loop can accept up to 19 variables. To allow the method to accept a varying number of variables, declare optional parameters.
49 |An exception is thrown when the for-loop attempts to call the method if there are more variables than parameters (too many parameters passed, too few defined) or fewer variables than mandatory parameters.
50 |For-loop, OwnProps, __Enum (Array), __Enum (Map)
54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /docs/lib/EnvGet.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Retrieves the value of the specified environment variable.
16 | 17 |Value := EnvGet(EnvVar)
18 | Type: String
24 |The name of the environment variable, e.g. "Path"
.
Type: String
31 |This function returns EnvVar's value. If EnvVar has an empty value or does not exist, an empty string is returned.
32 | 33 |The operating system limits each environment variable to 32 KB of text.
35 |This function exists because normal script variables are not stored in the environment. This is because performance would be worse and also because the OS limits environment variables to 32 KB.
36 |Retrieves the value of an environment variable and stores it in LogonServer.
41 |LogonServer := EnvGet("LogonServer")42 |
Retrieves and reports the path of the "Program Files" directory. See RegRead example #2 for an alternative method.
46 |ProgramFilesDir := EnvGet(A_Is64bitOS ? "ProgramW6432" : "ProgramFiles") 47 | MsgBox "Program files are in: " ProgramFilesDir48 |
Retrieves and reports the path of the current user's Local AppData directory.
52 |LocalAppData := EnvGet("LocalAppData") 53 | MsgBox A_UserName "'s Local directory is located at: " LocalAppData54 |
Writes a value to the specified environment variable.
16 | 17 |EnvSet EnvVar , Value18 |
Type: String
24 |The name of the environment variable, e.g. "Path"
.
Type: String
30 |If omitted, the environment variable will be deleted. Otherwise, specify the value to write.
31 |An OSError is thrown on failure.
37 | 38 |The operating system limits each environment variable to 32 KB of text.
40 |An environment variable created or changed with this function will be accessible only to programs the script launches via Run or RunWait. See environment variables for more details.
41 |This function exists because normal script variables are not stored in the environment. This is because performance would be worse and also because the OS limits environment variables to 32 KB.
42 |Writes some text to an environment variable.
47 |EnvSet "AutGUI", "Some text to put in the environment variable."48 |
class Error extends Object16 | 17 |
Error objects are thrown by built-in code when a runtime error occurs, and may also be thrown explicitly by the script.
18 | 19 |Message: An error message.
29 |What: What threw the exception. This is usually the name of a function, but is blank for exceptions thrown due to an error in an expression (such as using a math operator on a non-numeric value).
30 |Extra: A string value relating to the error, if available. If this value can be converted to a non-empty string, the standard error dialog displays a line with "Specifically:" followed by this string.
31 |File: The full path of the script file which contains the line at which the error occurred, or at which the Error object was constructed.
32 |Line: The line number at which the error occurred, or at which the Error object was constructed.
33 |Stack: A string representing the call stack at the time the Error object was constructed. Each line may be formatted as follows:
34 |File (Line) : [What] SourceCode`r`n
> What`r`n
... N more
Stack
property cannot exceed 2047 characters.Note: The standard error dialog requires Message, Extra, File and Line to be own value properties.
44 | 45 |Creates an Error object.
47 |NewError := Error(Message , What, Extra)48 |
Error may be replaced with one of the subclasses listed under Error Types, although some subclasses may take different parameters.
49 |The parameters directly correspond to properties described above, but may differ for Error subclasses which override the __New method.
50 |Message and Extra are converted to strings. These are displayed by an error dialog if the exception is thrown and not caught.
51 |What indicates the source of the error. It can be an arbitrary string, but should be a negative integer or the name of a running function. Specifying -1 indicates the current function, -2 indicates the function which called it, and so on. If the script is compiled or the value does not identify a valid stack frame, the value is merely converted to a string and assigned to NewError.What
. Otherwise, the identified stack frame is used as follows to determine the other properties:
NewError.What
contains the name of the function.NewError.Line
and NewError.File
indicate the line which called the function.NewError.Stack
contains a partial stack trace, with the indicated stack frame at the top.Use of the What parameter can allow a complex function to use helper functions to perform its work or parameter validation, while omitting those internal details from any reported error information. For example:
58 |MyFunction(a, b) { 59 | CheckArg "a", a 60 | CheckArg "b", b 61 | ;... 62 | CheckArg(name, value) { 63 | if value < 0 64 | throw ValueError(name " is negative", "myfunction", value) 65 | } 66 | } 67 | 68 | try 69 | MyFunction(1, -1) ; err.Line indicates this line. 70 | catch ValueError as err 71 | MsgBox Format("{1}: {2}.`n`nFile:`t{3}`nLine:`t{4}`nWhat:`t{5}`nStack:`n{6}" 72 | , type(err), err.Message, err.File, err.Line, err.What, err.Stack)73 |
try 74 | SomeFunction() 75 | catch as e 76 | MsgBox(type(e) " in " e.What ", which was called at line " e.Line) 77 | 78 | SomeFunction() { 79 | throw Error("Fail", -1) 80 | }81 | 82 |
The following subclasses of Error are predefined:
85 |OSError(Code)
where Code is numeric sets Number and Message based on the given OS-defined error code. If Code is omitted, it defaults to A_LastError. For example, OSError(5).Message
returns "(5) Access is denied."Errors are also thrown using the base Error class.
104 | 105 |Throw, Try, Catch, Finally, OnError
107 | 108 | 109 | -------------------------------------------------------------------------------- /docs/lib/Exit.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Exits the current thread.
16 | 17 |Exit ExitCode18 |
Type: Integer
24 |If omitted, it defaults to 0 (zero is traditionally used to indicate success). Otherwise, specify an integer between -2147483648 and 2147483647 that is returned to its caller when the script exits. This code is accessible to any program that spawned the script, such as another script (via RunWait) or a batch (.bat) file.
25 |The Exit function terminates only the current thread. In other words, the stack of functions called directly or indirectly by a menu, timer, or hotkey function will all be returned from as though a Return were immediately encountered in each. If used directly inside such a function -- or in global code -- Exit is equivalent to Return.
31 |If the script is not persistent and this is the last thread, the script will terminate after the thread exits.
32 | 33 |Use ExitApp to completely terminate a script that is persistent.
34 | 35 |ExitApp, OnExit, Functions, Return, Threads, Persistent
37 |In this example, the Exit function terminates the call_exit function as well as the calling function.
40 |41 | #z:: 42 | { 43 | call_exit 44 | MsgBox "This MsgBox will never happen because of the Exit." 45 | call_exit() 46 | { 47 | Exit ; Terminate this function as well as the calling function. 48 | } 49 | } 50 |51 |
Terminates the script.
16 | 17 |ExitApp ExitCode18 |
Type: Integer
24 |If omitted, it defaults to 0 (zero is traditionally used to indicate success). Otherwise, specify an integer between -2147483648 and 2147483647 that is returned to its caller when the script exits. This code is accessible to any program that spawned the script, such as another script (via RunWait) or a batch (.bat) file.
25 |This is equivalent to choosing "Exit" from the script's tray menu or main menu.
31 |Any functions registered by OnExit are called before the script terminates. If such a function returns a non-zero integer, the script does not terminate; instead, the current thread exits as if Exit was called.
32 |Terminating the script is not the same as exiting each thread. For instance, Finally blocks are not executed and __Delete is not called for objects contained by local variables.
33 |ExitApp is often unnecessary in scripts which are not persistent.
34 | 35 |class File extends Object15 | 16 |
Provides an interface for file input/output, such as reading or writing text or retrieving its length. FileOpen returns an object of this type.
17 | 18 |"FileObj" is used below as a placeholder for any File object, as "File" is the class itself.
19 |In addition to the methods and property inherited from Object, File objects have the following predefined methods and properties.
20 | 21 |Reads a string of characters from the file and advances the file pointer.
52 |String := FileObj.Read(Characters)53 |
Type: Integer
58 |If omitted, the rest of the file is read and returned as one string. Otherwise, specify the maximum number of characters to read. If the File object was created from a handle to a non-seeking device such as a console buffer or pipe, omitting this parameter may cause the method to fail or return only what data is currently available.
59 |Type: String
63 |This method returns the string of characters that were read.
64 |Writes a string of characters to the file and advances the file pointer.
68 |BytesWritten := FileObj.Write(String)
69 | Type: String
74 |The string to write.
75 |Type: Integer
79 |This method returns the number of bytes (not characters) that were written.
80 |Reads a line of text from the file and advances the file pointer.
84 |TextLine := FileObj.ReadLine()
85 | Type: String
87 |This method returns a line of text, excluding the line ending.
88 |Lines up to 65,534 characters long can be read. If the length of a line exceeds this, the remainder of the line is returned by subsequent calls to this method.
Writes a line of text to the file and advances the file pointer.
93 |BytesWritten := FileObj.WriteLine(String)94 |
Type: String
99 |If blank or omitted, an empty line will be written. Otherwise, specify the string to write, which is always followed by `n
or `r`n
, depending on the EOL flags used to open the file.
Type: Integer
104 |This method returns the number of bytes (not characters) that were written.
105 |Reads a number from the file and advances the file pointer.
109 |Num := FileObj.ReadNumType()
110 | NumType is either UInt, Int, Int64, Short, UShort, Char, UChar, Double, or Float. These type names have the same meanings as with DllCall.
111 |Type: Integer, Float or String (empty)
113 |On success, this method returns a number. On failure, it returns an empty string.
114 |If the number of bytes read is non-zero but less than the size of NumType, the missing bytes are assumed to be zero.
116 |Writes a number to the file and advances the file pointer.
120 |BytesWritten := FileObj.WriteNumType(Num)
121 | NumType is either UInt, Int, Int64, Short, UShort, Char, UChar, Double, or Float. These type names have the same meanings as with DllCall.
122 |Type: Integer
131 |This method returns the number of bytes that were written. For example, FileObj.WriteUInt(42)
returns 4 if successful.
Reads raw binary data from the file into memory and advances the file pointer.
136 |BytesRead := FileObj.RawRead(Buffer , Bytes)137 |
The Buffer-like object or memory address which will receive the data.
143 |Reading into a Buffer is recommended. If Bytes is omitted, it defaults to the size of the buffer. An exception is thrown if Bytes exceeds the size of the buffer.
144 |If a memory address is passed, Bytes must also be specified.
145 |Type: Integer
149 |The maximum number of bytes to read. This is optional when Buffer is an object; otherwise, it is required.
150 |Type: Integer
154 |This method returns the number of bytes that were read.
155 |Writes raw binary data to the file and advances the file pointer.
159 |BytesWritten := FileObj.RawWrite(Data , Bytes)160 |
Type: Object, String or Integer
165 |A Buffer-like object or string containing binary data, or a memory address. If an object or string is specified, Bytes is optional and defaults to the size of the buffer or string. Otherwise, Bytes must also be specified.
166 |Type: Integer
170 |The number of bytes to write. This is optional when Data is an object or string; otherwise, it is required.
171 |Type: Integer
175 |This method returns the number of bytes that were written.
176 |Moves the file pointer.
180 |IsMoved := FileObj.Seek(Distance , Origin)181 |
Type: Integer
186 |Distance to move, in bytes. Lower values are closer to the beginning of the file.
187 |Type: Integer
191 |If omitted, it defaults to 2 when Distance is negative and 0 otherwise. Otherwise, specify one of the following numbers to indicate the starting point for the file pointer move:
192 |Type: Integer (boolean)
201 |On success, this method returns 1 (true). On failure, it returns 0 (false).
202 |This method is equivalent to FileObj.Pos := Distance
, if Distance is not negative and Origin is omitted or 0 (SEEK_SET).
Closes the file, flushes any data in the cache to disk and releases the share locks.
208 |FileObj.Close()
209 | Although the file is closed automatically when the object is freed, it is recommended to close the file as soon as possible.
Retrieves or sets the position of the file pointer.
215 |CurrentPos := FileObj.Pos
216 | FileObj.Pos := NewPos
217 | CurrentPos and NewPos are a byte offset from the beginning of the file, where 0 is the first byte. When data is written to or read from the file, the file pointer automatically moves to the next byte after that data.
218 |This property is equivalent to FileObj.Seek(NewPos)
.
Retrieves or sets the size of the file.
223 |CurrentSize := FileObj.Length
224 | FileObj.Length := NewSize
225 | CurrentSize and NewSize are the size of the file, in bytes.
226 |This property should be used only with an actual file. If the File object was created from a handle to a pipe, it may return the amount of data currently available in the pipe's internal buffer, but this behaviour is not guaranteed.
Retrieves a non-zero number if the file pointer has reached the end of the file, otherwise zero.
230 |IsAtEOF := FileObj.AtEOF
231 | This property should be used only with an actual file. If the File object was created from a handle to a non-seeking device such as a console buffer or pipe, the returned value may not be meaningful, as such devices do not logically have an "end of file".
Retrieves or sets the text encoding used by this file object.
235 |CurrentEncoding := FileObj.Encoding
236 | FileObj.Encoding := NewEncoding
237 | NewEncoding may be a numeric code page identifier (see Microsoft Docs) or one of the following strings.
238 |CurrentEncoding is one of the following strings:
239 |UTF-8
: Unicode UTF-8, equivalent to CP65001.UTF-16
: Unicode UTF-16 with little endian byte order, equivalent to CP1200.CPnnn
: a code page with numeric identifier nnn.CurrentEncoding is never a value with the -RAW
suffix, regardless of how the file was opened or whether it contains a byte order mark (BOM). Setting NewEncoding never causes a BOM to be added or removed, as the BOM is normally written to the file when it is first created.
Setting NewEncoding to UTF-8-RAW
or UTF-16-RAW
is valid, but the -RAW
suffix is ignored. This only applies to FileObj.Encoding
, not FileOpen.
Returns a system file handle, intended for use with DllCall. See CreateFile.
250 |Handle := FileObj.Handle
251 | File objects internally buffer reads or writes. If data has been written into the object's internal buffer, it is committed to disk before the handle is returned. If the buffer contains data read from file, it is discarded and the actual file pointer is reset to the logical position indicated by the Pos property.
Writes text or binary data to the end of a file (first creating the file, if necessary).
16 | 17 |FileAppend Text , Filename, Options18 |
The text or raw binary data to append to the file. Text may include linefeed characters (`n) to start new lines. In addition, a single long line can be broken up into several shorter ones by means of a continuation section.
25 |A Buffer-like object may be passed to append raw binary data. If a file is created, a byte order mark (BOM) is written only if "UTF-8" or "UTF-16" has been specified within Options. The default encoding is ignored and the data contained by the object is written as-is, regardless of Options. Any object which implements Ptr and Size properties may be used.
26 |Type: String
31 |If omitted, the output file of the innermost enclosing file-reading loop will be used (if available). Otherwise, specify the name of the file to be appended, which is assumed to be in A_WorkingDir if an absolute path isn't specified. The destination directory must already exist.
32 |Standard Output (stdout): Specifying an asterisk (*) for Filename causes Text to be sent to standard output (stdout). Such text can be redirected to a file, piped to another EXE, or captured by fancy text editors. For example, the following would be valid if typed at a command prompt:
33 |"%ProgramFiles%\AutoHotkey\AutoHotkey.exe" "My Script.ahk" >"Error Log.txt"34 |
However, text sent to stdout will not appear at the command prompt it was launched from. This can be worked around by 1) compiling the script with the Ahk2Exe ConsoleApp directive, or 2) piping a script's output to another command or program. For example:
35 |"%ProgramFiles%\AutoHotkey\AutoHotkey.exe" "My Script.ahk" |more36 |
For /F "tokens=*" %L in ('""%ProgramFiles%\AutoHotkey\AutoHotkey.exe" "My Script .ahk""') do @Echo %L37 |
Specifying two asterisks (**) for Filename causes Text to be sent to the standard error stream (stderr).
38 |Type: String
43 |Zero or more of the following strings. Separate each option from the next with a single space or tab. For example: "`n UTF-8"
Encoding: Specify any of the encoding names accepted by FileEncoding (excluding the empty string) to use that encoding if the file lacks a UTF-8 or UTF-16 byte order mark. If omitted, it defaults to A_FileEncoding (unless Text is an object, in which case no byte order mark is written).
45 |RAW: Specify the word RAW (case-insensitive) to write the exact bytes contained by Text to the file as-is, without any conversion. This option overrides any previously specified encoding and vice versa. If Text is not an object, the data size is always a multiple of 2 bytes due to the use of UTF-16 strings.
46 |`n (a linefeed character): Inserts a carriage return (`r) before each linefeed (`n) if one is not already present. In other words, it translates from `n to `r`n. This translation typically does not affect performance. If this option is not used, line endings within Text are not changed.
47 |An OSError is thrown on failure.
53 |A_LastError is set to the result of the operating system's GetLastError() function.
54 | 55 |To overwrite an existing file, delete it with FileDelete prior to using FileAppend.
57 |The target file is automatically closed after the text is appended (except when FileAppend is used in its single-parameter mode inside a file-reading/writing loop).
58 |FileOpen in append mode provides more control than FileAppend and allows the file to be kept open rather than opening and closing it each time. Once a file is opened in append mode, use FileObj.Write(Str)
to append the string. File objects also support binary I/O via RawWrite/RawRead or WriteNum/ReadNum.
FileEncoding, FileOpen/File Object, FileRead, file-reading loop, IniWrite, FileDelete, OutputDebug, continuation sections
61 |Creates a file, if necessary, and appends a line.
64 |FileAppend "Another line.`n", "C:\My Documents\Test.txt"65 |
Use a continuation section to enhance readability and maintainability.
69 |FileAppend " 70 | ( 71 | A line of text. 72 | By default, the hard carriage return (Enter) between the previous line and this one will be written to the file. 73 | This line is indented with a tab; by default, that tab will also be written to the file. 74 | )", A_Desktop "\My File.txt"75 |
Demonstrates how to automate FTP uploading using the operating system's built-in FTP command.
79 |FTPCommandFile := A_ScriptDir "\FTPCommands.txt" 80 | FTPLogFile := A_ScriptDir "\FTPLog.txt" 81 | try FileDelete FTPCommandFile ; In case previous run was terminated prematurely. 82 | 83 | FileAppend 84 | ( 85 | "open host.domain.com 86 | username 87 | password 88 | binary 89 | cd htdocs 90 | put " VarContainingNameOfTargetFile " 91 | delete SomeOtherFile.htm 92 | rename OldFileName.htm NewFileName.htm 93 | ls -l 94 | quit" 95 | ), FTPCommandFile 96 | 97 | RunWait Format('{1} /c ftp.exe -s:"{2}" >"{3}"', A_ComSpec, FTPCommandFile, FTPLogFile) 98 | FileDelete FTPCommandFile ; Delete for security reasons. 99 | Run FTPLogFile ; Display the log for review.100 |
Copies one or more files.
16 | 17 |FileCopy SourcePattern, DestPattern , Overwrite18 |
Type: String
24 |The name of a single file or folder, or a wildcard pattern such as "C:\Temp\*.tmp"
. SourcePattern is assumed to be in A_WorkingDir if an absolute path isn't specified.
Both asterisks (*
) and question marks (?
) are supported as wildcards. *
matches zero or more characters and ?
matches any single character. Usage examples:
*.*
or *
matches all files.*.htm
matches files with the extension .htm, .html, etc.*.
matches files without an extension.log?.txt
matches e.g. log1.txt but not log10.txt.*report*
matches any filename containing the word "report".Type: String
38 |The name or pattern of the destination, which is assumed to be in A_WorkingDir if an absolute path isn't specified.
39 |If present, the first asterisk (*
) in the filename is replaced with the source filename excluding its extension, while the first asterisk after the last full stop (.
) is replaced with the source file's extension. If an asterisk is present but the extension is omitted, the source file's extension is used.
To perform a simple copy -- retaining the existing file name(s) -- specify only the folder name as shown in these mostly equivalent examples:
41 |FileCopy "C:\*.txt", "C:\My Folder"42 |
FileCopy "C:\*.txt", "C:\My Folder\*.*"43 |
The destination directory must already exist. If My Folder does not exist, the first example above will use "My Folder" as the target filename, while the second example will copy no files.
44 |Type: Integer
49 |If omitted, it defaults to 0. Otherwise, specify one of the following numbers to indicate whether to overwrite files if they already exist:
50 |0: Do not overwrite existing files. The operation will fail and have no effect if DestPattern already exists as a file or directory.
51 |1: Overwrite existing files. However, any files or subfolders inside DestPattern that do not have a counterpart in SourcePattern will not be deleted.
52 |Other values are reserved for future use.
53 |An Error is thrown if any files failed to be copied, with its Extra property set to the number of failures. If no files were found, an error is thrown only if SourcePattern lacks the wildcards *
and ?
. In other words, copying a wildcard pattern such as "*.txt"
is considered a success when it does not match any files.
Unlike FileMove, copying a file onto itself is always counted as an error, even if the overwrite mode is in effect.
60 |If files were found, A_LastError is set to 0 (zero) or the result of the operating system's GetLastError() function immediately after the last failure. Otherwise A_LastError contains an error code that might indicate why no files were found.
61 | 62 |FileCopy copies files only. To instead copy the contents of a folder (all its files and subfolders), see the examples section below. To copy a single folder (including its subfolders), use DirCopy.
64 |The operation will continue even if error(s) are encountered.
65 |FileMove, DirCopy, DirMove, FileDelete
67 |Makes a copy but keep the original file name.
70 |FileCopy "C:\My Documents\List1.txt", "D:\Main Backup\"71 |
Copies a file into the same directory by providing a new name.
75 |FileCopy "C:\My File.txt", "C:\My File New.txt"76 |
Copies text files to a new location and gives them a new extension.
80 |FileCopy "C:\Folder1\*.txt", "D:\New Folder\*.bkp"81 |
Copies all files and folders inside a folder to a different folder.
85 |ErrorCount := CopyFilesAndFolders("C:\My Folder\*.*", "D:\Folder to receive all files & folders") 86 | if ErrorCount != 0 87 | MsgBox ErrorCount " files/folders could not be copied." 88 | 89 | CopyFilesAndFolders(SourcePattern, DestinationFolder, DoOverwrite := false) 90 | ; Copies all files and folders matching SourcePattern into the folder named DestinationFolder and 91 | ; returns the number of files/folders that could not be copied. 92 | { 93 | ErrorCount := 0 94 | ; First copy all the files (but not the folders): 95 | try 96 | FileCopy SourcePattern, DestinationFolder, DoOverwrite 97 | catch as Err 98 | ErrorCount := Err.Extra 99 | ; Now copy all the folders: 100 | Loop Files, SourcePattern, "D" ; D means "retrieve folders only". 101 | { 102 | try 103 | DirCopy A_LoopFilePath, DestinationFolder "\" A_LoopFileName, DoOverwrite 104 | catch 105 | { 106 | ErrorCount += 1 107 | ; Report each problem folder by name. 108 | MsgBox "Could not copy " A_LoopFilePath " into " DestinationFolder 109 | } 110 | } 111 | return ErrorCount 112 | }113 |
Creates a shortcut (.lnk) file.
16 | 17 |FileCreateShortcut Target, LinkFile , WorkingDir, Args, Description, IconFile, ShortcutKey, IconNumber, RunState18 |
Type: String
24 |Name of the file that the shortcut refers to, which should include an absolute path unless the file is integrated with the system (e.g. Notepad.exe). The file does not have to exist at the time the shortcut is created; however, if it does not, some systems might alter the path in unexpected ways.
25 |Type: String
30 |Name of the shortcut file to be created, which is assumed to be in A_WorkingDir if an absolute path isn't specified. Be sure to include the .lnk extension. The destination directory must already exist. If the file already exists, it will be overwritten.
31 |Type: String
36 |If blank or omitted, LinkFile will have a blank "Start in" field and the system will provide a default working directory when the shortcut is launched. Otherwise, specify the directory that will become Target's current working directory when the shortcut is launched.
37 |Type: String
42 |If blank or omitted, Target will be launched without parameters. Otherwise, specify the parameters that will be passed to Target when it is launched. Separate parameters with spaces. If a parameter contains spaces, enclose it in double quotes.
43 |Type: String
48 |If blank or omitted, LinkFile will have no description. Otherwise, specify comments that describe the shortcut (used by the OS to display a tooltip, etc.)
49 |Type: String
54 |If blank or omitted, LinkFile will have Target's icon. Otherwise, specify the full path and name of the icon to be displayed for LinkFile. It must either be an .ICO file or the very first icon of an EXE or DLL file.
55 |Type: String
60 |If blank or omitted, LinkFile will have no shortcut key. Otherwise, specify a single letter, number, or the name of a single key from the key list (mouse buttons and other non-standard keys might not be supported). Do not include modifier symbols. Currently, all shortcut keys are created as Ctrl+Alt shortcuts. For example, if the letter B is specified for this parameter, the shortcut key will be Ctrl+Alt+B.
61 |Type: Integer
66 |If omitted, it defaults to 1. Otherwise, specify the number of the icon to be used in IconFile. For example, 2 is the second icon.
67 |Type: Integer
72 |If omitted, it defaults to 1. Otherwise, specify one of the following digits to launch Target minimized or maximized:
73 |An exception is thrown on failure.
83 | 84 |Target might not need to include a path if the target file resides in one of the folders listed in the system's PATH environment variable.
86 |The shortcut key (ShortcutKey) of a newly created shortcut will have no effect unless the shortcut file resides on the desktop or somewhere in the Start Menu. If the shortcut key you choose is already in use, your new shortcut takes precedence.
87 |An alternative way to create a shortcut to a URL is the following example, which creates a special URL shortcut. Change the first two parameters to suit your preferences:
88 |IniWrite "https://www.google.com", "C:\My Shortcut.url", "InternetShortcut", "URL"89 |
The following may be optionally added to assign an icon to the above:
90 |IniWrite <IconFile>, "C:\My Shortcut.url", "InternetShortcut", "IconFile" 91 | IniWrite 0, "C:\My Shortcut.url", "InternetShortcut", "IconIndex"92 |
In the above, replace 0
with the index of the icon (0 is used for the first icon) and replace <IconFile>
with a URL, EXE, DLL, or ICO file. Examples: "C:\Icons.dll"
, "C:\App.exe"
, "https://www.somedomain.com/ShortcutIcon.ico"
The operating system will treat a .URL file created by the above as a real shortcut even though it is a plain text file rather than a .LNK file.
94 |The letter "i" in the last parameter makes the shortcut key be Ctrl+Alt+I.
99 |FileCreateShortcut "Notepad.exe", A_Desktop "\My Shortcut.lnk", "C:\", A_ScriptFullPath, "My Description", "C:\My Icon.ico", "i"100 |
Deletes one or more files permanently.
16 | 17 |FileDelete FilePattern
18 | Type: String
24 |The name of a single file or a wildcard pattern such as "C:\Temp\*.tmp"
. FilePattern is assumed to be in A_WorkingDir if an absolute path isn't specified.
Both asterisks (*
) and question marks (?
) are supported as wildcards. *
matches zero or more characters and ?
matches any single character. Usage examples:
*.*
or *
matches all files.*.htm
matches files with the extension .htm, .html, etc.*.
matches files without an extension.log?.txt
matches e.g. log1.txt but not log10.txt.*report*
matches any filename containing the word "report".To remove an entire folder, along with all its sub-folders and files, use DirDelete.
35 |An Error is thrown if any files failed to be deleted, with its Extra property set to the number of failures. Deleting a wildcard pattern such as "*.tmp"
is considered a success even if it does not match any files.
If files were found, A_LastError is set to 0 (zero) or the result of the operating system's GetLastError() function immediately after the last failure. Otherwise A_LastError contains an error code that might indicate why no files were found.
42 | 43 |To send a file to the recycle bin, use the FileRecycle function.
45 |To delete a read-only file, first remove the read-only attribute. For example: FileSetAttrib "-R", "C:\My File.txt"
.
FileRecycle, DirDelete, FileCopy, FileMove
48 |Sets the default encoding for FileRead, Loop Read, FileAppend, and FileOpen.
16 | 17 |FileEncoding Encoding
18 |
19 | Specify one of the following values:
25 |CP0 or empty string: The system default ANSI code page. See remarks below.
26 |UTF-8: Unicode UTF-8, equivalent to CP65001.
27 |UTF-8-RAW: As above, but no byte order mark is written when a new file is created.
28 |UTF-16: Unicode UTF-16 with little endian byte order, equivalent to CP1200.
29 |UTF-16-RAW: As above, but no byte order mark is written when a new file is created.
30 |CPnnn: A code page with numeric identifier nnn. See Code Page Identifiers.
31 |nnn: A numeric code page identifier.
32 |Type: String
37 |This function returns the previous setting.
38 | 39 |If FileEncoding is not used, the default encoding is CP0.
41 |CP0 does not universally identify a single code page; rather, it corresponds to the system default ANSI code page, which depends on the system locale or "language for non-Unicode programs" system setting. To get the actual code page number, call DllCall("GetACP")
.
The built-in variable A_FileEncoding contains the current setting.
43 |Every newly launched thread (such as a hotkey, custom menu item, or timed subroutine) starts off fresh with the default setting for this function. That default may be changed by using this function during script startup.
44 |The default encoding is not used if a UTF-8 or UTF-16 byte order mark is present in the file, unless the file is being opened with write-only access (i.e. the previous contents of the file are being discarded).
45 | 46 |FileOpen, StrGet, StrPut, Reading Binary Data
48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /docs/lib/FileExist.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Checks for the existence of a file or folder and returns its attributes.
16 | 17 |AttributeString := FileExist(FilePattern)
18 | Type: String
24 |The name of a single file or folder, or a wildcard pattern such as "C:\Temp\*.tmp"
. FilePattern is assumed to be in A_WorkingDir if an absolute path isn't specified.
Both asterisks (*
) and question marks (?
) are supported as wildcards. *
matches zero or more characters and ?
matches any single character. Usage examples:
*.*
or *
matches all files.*.htm
matches files with the extension .htm, .html, etc.*.
matches files without an extension.log?.txt
matches e.g. log1.txt but not log10.txt.*report*
matches any filename containing the word "report".Type: String
39 |This function returns the attributes of the first matching file or folder. This string is a subset of RASHNDOCTL
, where each letter means the following:
If the file has no attributes (rare), "X" is returned. If no file or folder is found, an empty string is returned.
53 | 54 |Note that a wildcard check like InStr(FileExist("MyFolder\*"), "D")
with MyFolder containing files and subfolders will only tell you whether the first matching file is a folder, not whether a folder exists. To check for the latter, use DirExist, e.g. DirExist("MyFolder\*")
.
Unlike FileGetAttrib, FileExist supports wildcard patterns and always returns a non-empty value if a matching file exists.
57 |Since an empty string is seen as "false", the function's return value can always be used as a quasi-boolean value. For example, the statement if FileExist("C:\My File.txt")
would be true if the file exists and false otherwise.
Since FilePattern may contain wildcards, FileExist may be unsuitable for validating a file path which is to be used with another function or program. For example, FileExist("*.txt")
may return attributes even though "*.txt" is not a valid filename. In such cases, FileGetAttrib is preferred.
DirExist, FileGetAttrib, file loops
62 | 63 |Shows a message box if the D drive does exist.
66 |if FileExist("D:\") 67 | MsgBox "The drive exists."68 |
Shows a message box if at least one text file does exist in a directory.
72 |if FileExist("D:\Docs\*.txt") 73 | MsgBox "At least one .txt file exists."74 |
Shows a message box if a file does not exist.
78 |if not FileExist("C:\Temp\FlagFile.txt") 79 | MsgBox "The target file does not exist."80 |
Demonstrates how to check a file for a specific attribute.
84 |if InStr(FileExist("C:\My File.txt"), "H") 85 | MsgBox "The file is hidden."86 |
Reports whether a file or folder is read-only, hidden, etc.
16 | 17 |AttributeString := FileGetAttrib(Filename)18 | 19 |
Type: String
25 |If omitted, the current file of the innermost enclosing file loop will be used. Otherwise, specify the name of the target file, which is assumed to be in A_WorkingDir if an absolute path isn't specified. Unlike FileExist and DirExist, this must be a true filename, not a pattern.
26 |Type: String
32 |This function returns the attributes of the file or folder. This string is a subset of RASHNDOCTL
, where each letter means the following:
An OSError is thrown on failure.
48 |A_LastError is set to the result of the operating system's GetLastError() function.
49 | 50 |To check if a particular attribute is present in the retrieved string, see example #2 below.
52 |On a related note, to retrieve a file's 8.3 short name, follow this example:
53 |Loop Files, "C:\My Documents\Address List.txt" 54 | ShortPathName := A_LoopFileShortPath ; Will yield something similar to C:\MYDOCU~1\ADDRES~1.txt55 |
A similar method can be used to get the long name of an 8.3 short name.
56 | 57 |FileExist, DirExist, FileSetAttrib, FileGetTime, FileSetTime, FileGetSize, FileGetVersion, file loop
59 | 60 |Stores the attribute letters of a directory in OutputVar. Note that existing directories always have the attribute letter D.
63 |OutputVar := FileGetAttrib("C:\New Folder")64 |
Checks if the Hidden attribute is present in the retrieved string.
67 |if InStr(FileGetAttrib("C:\My File.txt"), "H") 68 | MsgBox "The file is hidden."69 |
Retrieves information about a shortcut (.lnk) file, such as its target file.
16 | 17 |FileGetShortcut LinkFile , &OutTarget, &OutDir, &OutArgs, &OutDescription, &OutIcon, &OutIconNum, &OutRunState18 |
Type: String
24 |Name of the shortcut file to be analyzed, which is assumed to be in A_WorkingDir if an absolute path isn't specified. Be sure to include the .lnk extension.
25 |Type: VarRef
30 |If omitted, the corresponding value will not be stored. Otherwise, specify a reference to the output variable in which to store the shortcut's target (not including any arguments it might have). For example: C:\WINDOWS\system32\notepad.exe
31 |Type: VarRef
36 |If omitted, the corresponding value will not be stored. Otherwise, specify a reference to the output variable in which to store the shortcut's working directory. For example: C:\My Documents. If environment variables such as %WinDir% are present in the string, one way to resolve them is via StrReplace. For example: OutDir := StrReplace(OutDir, "%WinDir%", A_WinDir)
Type: VarRef
42 |If omitted, the corresponding value will not be stored. Otherwise, specify a reference to the output variable in which to store the shortcut's parameters (blank if none).
43 |Type: VarRef
48 |If omitted, the corresponding value will not be stored. Otherwise, specify a reference to the output variable in which to store the shortcut's comments (blank if none).
49 |Type: VarRef
54 |If omitted, the corresponding value will not be stored. Otherwise, specify a reference to the output variable in which to store the filename of the shortcut's icon (blank if none).
55 |Type: VarRef
60 |If omitted, the corresponding value will not be stored. Otherwise, specify a reference to the output variable in which to store the shortcut's icon number within the icon file (blank if none). This value is most often 1, which means the first icon.
61 |Type: VarRef
66 |If omitted, the corresponding value will not be stored. Otherwise, specify a reference to the output variable in which to store the shortcut's initial launch state, which is one of the following digits:
67 |An OSError is thrown on failure.
78 | 79 |Any of the output variables may be omitted if the corresponding information is not needed.
81 |Allows the user to select an .lnk file to show its information.
86 |LinkFile := FileSelect(32,, "Pick a shortcut to analyze.", "Shortcuts (*.lnk)") 87 | if LinkFile = "" 88 | return 89 | FileGetShortcut LinkFile, &OutTarget, &OutDir, &OutArgs, &OutDesc, &OutIcon, &OutIconNum, &OutRunState 90 | MsgBox OutTarget "`n" OutDir "`n" OutArgs "`n" OutDesc "`n" OutIcon "`n" OutIconNum "`n" OutRunState 91 |92 |
Retrieves the size of a file.
16 | 17 |Size := FileGetSize(Filename, Units)18 |
Type: String
24 |If omitted, the current file of the innermost enclosing file loop will be used. Otherwise, specify the name of the target file, which is assumed to be in A_WorkingDir if an absolute path isn't specified.
25 |Type: String
30 |If blank or omitted, it defaults to B. Otherwise, specify one of the following letters to cause the result to be returned in specific units:
31 |Type: Integer
42 |This function returns the size of the specified file (rounded down to the nearest whole number).
43 | 44 |An OSError is thrown on failure.
46 |A_LastError is set to the result of the operating system's GetLastError() function.
47 | 48 |Files of any size are supported, even those over 4 gigabytes, and even if Units is bytes.
50 |If the target file is a directory, the size will be reported as whatever the OS believes it to be (probably zero in all cases).
51 |To calculate the size of folder, including all its files, follow this example:
52 |FolderSize := 0 53 | WhichFolder := DirSelect() ; Ask the user to pick a folder. 54 | Loop Files, WhichFolder "\*.*", "R" 55 | FolderSize += A_LoopFileSize 56 | MsgBox "Size of " WhichFolder " is " FolderSize " bytes."57 |
FileGetAttrib, FileSetAttrib, FileGetTime, FileSetTime, FileGetVersion, file loop
59 |Retrieves the size in bytes and stores it in Size.
62 |Size := FileGetSize("C:\My Documents\test.doc")63 |
Retrieves the size in kilobytes and stores it in Size.
67 |Size := FileGetSize("C:\My Documents\test.doc", "K")68 |
Retrieves the datetime stamp of a file or folder.
16 | 17 |Timestamp := FileGetTime(Filename, WhichTime)18 |
Type: String
24 |If omitted, the current file of the innermost enclosing file loop will be used. Otherwise, specify the name of the target file or folder, which is assumed to be in A_WorkingDir if an absolute path isn't specified.
25 |Type: String
30 |If blank or omitted, it defaults to M. Otherwise, specify one of the following letters to set which timestamp should be retrieved:
31 |Type: String
42 |This function returns a string of digits in the YYYYMMDDHH24MISS format. The time is your own local time, not UTC/GMT. This string should not be treated as a number, i.e. one should not perform math on it or compare it numerically.
43 | 44 |An OSError is thrown on failure.
46 |A_LastError is set to the result of the operating system's GetLastError() function.
47 | 48 |See YYYYMMDDHH24MISS for an explanation of dates and times.
50 |FileSetTime, FormatTime, FileGetAttrib, FileSetAttrib, FileGetSize, FileGetVersion, file loop, DateAdd, DateDiff
52 |Retrieves the modification time and stores it in Timestamp.
55 |Timestamp := FileGetTime("C:\My Documents\test.doc")56 |
Retrieves the creation time and stores it in Timestamp.
60 |Timestamp := FileGetTime("C:\My Documents\test.doc", "C")61 |
Retrieves the version of a file.
16 | 17 |Version := FileGetVersion(Filename)18 |
Type: String
24 |If omitted, the current file of the innermost enclosing file loop will be used. Otherwise, specify the name of the target file. If a full path is not specified, this function uses the search sequence specified by the system LoadLibrary function.
25 |Type: String
31 |This function returns the version number of the specified file.
32 | 33 |An OSError is thrown on failure, such as if the file lacks version information.
35 |A_LastError is set to the result of the operating system's GetLastError() function.
36 | 37 |Most non-executable files (and even some EXEs) have no version, and thus an error will be thrown.
39 | 40 |FileGetAttrib, FileSetAttrib, FileGetTime, FileSetTime, FileGetSize, file loop
42 |Retrieves the version of a file and stores it in Version.
45 |Version := FileGetVersion("C:\My Application.exe")46 |
Retrieves the version of the file "AutoHotkey.exe" located in AutoHotkey's installation directory and stores it in Version.
50 |Version := FileGetVersion(A_ProgramFiles "\AutoHotkey\AutoHotkey.exe")51 |
Includes the specified file inside the compiled version of the script.
16 | 17 |FileInstall Source, Dest , Overwrite18 |
Type: String
24 |The name of a single file to be added to the compiled EXE. The file is assumed to be in (or relative to) the script's own directory if an absolute path isn't specified.
25 |This parameter must be a quoted literal string (not a variable or any other expression), and must be listed to the right of the function name FileInstall (that is, not on a continuation line beneath it).
26 |Type: String
31 |When Source is extracted from the EXE, this is the name of the file to be created. It is assumed to be in A_WorkingDir if an absolute path isn't specified. The destination directory must already exist.
32 |Type: Integer
37 |If omitted, it defaults to 0. Otherwise, specify one of the following numbers to indicate whether to overwrite files if they already exist:
38 |0: Do not overwrite existing files. The operation will fail and have no effect if Dest already exists.
39 |1: Overwrite existing files.
40 |Other values are reserved for future use.
41 |An exception is thrown on failure.
47 | 48 |Any case where the file cannot be written to the destination is considered failure. For example:
49 |When a call to this function is read by Ahk2Exe during compilation of the script, the file specified by Source is added to the resulting compiled script. Later, when the compiled script EXE runs and the call to FileInstall is executed, the file is extracted from the EXE and written to the location specified by Dest.
58 |Files added to a script are neither compressed nor encrypted during compilation, but the compiled script EXE can be compressed by using the appropriate option in Ahk2Exe.
59 |If this function is used in a normal (uncompiled) script, a simple file copy will be performed instead -- this helps the testing of scripts that will eventually be compiled. No action is taken if the full source and destination paths are equal, as attempting to copy the file to its current location would result in an error. The paths are compared with lstrcmpi after expansion with GetFullPathName.
60 | 61 |Includes a text file inside the compiled version of the script. Later, when the compiled script is executed, the included file is extracted to another location with another name. If a file with this name already exists at this location, it will be overwritten.
67 |FileInstall "My File.txt", A_Desktop "\Example File.txt", 168 |
Moves or renames one or more files.
16 | 17 |FileMove SourcePattern, DestPattern , Overwrite18 |
Type: String
24 |The name of a single file or a wildcard pattern such as "C:\Temp\*.tmp"
. SourcePattern is assumed to be in A_WorkingDir if an absolute path isn't specified.
Both asterisks (*
) and question marks (?
) are supported as wildcards. *
matches zero or more characters and ?
matches any single character. Usage examples:
*.*
or *
matches all files.*.htm
matches files with the extension .htm, .html, etc.*.
matches files without an extension.log?.txt
matches e.g. log1.txt but not log10.txt.*report*
matches any filename containing the word "report".Type: String
38 |The name or pattern of the destination, which is assumed to be in A_WorkingDir if an absolute path isn't specified.
39 |If present, the first asterisk (*
) in the filename is replaced with the source filename excluding its extension, while the first asterisk after the last full stop (.
) is replaced with the source file's extension. If an asterisk is present but the extension is omitted, the source file's extension is used.
To perform a simple move -- retaining the existing file name(s) -- specify only the folder name as shown in these mostly equivalent examples:
41 |FileMove "C:\*.txt", "C:\My Folder"42 |
FileMove "C:\*.txt", "C:\My Folder\*.*"43 |
The destination directory must already exist. If My Folder does not exist, the first example above will use "My Folder" as the target filename, while the second example will move no files.
44 |Type: Integer
49 |If omitted, it defaults to 0. Otherwise, specify one of the following numbers to indicate whether to overwrite files if they already exist:
50 |0: Do not overwrite existing files. The operation will fail and have no effect if DestPattern already exists as a file or directory.
51 |1: Overwrite existing files. However, any files or subfolders inside DestPattern that do not have a counterpart in SourcePattern will not be deleted.
52 |Other values are reserved for future use.
53 |An Error is thrown if any files failed to be moved, with its Extra property set to the number of failures. If no files were found, an exception is thrown only if SourcePattern lacks the wildcards *
and ?
. In other words, moving a wildcard pattern such as "*.txt"
is considered a success when it does not match any files.
Unlike FileCopy, moving a file onto itself is always considered successful, even if the overwrite mode is not in effect.
60 |If files were found, A_LastError is set to 0 (zero) or the result of the operating system's GetLastError() function immediately after the last failure. Otherwise A_LastError contains an error code that might indicate why no files were found.
61 | 62 |FileMove moves files only. To instead move the contents of a folder (all its files and subfolders), see the examples section below. To move or rename a single folder, use DirMove.
64 |The operation will continue even if error(s) are encountered.
65 |Although this function is capable of moving files to a different volume, the operation will take longer than a same-volume move. This is because a same-volume move is similar to a rename, and therefore much faster.
66 |FileCopy, DirCopy, DirMove, FileDelete
68 |Moves a file without renaming it.
71 |FileMove "C:\My Documents\List1.txt", "D:\Main Backup\"72 |
Moves text files to a new location and gives them a new extension.
81 |FileMove "C:\Folder1\*.txt", "D:\New Folder\*.bkp"82 |
Moves all files and folders inside a folder to a different folder.
86 |ErrorCount := MoveFilesAndFolders("C:\My Folder\*.*", "D:\Folder to receive all files & folders") 87 | if ErrorCount != 0 88 | MsgBox ErrorCount " files/folders could not be moved." 89 | 90 | MoveFilesAndFolders(SourcePattern, DestinationFolder, DoOverwrite := false) 91 | ; Moves all files and folders matching SourcePattern into the folder named DestinationFolder and 92 | ; returns the number of files/folders that could not be moved. 93 | { 94 | ErrorCount := 0 95 | if DoOverwrite = 1 96 | DoOverwrite := 2 ; See DirMove for description of mode 2 vs. 1. 97 | ; First move all the files (but not the folders): 98 | try 99 | FileMove SourcePattern, DestinationFolder, DoOverwrite 100 | catch as Err 101 | ErrorCount := Err.Extra 102 | ; Now move all the folders: 103 | Loop Files, SourcePattern, "D" ; D means "retrieve folders only". 104 | { 105 | try 106 | DirMove A_LoopFilePath, DestinationFolder "\" A_LoopFileName, DoOverwrite 107 | catch 108 | { 109 | ErrorCount += 1 110 | ; Report each problem folder by name. 111 | MsgBox "Could not move " A_LoopFilePath " into " DestinationFolder 112 | } 113 | } 114 | return ErrorCount 115 | }116 |
Opens a file to read specific content from it and/or to write new content into it.
21 |FileObj := FileOpen(Filename, Flags , Encoding)22 | 23 |
Type: String
29 |The path of the file to open, which is assumed to be in A_WorkingDir if an absolute path isn't specified.
30 |Specify an asterisk (or two) as shown below to open the standard input/output/error stream:
31 |32 | FileOpen("*", "r") ; for stdin 33 | FileOpen("*", "w") ; for stdout 34 | FileOpen("**", "w") ; for stderr35 |
Either a string of characters indicating the desired access mode followed by other options (with optional spaces or tabs in between); or a combination (sum) of numeric flags. Supported values are described in the tables below.
41 |If omitted, the default encoding (as set by FileEncoding or CP0 otherwise) will be used. If blank, it defaults to CP0 (the system default ANSI code page). Otherwise, specify the encoding or code page to use for text I/O, e.g. "UTF-8"
, "UTF-16"
, "CP936"
or 936
.
If the file contains a UTF-8 or UTF-16 byte order mark (BOM), or if the h
(handle) flag is used, this parameter and the default encoding will be ignored, unless the file is being opened with write-only access (i.e. the previous contents of the file are being discarded).
Flag | 58 |Dec | 59 |Hex | 60 |Description | 61 |
---|---|---|---|
r | 64 |0 | 65 |0x0 | 66 |Read: Fails if the file doesn't exist. | 67 |
w | 70 |1 | 71 |0x1 | 72 |Write: Creates a new file, overwriting any existing file. | 73 |
a | 76 |2 | 77 |0x2 | 78 |Append: Creates a new file if the file didn't exist, otherwise moves the file pointer to the end of the file. | 79 |
rw | 82 |3 | 83 |0x3 | 84 |Read/Write: Creates a new file if the file didn't exist. | 85 |
h | 88 |89 | | 90 | | Indicates that Filename is a file handle to wrap in an object. Sharing mode flags are ignored and the file or stream represented by the handle is not checked for a byte order mark. The file handle is not closed automatically when the file object is destroyed and calling File.Close has no effect. Note that File.Seek, File.Pos and File.Length should not be used if Filename is a handle to a nonseeking device such as a pipe or a communications device. | 91 |
Flag | 98 |Dec | 99 |Hex | 100 |Description | 101 |
---|---|---|---|
-rwd | 104 |105 | | 106 | | Locks the file for read, write and/or delete access. Any combination of r , w and d may be used. Specifying - is the same as specifying -rwd . If omitted entirely, the default is to share all access. |
107 |
110 | | 0 | 111 |0x0 | 112 |If Flags is numeric, the absence of sharing mode flags causes the file to be locked. | 113 |
116 | | 256 | 117 |0x100 | 118 |Shares read access. | 119 |
122 | | 512 | 123 |0x200 | 124 |Shares write access. | 125 |
128 | | 1024 | 129 |0x400 | 130 |Shares delete access. | 131 |
Flag | 138 |Dec | 139 |Hex | 140 |Description | 141 |
---|---|---|---|
`n | 144 |4 | 145 |0x4 | 146 |Replace `r`n with `n when reading and `n with `r`n when writing. |
147 |
`r | 150 |8 | 151 |0x8 | 152 |Replace standalone `r with `n when reading. |
153 |
Type: Object
158 |The return value is a new File object encapsulating the open handle to the file. Use the methods and properties of this object to access the file's contents.
159 | 160 |If the file cannot be opened, an OSError is thrown.
162 | 163 |File.ReadLine always supports `n
, `r`n
and `r
as line endings and does not include them in its return value, regardless of whether the `r
or `n
options are used. The options only affect translation of line endings within the text returned by File.Read or written by File.Write or File.WriteLine.
When a UTF-8 or UTF-16 file is created, a byte order mark (BOM) is written to the file unless Encoding or the default encoding (as set by FileEncoding) is "UTF-8-RAW"
or "UTF-16-RAW"
.
When a file containing a UTF-8 or UTF-16 byte order mark (BOM) is opened with read access, the BOM is excluded from the output by positioning the file pointer after it. Therefore, File.Pos may report 3 or 2 immediately after opening the file.
167 |If necessary, the write buffer can be flushed using File.Read such as FileObj.Read(0)
. See example #3 below.
FileEncoding, File Object, FileRead
171 | 172 |Writes some text to a file then reads it back into memory (it provides the same functionality as this DllCall example).
176 |FileName := FileSelect("S16",, "Create a new file:") 177 | if (FileName = "") 178 | return 179 | try 180 | FileObj := FileOpen(FileName, "w") 181 | catch as Err 182 | { 183 | MsgBox "Can't open '" FileName "' for writing." 184 | . "`n`n" Type(Err) ": " Err.Message 185 | return 186 | } 187 | 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. 188 | FileObj.Write(TestString) 189 | FileObj.Close() 190 | 191 | ; Now that the file was written, read its contents back into memory. 192 | try 193 | FileObj := FileOpen(FileName, "r-d") ; read the file ("r"), share all access except for delete ("-d") 194 | catch as Err 195 | { 196 | MsgBox "Can't open '" FileName "' for reading." 197 | . "`n`n" Type(Err) ": " Err.Message 198 | return 199 | } 200 | CharsToRead := StrLen(TestString) 201 | TestString := FileObj.Read(CharsToRead) 202 | FileObj.Close() 203 | MsgBox "The following string was read from the file: " TestString204 |
Opens the script in read-only mode and read its first line.
208 |Script := FileOpen(A_ScriptFullPath, "r") 209 | MsgBox Script.ReadLine()210 |
Demonstrates the usage of the standard input/output streams.
214 |; Open a console window for this demonstration: 215 | DllCall("AllocConsole") 216 | ; Open the application's stdin/stdout streams. 217 | stdin := FileOpen("*", "r") 218 | stdout := FileOpen("*", "w") 219 | stdout.Write("Enter your query.`n\> ") 220 | stdout.Read(0) ; Flush the write buffer. 221 | query := RTrim(stdin.ReadLine(), "`n") 222 | stdout.WriteLine("Your query was '" query "'. Have a nice day.") 223 | stdout.Read(0) ; Flush the write buffer. 224 | Sleep 5000 225 |226 |
Retrieves the contents of a file.
16 | 17 |Text := FileRead(Filename , Options)18 |
Type: String
24 |The name of the file to read, which is assumed to be in A_WorkingDir if an absolute path isn't specified.
25 |Type: String
30 |Zero or more of the following strings. Separate each option from the next with a single space or tab. For example: "`n m5000 UTF-8"
Encoding: Specify any of the encoding names accepted by FileEncoding (excluding the empty string) to use that encoding if the file lacks a UTF-8 or UTF-16 byte order mark. If omitted, it defaults to A_FileEncoding.
32 |RAW: Specify the word RAW (case-insensitive) to read the file's content as raw binary data and return a Buffer object instead of a string. This option overrides any previously specified encoding and vice versa.
33 |m1024: If this option is omitted, the entire file is loaded unless there is insufficient memory, in which case an error message is shown and the thread exits (but Try can be used to avoid this). Otherwise, replace 1024 with a decimal or hexadecimal number of bytes. If the file is larger than this, only its leading part is loaded.
34 |Note: This might result in the last line ending in a naked carriage return (`r) rather than `r`n.
35 |`n (a linefeed character): Replaces any/all occurrences of carriage return & linefeed (`r`n) with linefeed (`n). However, this translation reduces performance and is usually not necessary. For example, text containing `r`n is already in the right format to be added to a Gui Edit control. The following parsing loop will work correctly regardless of whether each line ends in `r`n or just `n: Loop Parse, MyFileContents, "`n", "`r"
.
This function returns the contents of the specified file. The return value is a Buffer object if the RAW option is in effect and the file can be opened; otherwise, it is a string. If the file does not exist or cannot be opened for any other reason, an empty string is returned.
43 | 44 |An OSError is thrown if there was a problem opening or reading the file.
46 |A file greater than 4 GB in size will cause a MemoryError to be thrown unless the *m option is present, in which case the leading part of the file is loaded. A MemoryError will also be thrown if the program is unable to allocate enough memory to contain the requested amount of data.
47 |A_LastError is set to the result of the operating system's GetLastError() function.
48 | 49 |When the RAW
option is used, the return value is a Buffer object containing the raw, unmodified contents of the file. The object's Size property returns the number of bytes read. NumGet or StrGet can be used to retrieve data from the buffer. For example:
buf := FileRead(A_AhkPath, "RAW") 52 | if StrGet(buf, 2, "cp0") == "MZ" ; Looks like an executable file... 53 | { 54 | ; Read machine type from COFF file header. 55 | machine := NumGet(buf, NumGet(buf, 0x3C, "uint") + 4, "ushort") 56 | machine := machine=0x8664 ? "x64" : machine=0x014C ? "x86" : "unknown" 57 | ; Display machine type and file size. 58 | MsgBox "This " machine " executable is " buf.Size " bytes." 59 | } 60 | buf := ""61 |
This option is generally required for reading binary data because by default, any bytes read from file are interpreted as text and may be converted from the source file's encoding (as specified in the options or by A_FileEncoding) to the script's native encoding, UTF-16. If the data is not UTF-16 text, this conversion generally changes the data in undesired ways.
62 |For another demonstration of the RAW option, see ClipboardAll example #2.
63 |Finally, FileOpen and File.RawRead or File.ReadNum may be used to read binary data without first reading the entire file into memory.
64 | 65 |When the goal is to load all or a large part of a file into memory, FileRead performs much better than using a file-reading loop.
67 |If there is concern about using too much memory, check the file size beforehand with FileGetSize.
68 |FileOpen provides more advanced functionality than FileRead, such as reading or writing data at a specific location in the file without reading the entire file into memory. See File Object for a list of functions.
69 | 70 |FileEncoding, FileOpen/File Object, file-reading loop, FileGetSize, FileAppend, IniRead, Sort, Download
72 | 73 |Quickly sorts the contents of a file.
81 |82 | Contents := FileRead("C:\Address List.txt") 83 | Contents := Sort(Contents) 84 | FileDelete "C:\Address List (alphabetical).txt" 85 | FileAppend Contents, "C:\Address List (alphabetical).txt" 86 | Contents := "" ; Free the memory. 87 |88 |
Sends a file or directory to the recycle bin if possible, or permanently deletes it.
16 | 17 |FileRecycle FilePattern
18 | Type: String
24 |The name of a single file or a wildcard pattern such as "C:\Temp\*.tmp"
. FilePattern is assumed to be in A_WorkingDir if an absolute path isn't specified.
Both asterisks (*
) and question marks (?
) are supported as wildcards. *
matches zero or more characters and ?
matches any single character. Usage examples:
*.*
or *
matches all files.*.htm
matches files with the extension .htm, .html, etc.*.
matches files without an extension.log?.txt
matches e.g. log1.txt but not log10.txt.*report*
matches any filename containing the word "report".To recycle an entire directory, provide its name without a trailing backslash.
34 |An exception is thrown on failure.
40 | 41 |SHFileOperation is used to do the actual work. This function may permanently delete the file if it is too large to be recycled; also, a warning should be shown before this occurs.
43 |The file may be permanently deleted without warning if the file cannot be recycled for other reasons, such as:
44 |NukeOnDelete
registry value.FileRecycleEmpty, FileDelete, FileCopy, FileMove
50 |Sends all .tmp files in a directory to the recycle bin if possible.
53 |FileRecycle "C:\temp files\*.tmp"54 |
Empties the recycle bin.
16 | 17 |FileRecycleEmpty DriveLetter18 |
Type: String
24 |If omitted, the recycle bin for all drives is emptied. Otherwise, specify a drive letter such as "C:\"
.
An OSError is thrown on failure.
31 | 32 |FileRecycle, FileDelete, FileCopy, FileMove
34 |Displays a standard dialog that allows the user to open or save file(s).
17 | 18 |SelectedFile := FileSelect(Options, RootDir\Filename, Title, Filter)19 |
If blank or omitted, it defaults to zero, which is the same as having none of the options below. Otherwise, specify a number or one of the letters listed below, optionally followed by a number. For example, "M"
, 1
and "M1"
are all valid (but not equivalent).
D: Select Folder (Directory). Specify the letter D to allow the user to select a folder rather than a file. The dialog has most of the same features as when selecting a file, but does not support filters (Filter must be blank or omitted).
27 |M: Multi-select. Specify the letter M to allow the user to select more than one file via shift-click, control-click, or other means. In this case, the return value is an Array instead of a string. To extract the individual files, see the example at the bottom of this page.
28 |S: Save dialog. Specify the letter S to cause the dialog to always contain a Save button instead of an Open button.
29 |The following numbers can be used. To put more than one of them into effect, add them up. For example, to use 1 and 2, specify the number 3.
30 |1: File Must Exist
31 | 2: Path Must Exist
32 | 8: Prompt to Create New File
33 | 16: Prompt to Overwrite File
34 | 32: Shortcuts (.lnk files) are selected as-is rather than being resolved to their targets. This option also prevents navigation into a folder via a folder shortcut.
As the "Prompt to Overwrite" option is supported only by the Save dialog, specifying that option without the "Prompt to Create" option also puts the S option into effect. Similarly, the "Prompt to Create" option has no effect when the S option is present. Specifying the number 24 enables whichever type of prompt is supported by the dialog.
36 |Type: String
41 |If blank or omitted, the starting directory will be a default that might depend on the OS version (it will likely be the directory most recently selected by the user during a prior use of FileSelect). Otherwise, specify one or both of the following:
42 |RootDir: The root (starting) directory, which is assumed to be a subfolder in A_WorkingDir if an absolute path is not specified.
43 |Filename: The default filename to initially show in the dialog's edit field. Only the naked filename (with no path) will be shown. To ensure that the dialog is properly shown, ensure that no illegal characters are present (such as /<|:"
).
Examples:
45 |"C:\My Pictures\Default Image Name.gif" ; Both RootDir and Filename are present. 46 | "C:\My Pictures" ; Only RootDir is present. 47 | "My Pictures" ; Only RootDir is present, and it's relative to the current working directory. 48 | "My File" ; Only Filename is present (but if "My File" exists as a folder, it is assumed to be RootDir).49 |
Type: String
54 |If blank or omitted, it defaults to "Select File - " A_ScriptName
(i.e. the name of the current script), unless the "D" option is present, in which case the word "File" is replaced with "Folder". Otherwise, specify the title of the file-selection window.
Type: String
60 |If blank or omitted, the dialog will show all type of files and provide the "All Files (*.*)" option in the "Files of type" drop-down list.
61 |Otherwise, specify a string to indicate which types of files are shown by the dialog, e.g. "Documents (*.txt)"
. To include more than one file extension in the filter, separate them with semicolons, e.g. "Audio (*.wav; *.mp2; *.mp3)"
. In this case, the "Files of type" drop-down list has the specified string and "All Files (*.*)" as options.
This parameter must be blank or omitted if the "D" option is present.
63 |If multi-select is not in effect, this function returns the full path and name of the single file or folder chosen by the user, or an empty string if the user cancels the dialog.
70 |If the M option (multi-select) is in effect, this function returns an array of items, where each item is the full path and name of a single file. The example at the bottom of this page demonstrates how to extract the files one by one. If the user cancels the dialog, the array is empty (has zero items).
71 | 72 |A file-selection dialog usually looks like this:
74 | 75 |A GUI window may display a modal file-selection dialog by means of the +OwnDialogs option. A modal dialog prevents the user from interacting with the GUI window until the dialog is dismissed.
76 | 77 |DirSelect, MsgBox, InputBox, ToolTip, GUI, CLSID List, parsing loop, SplitPath
79 |Also, the operating system offers standard dialog boxes that prompt the user to pick a font, color, or icon. These dialogs can be displayed via DllCall in combination with comdlg32\ChooseFont, comdlg32\ChooseColor, or shell32\PickIconDlg. Search the forums for examples.
80 |Allows the user to select an existing .txt or .doc file.
83 |SelectedFile := FileSelect(3, , "Open a file", "Text Documents (*.txt; *.doc)") 84 | if SelectedFile = "" 85 | MsgBox "The dialog was canceled." 86 | else 87 | MsgBox "The following file was selected:`n" SelectedFile88 |
Allows the user to select multiple existing files.
92 |SelectedFiles := FileSelect("M3") ; M3 = Multiselect existing files. 93 | if SelectedFiles.Length = 0 94 | { 95 | MsgBox "The dialog was canceled." 96 | return 97 | } 98 | for FileName in SelectedFiles 99 | { 100 | Result := MsgBox("File #" A_Index " of " SelectedFiles.Length ":`n" FileName "`n`nContinue?",, "YN") 101 | if Result = "No" 102 | break 103 | } 104 |105 |
Allows the user to select a folder.
109 |110 | SelectedFolder := FileSelect("D", , "Select a folder") 111 | if SelectedFolder = "" 112 | MsgBox "The dialog was canceled." 113 | else 114 | MsgBox "The following folder was selected:`n" SelectedFolder 115 |116 |
Changes the attributes of one or more files or folders. Wildcards are supported.
16 | 17 |FileSetAttrib Attributes , FilePattern, Mode18 |
Type: String
24 |The attributes to change. For example, "+HA-R"
.
To easily turn on, turn off or toggle attributes, prefix one or more of the following attribute letters with a plus (+), minus (-) or caret (^) symbol, respectively:
26 |If no symbol precedes the attribute letters, the file's attributes are replaced with the given attributes. See example #5. To remove all attributes, use "N"
on its own.
Type: String
41 |If omitted, the current file of the innermost enclosing file loop will be used. Otherwise, specify the name of a single file or folder, or a wildcard pattern such as "C:\Temp\*.tmp"
. FilePattern is assumed to be in A_WorkingDir if an absolute path isn't specified.
Both asterisks (*
) and question marks (?
) are supported as wildcards. *
matches zero or more characters and ?
matches any single character. Usage examples:
*.*
or *
matches all files.*.htm
matches files with the extension .htm, .html, etc.*.
matches files without an extension.log?.txt
matches e.g. log1.txt but not log10.txt.*report*
matches any filename containing the word "report".Type: String
55 |If blank or omitted, only files are operated upon and subdirectories are not recursed into. Otherwise, specify one or more of the following letters:
56 |An Error is thrown if any files failed to be changed, with its Extra property set to the number of failures.
67 |If files were found, A_LastError is set to 0 (zero) or the result of the operating system's GetLastError() function immediately after the last failure. Otherwise A_LastError contains an error code that might indicate why no files were found.
68 | 69 |The compression state of files cannot be changed with this function.
71 | 72 |FileGetAttrib, FileGetTime, FileSetTime, FileGetSize, FileGetVersion, file loop
74 |Turns on the "read-only" and "hidden" attributes of all files and directories (subdirectories are not recursed into).
77 |FileSetAttrib "+RH", "C:\MyFiles\*.*", "DF" ; +RH is identical to +R+H78 |
Toggles the "hidden" attribute of a single directory.
82 |FileSetAttrib "^H", "C:\MyFiles"83 |
Turns off the "read-only" attribute and turns on the "archive" attribute of a single file.
87 |FileSetAttrib "-R+A", "C:\New Text File.txt"88 |
Recurses through all .ini files on the C drive and turns on their "archive" attribute.
92 |FileSetAttrib "+A", "C:\*.ini", "R"93 |
Copies the attributes of file2 to file1, i.e. it adds any attributes that file2 has and removes any attributes that file2 does not have.
97 |FileSetAttrib(FileGetAttrib(file2), file1)98 |
Changes the datetime stamp of one or more files or folders. Wildcards are supported.
16 | 17 |FileSetTime YYYYMMDDHH24MISS, FilePattern, WhichTime, Mode18 |
Type: String
24 |If blank or omitted, it defaults to the current local date and time. Otherwise, specify the time to use for the operation (see Remarks for the format). Years prior to 1601 are not supported.
25 |Type: String
30 |If omitted, the current file of the innermost enclosing file loop will be used. Otherwise, specify the name of a single file or folder, or a wildcard pattern such as "C:\Temp\*.tmp"
. FilePattern is assumed to be in A_WorkingDir if an absolute path isn't specified.
Both asterisks (*
) and question marks (?
) are supported as wildcards. *
matches zero or more characters and ?
matches any single character. Usage examples:
*.*
or *
matches all files.*.htm
matches files with the extension .htm, .html, etc.*.
matches files without an extension.log?.txt
matches e.g. log1.txt but not log10.txt.*report*
matches any filename containing the word "report".Type: String
44 |If blank or omitted, it defaults to M. Otherwise, specify one of the following letters to set which timestamp should be changed:
45 |Type: String
55 |If blank or omitted, only files are operated upon and subdirectories are not recursed into. Otherwise, specify one or more of the following letters:
56 |Note: If FilePattern is a single folder rather than a wildcard pattern, it will always be operated upon regardless of this setting.
62 |An Error is thrown if any files failed to be changed, with its Extra property set to the number of failures.
68 |If files were found, A_LastError is set to 0 (zero) or the result of the operating system's GetLastError() function immediately after the last failure. Otherwise A_LastError contains an error code that might indicate why no files were found.
69 | 70 |A file's last access time might not be as precise on FAT16 & FAT32 volumes as it is on NTFS volumes.
72 |The elements of the YYYYMMDDHH24MISS format are:
73 |Element | 76 |Description | 77 |
---|---|
YYYY | 80 |The 4-digit year | 81 |
MM | 84 |The 2-digit month (01-12) | 85 |
DD | 88 |The 2-digit day of the month (01-31) | 89 |
HH24 | 92 |The 2-digit hour in 24-hour format (00-23). For example, 09 is 9am and 21 is 9pm. | 93 |
MI | 96 |The 2-digit minutes (00-59) | 97 |
SS | 100 |The 2-digit seconds (00-59) | 101 |
If only a partial string is given for YYYYMMDDHH24MISS (e.g. 200403), any remaining element that has been omitted will be supplied with the following default values:
104 |The built-in variable A_Now contains the current local time in the above format. Similarly, A_NowUTC contains the current Coordinated Universal Time.
112 |Note: Date-time values can be compared, added to, or subtracted from via DateAdd and DateDiff. Also, it is best to not use greater-than or less-than to compare times unless they are both the same string length. This is because they would be compared as numbers; for example, 20040201 is always numerically less (but chronologically greater) than 200401010533. So instead use DateDiff to find out whether the amount of time between them is positive or negative.
113 |FileGetTime, FileGetAttrib, FileSetAttrib, FileGetSize, FileGetVersion, FormatTime, file loop, DateAdd, DateDiff
115 |Sets the modification time to the current time for all matching files.
118 |FileSetTime "", "C:\temp\*.txt"119 |
Sets the modification date (time will be midnight).
123 |FileSetTime 20040122, "C:\My Documents\test.doc"124 |
Sets the creation date. The time will be set to 4:55pm.
128 |FileSetTime 200401221655, "C:\My Documents\test.doc", "C"129 |
Changes the mod-date of all files that match a pattern. Any matching folders will also be changed due to the last parameter.
133 |FileSetTime 20040122165500, "C:\Temp\*.*", "M", "DF"134 |
Ensures that one or more statements are always executed after a Try statement finishes.
16 | 17 |Finally Statement
18 | Finally
19 | {
20 | Statements
21 | }
22 | Every use of Finally must belong to (be associated with) a Try statement above it (after any optional Catch and/or Else). A Finally always belongs to the nearest unclaimed Try statement above it unless a block is used to change that behavior.
24 |Try statements behave differently depending on whether Catch or Finally is present. For more information, see Try.
25 |Goto, Break, Continue and Return cannot be used to exit a Finally block, as that would require suppressing any control flow statements within the Try block. For example, if Try uses return 42
, the value 42 is returned after the Finally block executes. Attempts to jump out of a Finally block using one of these statements are detected as errors at load time where possible, or at run time otherwise.
Finally statements are not executed if the script is directly terminated by any means, including the tray menu or ExitApp.
27 |The One True Brace (OTB) style may optionally be used with the Finally statement. For example:
28 |try { 29 | ... 30 | } finally { 31 | ... 32 | } 33 | 34 | try { 35 | ... 36 | } catch { 37 | ... 38 | } else { 39 | ... 40 | } finally { 41 | ... 42 | }43 |
Try, Catch, Else, Throw, Blocks
45 |Demonstrates the behavior of Finally in detail.
48 |try 49 | { 50 | ToolTip "Working..." 51 | Example1() 52 | } 53 | catch as e 54 | { 55 | ; For more detail about the object that e contains, see Error. 56 | MsgBox(Type(e) " thrown!`n`nwhat: " e.what "`nfile: " e.file 57 | . "`nline: " e.line "`nmessage: " e.message "`nextra: " e.extra,, 16) 58 | } 59 | finally 60 | { 61 | ToolTip ; hide the tooltip 62 | } 63 | 64 | MsgBox "Done!" 65 | 66 | ; This function has a Finally block that acts as cleanup code 67 | Example1() 68 | { 69 | try 70 | Example2() 71 | finally 72 | MsgBox "This is always executed regardless of exceptions" 73 | } 74 | 75 | ; This function fails when the minutes are odd 76 | Example2() 77 | { 78 | if Mod(A_Min, 2) 79 | throw Error("That's odd...") 80 | MsgBox "Example2 did not fail" 81 | }82 |
Converts a numeric string or integer value to a floating-point number.
16 |FltValue := Float(Value)
17 |
18 | Type: Float
20 |This function returns the result of converting Value to a pure floating-point number (having the type name "Float"), or Value itself if it is already the correct type.
21 | 22 |If the value cannot be converted, a TypeError is thrown.
24 |To determine if a value can be converted to a floating-point number, use the IsNumber function.
25 |Float is actually a class, but can be called as a function. Value is Float
can be used to check whether a value is a pure floating-point number.
Type, Integer, Number, String, Values, Expressions, Is functions
29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /docs/lib/For.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Repeats one or more statements once for each key-value pair in an object.
16 | 17 |For Value1 , Value2 in Expression18 |
Type: Variable
24 |The variables in which to store the values returned by the enumerator at the beginning of each iteration. The nature of these values is defined by the enumerator, which is determined by Expression. These variables cannot be dynamic.
25 |When the loop breaks or completes, these variables are restored to their former values. If a loop variable is a ByRef parameter, the target variable is unaffected by the loop. Closures which reference the variable (if local) are also unaffected and will see only the value it had outside the loop.
26 |Note: Even if defined inside the loop body, a nested function which refers to a loop variable cannot see or change the current iteration's value. Instead, pass the variable explicitly or bind its value to a parameter.
27 |Up to 19 variables are supported, if supported by the enumerator.
28 |Variables can be omitted. For example, for , value in myMap
calls myMap's enumerator with only its second parameter, omitting its first parameter. If the enumerator is user-defined and the parameter is mandatory, an exception is thrown as usual. The parameter count passed to __Enum is 0 if there are no variables or commas; otherwise it is 1 plus the number of commas present.
Type: Object
34 |An expression which results in an enumerable object, or a variable which contains an enumerable object.
35 |The parameter list can optionally be enclosed in parentheses. For example: for (val in myarray)
The process of enumeration is as follows:
42 |__Enum
method is called to retrieve an enumerator object. If no such method exists, the object itself is assumed to be an enumerator object.Although not exactly equivalent to a for-loop, the following demonstrates this process:
48 |_enum := Expression 49 | try _enum := _enum.__Enum(2) 50 | while _enum(&Value1, &Value2) 51 | { 52 | ... 53 | } 54 |55 |
As in the code above, an exception is thrown if Expression or __Enum yields a value which cannot be called.
56 |While enumerating properties, methods or array elements, it is generally unsafe to insert or remove items of that type. Doing so may cause some items to be skipped or enumerated multiple times. One workaround is to build a list of items to remove, then use a second loop to remove the items after the first loop completes.
57 |A for-loop is usually followed by a block, which is a collection of statements that form the body of the loop. However, a loop with only a single statement does not require a block (an "if" and its "else" count as a single statement for this purpose). The One True Brace (OTB) style may optionally be used, which allows the open-brace to appear on the same line rather than underneath. For example: for x, y in z {
.
As with all loops, Break, Continue and A_Index may be used.
59 |The loop may optionally be followed by an Else statement, which is executed if the loop had zero iterations.
60 | 61 |Since Value1 and Value2 are passed directly to the enumerator, the values they are assigned depends on what type of object is being enumerated. For COM objects, Value1 contains the value returned by IEnumVARIANT::Next() and Value2 contains a number which represents its variant type. For example, when used with a Scripting.Dictionary object, each Value1 contains a key from the dictionary and Value2 is typically 8 for strings and 3 for integers. See ComObjType for a list of type codes.
63 |When enumerating a SafeArray, Value1 contains the current element and Value2 contains its variant type.
64 | 65 |Enumerator object, OwnProps, While-loop, Loop, Until, Break, Continue, Blocks
67 | 68 |Lists the properties owned by an object.
71 |colours := {red: 0xFF0000, blue: 0x0000FF, green: 0x00FF00} 72 | ; The above expression could be used directly in place of "colours" below: 73 | s := "" 74 | for k, v in colours.OwnProps() 75 | s .= k "=" v "`n" 76 | MsgBox s 77 |78 |
Lists all open Explorer and Internet Explorer windows, using the Shell object.
82 |windows := "" 83 | for window in ComObject("Shell.Application").Windows 84 | windows .= window.LocationName " :: " window.LocationURL "`n" 85 | MsgBox windows86 |
Defines an enumerator as a fat arrow function. Returns numbers from the Fibonacci sequence, indefinitely or until stopped.
90 |for n in FibF() 91 | if MsgBox("#" A_Index " = " n "`nContinue?",, "y/n") = "No" 92 | break 93 | 94 | FibF() { 95 | a := 0, b := 1 96 | return (&n) => ( 97 | n := c := b, b += a, a := c, 98 | true 99 | ) 100 | }101 |
Defines an enumerator as a class. Equivalent to the previous example.
105 |for n in FibC() 106 | if MsgBox("#" A_Index " = " n "`nContinue?",, "y/n") = "No" 107 | break 108 | 109 | class FibC { 110 | a := 0, b := 1 111 | Call(&n) { 112 | n := c := this.b, this.b += this.a, this.a := c 113 | return true 114 | } 115 | }116 |
Formats a variable number of input values according to a format string.
16 | 17 |String := Format(FormatStr , Values...)18 |
Type: String
24 |A format string composed of literal text and placeholders of the form {Index:Format}
.
Index is an integer indicating which input value to use, where 1 is the first value.
26 |Format is an optional format specifier, as described below.
27 |Omit the index to use the next input value in the sequence (even if it has been used earlier in the string). For example, "{2:i} {:i}"
formats the second and third input values as decimal integers, separated by a space. If Index is omitted, Format must still be preceded by :
. Specify empty braces to use the next input value with default formatting: {}
Use {{}
and {}}
to include literal braces in the string. Any other invalid placeholders are included in the result as is.
Whitespace inside the braces is not permitted (except as a flag).
30 |Type: String, Integer or Float
35 |Input values to be formatted and inserted into the final string. Each value is a separate parameter. The first value has an index of 1.
36 |To pass an array of values, use a variadic function call:
37 |arr := [13, 240] 38 | MsgBox Format("{2:x}{1:02x}", arr*)39 |
Type: String
45 |This function returns the formatted version of the specified string.
46 | 47 |Each format specifier can include the following components, in this order (without the spaces):
49 |Flags Width .Precision ULT Type50 |
Flags: Zero or more flags from the flag table below to affect output justification and prefixes.
51 |Width: A decimal integer which controls the minimum width of the formatted value, in characters. By default, values are right-aligned and spaces are used for padding. This can be overridden by using the -
(left-align) and 0
(zero prefix) flags.
.Precision: A decimal integer which controls the maximum number of string characters, decimal places, or significant digits to output, depending on the output type. It must be preceded by a decimal point. Specifying a precision may cause the value to be truncated or rounded. Output types and how each is affected by the precision value are as follows (see table below for an explanation of the different output types):
53 |f
, e
, E
: Precision specifies the number of digits after the decimal point. The default is 6.g
, G
: Precision specifies the maximum number of significant digits. The default is 6.s
: Precision specifies the maximum number of characters to be printed. Characters in excess of this are not printed.d
, i
, u
, x
, X
, o
), Precision acts like Width with the 0
prefix and a default of 1.ULT: Specifies a case transformation to apply to a string value -- Upper, Lower or Title. Valid only with the s
type. For example {:U}
or {:.20Ts}
. Lower-case l
and t
are also supported, but u
is reserved for unsigned integers.
Type: A character from the type table below indicating how the input value should be interpreted. If omitted, it defaults to s
.
Flag | Meaning |
---|---|
- |
67 |
68 | Left align the result within the given field width (insert spaces to the right if needed). For example, If omitted, the result is right aligned within the given field width. 70 | |
71 |
+ |
74 |
75 | Use a sign (+ or -) to prefix the output value if it is of a signed type. For example, If omitted, a sign appears only for negative signed values (-). 77 | |
78 |
0 |
81 |
82 | If width is prefixed by 0, leading zeros are added until the minimum width is reached. For example, If omitted, no padding occurs. 84 | |
85 |
|
88 |
89 | Use a space to prefix the output value with a single space if it is signed and positive. The space is ignored if both If omitted, no space appears. 91 | |
92 |
# |
95 |
96 | When it's used with the o, x, or X format, the # flag uses When it's used with the e, E, f, a or A format, the # flag forces the output value to contain a decimal point. For example, When it's used with the g or G format, the # flag forces the output value to contain a decimal point and prevents the truncation of trailing zeros. 99 |Ignored when used with c, d, i, u, or s. 100 | |
101 |
Type Character | Argument | Output format |
---|---|---|
d or i |
109 | Integer | 110 |Signed decimal integer. For example, Format("{:d}", 1.23) returns 1 . |
111 |
u |
114 | Integer | 115 |Unsigned decimal integer. | 116 |
x or X |
119 | Integer | 120 |Unsigned hexadecimal integer; uses "abcdef" or "ABCDEF" depending on the case of x . The 0x prefix is not included unless the # flag is used, as in {:#x} . To always include the prefix, use 0x{:x} or similar. For example, Format("{:X}", 255) returns FF . |
121 |
o |
124 | Integer | 125 |Unsigned octal integer. For example, Format("{:o}", 255) returns 377 . |
126 |
f |
129 | Floating-point | 130 |Signed value that has the form [ - ]dddd.dddd, where dddd is one or more decimal digits. The number of digits before the decimal point depends on the magnitude of the number, and the number of digits after the decimal point depends on the requested precision. For example, Format("{:.2f}", 1) returns 1.00 . |
131 |
e |
134 | Floating-point | 135 |Signed value that has the form [ - ]d.dddd e [sign]dd[d] where d is one decimal digit, dddd is one or more decimal digits, dd[d] is two or three decimal digits depending on the output format and size of the exponent, and sign is + or -. For example, Format("{:e}", 255) returns 2.550000e+02 . |
136 |
E |
139 | Floating-point | 140 |Identical to the e format except that E rather than e introduces the exponent. |
141 |
g |
144 | Floating-point | 145 |Signed values are displayed in f or e format, whichever is more compact for the given value and precision. The e format is used only when the exponent of the value is less than -4 or greater than or equal to the precision argument. Trailing zeros are truncated, and the decimal point appears only if one or more digits follow it. |
146 |
G |
149 | Floating-point | 150 |Identical to the g format, except that E, rather than e, introduces the exponent (where appropriate). |
151 |
a |
154 | Floating-point | 155 |Signed hexadecimal double-precision floating-point value that has the form [?]0xh.hhhh p±dd, where h.hhhh are the hex digits (using lower case letters) of the mantissa, and dd are one or more digits for the exponent. The precision specifies the number of digits after the point. For example, Format("{:a}", 255) returns 0x1.fe00000000000p+7 . |
156 |
A |
159 | Floating-point | 160 |Identical to the a format, except that P, rather than p, introduces the exponent. |
161 |
p |
164 | Integer | 165 |Displays the argument as a memory address in hexadecimal digits. For example, Format("{:p}", 255) returns 00000000000000FF . |
166 |
s |
169 | String | 170 |Specifies a string. If the input value is numeric, it is automatically converted to a string before the Width and Precision arguments are applied. | 171 |
c |
174 | Character code | 175 |Specifies a single character by its ordinal value, similar to Chr(n) . If the input value is outside the expected range, it wraps around. For example, Format("{:c}", 116) returns t . |
176 |
Unlike printf, size specifiers are not supported. All integers and floating-point input values are 64-bit.
181 | 182 |Demonstrates different usages.
188 |189 | s := "" 190 | ; Simple substitution 191 | s .= Format("{2}, {1}!`r`n", "World", "Hello") 192 | ; Padding with spaces 193 | s .= Format("|{:-10}|`r`n|{:10}|`r`n", "Left", "Right") 194 | ; Hexadecimal 195 | s .= Format("{1:#x} {2:X} 0x{3:x}`r`n", 3735928559, 195948557, 0) 196 | ; Floating-point 197 | s .= Format("{1:0.3f} {1:.10f}", 4*ATan(1)) 198 | 199 | ListVars ; Use AutoHotkey's main window to display monospaced text. 200 | WinWaitActive "ahk_class AutoHotkey" 201 | ControlSetText(s, "Edit1") 202 | WinWaitClose 203 |204 |
Transforms a YYYYMMDDHH24MISS timestamp into the specified date/time format.
19 | 20 |String := FormatTime(YYYYMMDDHH24MISS, Format)21 |
Type: String
27 |If blank or omitted, it defaults to the current local date and time. Otherwise, specify all or the leading part of a timestamp in the YYYYMMDDHH24MISS format.
28 |Type: String
33 |If blank or omitted, it defaults to the time followed by the long date, both of which will be formatted according to the current user's locale. For example: 4:55 PM Saturday, November 27, 2004
34 |Otherwise, specify one or more of the date-time formats from the tables below, along with any literal spaces and punctuation in between (commas do not need to be escaped; they can be used normally). In the following example, note that M must be capitalized: M/d/yyyy h:mm tt
35 |Type: String
41 |This function returns the transformed version of the specified timestamp.
42 |If YYYYMMDDHH24MISS contains a invalid date and/or time portion -- such as February 29th of a non-leap year -- the date and/or time will be omitted from the return value. Although only years between 1601 and 9999 are supported, a formatted time can still be produced for earlier years as long as the time portion is valid.
43 |If Format contains more than 2000 characters, an empty string is returned.
44 | 45 |Format | 49 |Description | 50 |
---|---|
d | 53 |Day of the month without leading zero (1 – 31) | 54 |
dd | 57 |Day of the month with leading zero (01 – 31) | 58 |
ddd | 61 |Abbreviated name for the day of the week (e.g. Mon) in the current user's language | 62 |
dddd | 65 |Full name for the day of the week (e.g. Monday) in the current user's language | 66 |
M | 69 |Month without leading zero (1 – 12) | 70 |
MM | 73 |Month with leading zero (01 – 12) | 74 |
MMM | 77 |Abbreviated month name (e.g. Jan) in the current user's language | 78 |
MMMM | 81 |Full month name (e.g. January) in the current user's language | 82 |
y | 85 |Year without century, without leading zero (0 – 99) | 86 |
yy | 89 |Year without century, with leading zero (00 – 99) | 90 |
yyyy | 93 |Year with century. For example: 2005 | 94 |
gg | 97 |Period/era string for the current user's locale (blank if none) | 98 |
Format | 104 |Description | 105 |
---|---|
h | 108 |Hours without leading zero; 12-hour format (1 – 12) | 109 |
hh | 112 |Hours with leading zero; 12-hour format (01 – 12) | 113 |
H | 116 |Hours without leading zero; 24-hour format (0 – 23) | 117 |
HH | 120 |Hours with leading zero; 24-hour format (00 – 23) | 121 |
m | 124 |Minutes without leading zero (0 – 59) | 125 |
mm | 128 |Minutes with leading zero (00 – 59) | 129 |
s | 132 |Seconds without leading zero (0 – 59) | 133 |
ss | 136 |Seconds with leading zero (00 – 59) | 137 |
t | 140 |Single character time marker, such as A or P (depends on locale) | 141 |
tt | 144 |Multi-character time marker, such as AM or PM (depends on locale) | 145 |
The following formats must be used alone; that is, with no other formats or text present in the Format parameter. These formats are not case-sensitive.
149 |Format | 152 |Description | 153 |
---|---|
(Blank) | 156 |Leave Format blank to produce the time followed by the long date. For example, in some locales it might appear as 4:55 PM Saturday, November 27, 2004 | 157 |
Time | 160 |Time representation for the current user's locale, such as 5:26 PM | 161 |
ShortDate | 164 |Short date representation for the current user's locale, such as 02/29/04 | 165 |
LongDate | 168 |Long date representation for the current user's locale, such as Friday, April 23, 2004 | 169 |
YearMonth | 172 |Year and month format for the current user's locale, such as February, 2004 | 173 |
YDay | 176 |Day of the year without leading zeros (1 – 366) | 177 |
YDay0 | 180 |Day of the year with leading zeros (001 – 366) | 181 |
WDay | 184 |Day of the week (1 – 7). Sunday is 1. | 185 |
YWeek | 188 |The ISO 8601 full year and week number. For example: 200453. If the week containing January 1st has four or more days in the new year, it is considered week 1. Otherwise, it is the last week of the previous year, and the next week is week 1. Consequently, both January 4th and the first Thursday of January are always in week 1. | 189 |
The following options can appear inside the YYYYMMDDHH24MISS parameter immediately after the timestamp (if there is no timestamp, they may be used alone). In the following example, note the lack of commas between the last four items:
193 |OutputVar := FormatTime("20040228 LSys D1 D4")194 |
R: Reverse. Have the date come before the time (meaningful only when Format is blank).
195 |Ln: If this option is not present, the current user's locale is used to format the string. To use the system's locale instead, specify LSys. To use a specific locale, specify the letter L followed by a hexadecimal or decimal locale identifier (LCID). For information on how to construct an LCID, search www.microsoft.com for the following phrase: Locale Identifiers
196 |Dn: Date options. Specify for n one of the following numbers:
197 |Tn: Time options. Specify for n one of the following numbers:
209 |Note: Dn and Tn may be repeated to put more than one option into effect, such as this example: FormatTime("20040228 D2 D4 T1 T8")
Letters and numbers that you want to be transcribed literally from Format into the final string should be enclosed in single quotes as in this example: "'Date:' MM/dd/yy 'Time:' hh:mm:ss tt"
.
By contrast, non-alphanumeric characters such as spaces, tabs, linefeeds (`n), slashes, colons, commas, and other punctuation do not need to be enclosed in single quotes. The exception to this is the single quote character itself: to produce it literally, use four consecutive single quotes (''''), or just two if the quote is already inside an outer pair of quotes.
223 |If Format contains date and time elements together, they must not be intermixed. In other words, the string should be dividable into two halves: a time half and a date half. For example, a format string consisting of "hh yyyy mm" would not produce the expected result because it has a date element in between two time elements.
224 |When Format contains a numeric day of the month (either d or dd) followed by the full month name (MMMM), the genitive form of the month name is used (if the language has a genitive form).
225 |On a related note, addition, subtraction and comparison of dates and times can be performed with DateAdd and DateDiff.
226 |To convert in the reverse direction -- that is, from a formatted date/time to YYYYMMDDHH24MISS format -- see this archived forum thread.
228 |See also: Gui DateTime control, Format, built-in date and time variables, FileGetTime
229 |Demonstrates different usages.
232 |TimeString := FormatTime() 233 | MsgBox "The current time and date (time first) is " TimeString 234 | 235 | TimeString := FormatTime("R") 236 | MsgBox "The current time and date (date first) is " TimeString 237 | 238 | TimeString := FormatTime(, "Time") 239 | MsgBox "The current time is " TimeString 240 | 241 | TimeString := FormatTime("T12", "Time") 242 | MsgBox "The current 24-hour time is " TimeString 243 | 244 | TimeString := FormatTime(, "LongDate") 245 | MsgBox "The current date (long format) is " TimeString 246 | 247 | TimeString := FormatTime(20050423220133, "dddd MMMM d, yyyy hh:mm:ss tt") 248 | MsgBox "The specified date and time, when formatted, is " TimeString 249 | 250 | MsgBox FormatTime(200504, "'Month Name': MMMM`n'Day Name': dddd") 251 | 252 | YearWeek := FormatTime(20050101, "YWeek") 253 | MsgBox "January 1st of 2005 is in the following ISO year and week number: " YearWeek254 |
Changes the date-time stamp of a file.
258 |FileName := FileSelect(3,, "Pick a file") 259 | if FileName = "" ; The user didn't pick a file. 260 | return 261 | FileTime := FileGetTime(FileName) 262 | FileTime := FormatTime(FileTime) ; Since the last parameter is omitted, the long date and time are retrieved. 263 | MsgBox "The selected file was last modified at " FileTime264 |
Converts the specified number of seconds into the corresponding number of hours, minutes, and seconds (hh:mm:ss format).
268 |MsgBox FormatSeconds(7384) ; 7384 = 2 hours + 3 minutes + 4 seconds. It yields: 2:03:04 269 | 270 | FormatSeconds(NumberOfSeconds) ; Convert the specified number of seconds to hh:mm:ss format. 271 | { 272 | time := 19990101 ; *Midnight* of an arbitrary date. 273 | time := DateAdd(time, NumberOfSeconds, "Seconds") 274 | return NumberOfSeconds//3600 ":" FormatTime(time, "mm:ss") 275 | /* 276 | ; Unlike the method used above, this would not support more than 24 hours worth of seconds: 277 | return FormatTime(time, "h:mm:ss") 278 | */ 279 | }280 |
class Func extends Object15 | 16 |
Represents a user-defined or built-in function and provides an interface to call it, bind parameters to it, and retrieve information about it or its parameters.
17 |For information about other objects which can be called like functions, see Function Objects.
18 |The Closure
class extends Func
but does not define any new properties.
For each built-in function or function definition within the script, there is a corresponding read-only variable containing a Func object. This variable is directly used to call the function, but its value can also be read to retrieve the function itself, as a value. For example:
21 |InspectFn StrLen 22 | InspectFn InspectFn 23 | 24 | InspectFn(fn) 25 | { 26 | ; Display information about the passed function. 27 | MsgBox fn.Name "() is " (fn.IsBuiltIn ? "built-in." : "user-defined.") 28 | } 29 |30 |
"FuncObj" is used below as a placeholder for any Func object, as "Func" is the class itself.
31 |In addition to the methods and property inherited from Object, Func objects have the following predefined methods and properties.
32 | 33 |Calls the function.
58 |FuncObj(Param1, Param2, ...)
59 | FuncObj.Call(Param1, Param2, ...)
60 | Parameters and return value are defined by the function.
65 |The "Call" method is implied when calling a value, so need not be explicitly specified.
69 |Binds parameters to the function.
73 |BoundFunc := FuncObj.Bind(Param1, Param2, ...)
74 | Any number of parameters.
79 |Type: Object
83 |This method returns a BoundFunc object.
84 |Determines whether a parameter is ByRef.
88 |Boolean := FuncObj.IsByRef(ParamIndex)89 |
Type: Integer
94 |If omitted, Boolean indicates whether the function has any ByRef parameters. Otherwise, specify the one-based index of a parameter.
95 |Type: Integer (boolean)
99 |This method returns 1 (true) if the parameter is ByRef, otherwise 0 (false). If ParamIndex is invalid, an exception is thrown.
100 |Determines whether a parameter is optional.
104 |Boolean := FuncObj.IsOptional(ParamIndex)105 |
Type: Integer
110 |If omitted, Boolean indicates whether the function has any optional parameters. Otherwise, specify the one-based index of a parameter.
111 |Type: Integer (boolean)
115 |This method returns 1 (true) if the parameter is optional, otherwise 0 (false). If ParamIndex is invalid, an exception is thrown.
116 |Parameters do not need to be formally declared if the function is variadic. Built-in functions are supported.
Returns the function's name.
123 |FunctionName := FuncObj.Name
124 | Returns 1 (true) if the function is built-in, otherwise 0 (false).
128 |Boolean := FuncObj.IsBuiltIn
129 | Returns 1 (true) if the function is variadic, otherwise 0 (false).
133 |Boolean := FuncObj.IsVariadic
134 | Returns the number of required parameters.
138 |ParamCount := FuncObj.MinParams
139 | Returns the number of formally-declared parameters for a user-defined function or maximum parameters for a built-in function.
143 |ParamCount := FuncObj.MaxParams
144 | If the function is variadic, ParamCount indicates the maximum number of parameters which can be accepted by the function without overflowing into the "variadic*" parameter.
Retrieves the name/text of a key.
17 | 18 |Name := GetKeyName(KeyName)
19 | Type: String
25 |This can be just about any single character from the keyboard or one of the key names from the key list. Examples: B, 5, LWin, RControl, Alt, Enter, Escape.
26 |Alternatively, this can be an explicit virtual key code such as vkFF, an explicit scan code such as sc01D, or a combination of VK and SC (in that order) such as vk1Bsc001. Note that these codes must be in hexadecimal.
27 |Type: String
33 |This function returns the name of the specified key, or blank if the key is invalid or unnamed.
34 | 35 |GetKeyVK, GetKeySC, GetKeyState, Key List
37 |Retrieves and reports the English name of Esc.
40 |MsgBox GetKeyName("Esc") ; Shows Escape 41 | MsgBox GetKeyName("vk1B") ; Shows also Escape42 |
Retrieves the scan code of a key.
17 | 18 |SC := GetKeySC(KeyName)
19 | Type: String
25 |Any single character or one of the key names from the key list. Examples: B, 5, LWin, RControl, Alt, Enter, Escape.
26 |Alternatively, this can be an explicit virtual key code such as vkFF, an explicit scan code such as sc01D, or a combination of VK and SC (in that order) such as vk1Bsc001. Note that these codes must be in hexadecimal.
27 |Type: Integer
33 |This function returns the scan code of the specified key, or 0 if the key is invalid or has no scan code.
34 | 35 |Before using the scan code with a built-in function like Hotkey or GetKeyState, it must first be converted to hexadecimal format, such as by using Format("sc{:X}", sc_code)
. By contrast, external functions called via DllCall typically use the numeric value directly.
If KeyName corresponds to a virtual key code or single character, the function attempts to map the value to a scan code by calling certain system functions which refer to the script's current keyboard layout. This may differ from the keyboard layout of the active window.
38 |If KeyName is an ASCII letter in the range A-Z and has no mapping within the keyboard layout, the corresponding virtual key in the range vk41-vk5A is used as a fallback. This virtual key is then mapped to a scan code as described above.
39 |Some keyboard layouts do not define a 1:1 mapping of virtual key codes to scan codes. When multiple interpretations are possible, the underlying system functions most likely choose one based on the order defined in the keyboard layout, which is not always the most common or logical choice.
40 | 41 |GetKeyVK, GetKeyName, GetKeyState, Key List, Format
43 |Retrieves and reports the hexadecimal scan code of the left Ctrl.
46 |sc_code := GetKeySC("LControl") 47 | MsgBox Format("sc{:X}", sc_code) ; Reports sc1D48 |
Returns 1 (true) or 0 (false) depending on whether the specified keyboard key or mouse/controller button is down or up. Also retrieves controller status.
16 | 17 |IsDown := GetKeyState(KeyName , Mode)18 |
Type: String
24 |This can be just about any single character from the keyboard or one of the key names from the key list, such as a mouse/controller button. Examples: B, 5, LWin, RControl, Alt, Enter, Escape, LButton, MButton, Joy1.
25 |Alternatively, an explicit virtual key code such as vkFF may be specified. This is useful in the rare case where a key has no name. The code of such a key can be determined by following the steps at the bottom of the key list page. Note that this code must be in hexadecimal.
26 |Known limitation: This function cannot differentiate between two keys which share the same virtual key code, such as Left and NumpadLeft.
27 |Type: String
32 |This parameter is ignored when retrieving controller status.
33 |If omitted, it defaults to that which retrieves the logical state of the key. This is the state that the OS and the active window believe the key to be in, but is not necessarily the same as the physical state.
34 |Otherwise, specify one of the following letters:
35 |P: Retrieve the physical state (i.e. whether the user is physically holding it down). The physical state of a key or mouse button will usually be the same as the logical state unless the keyboard and/or mouse hooks are installed, in which case it will accurately reflect whether or not the user is physically holding down the key or button (as long as it was pressed down while the script was running). You can determine if your script is using the hooks via the KeyHistory function or menu item. You can force the hooks to be installed by calling InstallKeybdHook and/or InstallMouseHook.
36 |T: Retrieve the toggle state. For keys other than CapsLock, NumLock and ScrollLock, the toggle state is generally 0 when the script starts and is not synchronized between processes.
37 |Type: Integer (boolean), Float, Integer or String (empty)
43 |This function returns 1 (true) if the key is down (or toggled on) or 0 (false) if it is up (or toggled off).
44 |When KeyName is a stick axis such as JoyX, this function returns a floating-point number between 0 and 100 to indicate the stick's position as a percentage of that axis's range of motion. This test script can be used to analyze your controller(s).
45 |When KeyName is JoyPOV, this function returns an integer between 0 and 35900. The following approximate POV values are used by many controllers:
46 |When KeyName is JoyName, JoyButtons, JoyAxes or JoyInfo, the retrieved value will be the name, number of buttons, number of axes or capabilities of the controller. For details, see Game Controller.
54 |When KeyName is a button or control of a controller that could not be detected, this function returns an empty string.
55 | 56 |A ValueError is thrown if invalid parameters are detected, e.g. when KeyName does not exist on the current keyboard layout.
58 | 59 |To wait for a key or mouse/controller button to achieve a new state, it is usually easier to use KeyWait instead of a GetKeyState loop.
61 |Systems with unusual keyboard drivers might be slow to update the state of their keys, especially the toggle-state of keys like CapsLock. A script that checks the state of such a key immediately after it changed may use Sleep beforehand to give the system time to update the key state.
62 |For examples of using GetKeyState with a controller, see the controller remapping page and the Controller-To-Mouse script.
63 |GetKeyVK, GetKeySC, GetKeyName, KeyWait, Key List, Controller remapping, KeyHistory, InstallKeybdHook, InstallMouseHook
65 | 66 |Retrieves the current state of the right mouse button.
70 |state := GetKeyState("RButton")71 |
Retrieves the current state of the first controller's second button.
75 |state := GetKeyState("Joy2")76 |
Checks if at least one Shift is down.
80 |if GetKeyState("Shift") 81 | MsgBox "At least one Shift key is down." 82 | else 83 | MsgBox "Neither Shift key is down."84 |
Retrieves the current toggle state of CapsLock.
88 |state := GetKeyState("CapsLock", "T")89 |
Remapping. (This example is only for illustration because it would be easier to use the built-in remapping feature.) In the following hotkey, the mouse button is kept held down while NumpadAdd is down, which effectively transforms NumpadAdd into a mouse button. This method can also be used to repeat an action while the user is holding down a key or button.
93 |*NumpadAdd:: 94 | { 95 | MouseClick "left",,, 1, 0, "D" ; Hold down the left mouse button. 96 | Loop 97 | { 98 | Sleep 10 99 | if !GetKeyState("NumpadAdd", "P") ; The key has been released, so break out of the loop. 100 | break 101 | ; ... insert here any other actions you want repeated. 102 | } 103 | MouseClick "left",,, 1, 0, "U" ; Release the mouse button. 104 | }105 |
Makes controller button behavior depend on stick axis position.
109 |joy2:: 110 | { 111 | JoyX := GetKeyState("JoyX") 112 | if JoyX > 75 113 | MsgBox "Action #1 (button pressed while stick was pushed to the right)." 114 | else if JoyX < 25 115 | MsgBox "Action #2 (button pressed while stick was pushed to the left)." 116 | else 117 | MsgBox "Action #3 (button pressed while stick was centered horizontally)." 118 | }119 |
See the controller remapping page and the Controller-To-Mouse script for other examples.
122 | 123 | 124 | 125 | -------------------------------------------------------------------------------- /docs/lib/GetKeyVK.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Retrieves the virtual key code of a key.
17 | 18 |VK := GetKeyVK(KeyName)
19 | Type: String
25 |Any single character or one of the key names from the key list. Examples: B, 5, LWin, RControl, Alt, Enter, Escape.
26 |Alternatively, this can be an explicit virtual key code such as vkFF, an explicit scan code such as sc01D, or a combination of VK and SC (in that order) such as vk1Bsc001. Note that these codes must be in hexadecimal.
27 |Type: Integer
33 |This function returns the virtual key code of the specified key, or 0 if the key is invalid or has no virtual key code.
34 | 35 |Before using the virtual key code with a built-in function like Hotkey or GetKeyState, it must first be converted to hexadecimal format, such as by using Format("vk{:X}", vk_code)
. By contrast, external functions called via DllCall typically use the numeric value directly.
If KeyName corresponds to a scan code or single character, the function attempts to map the value to a virtual key code by calling certain system functions which refer to the script's current keyboard layout. This may differ from the keyboard layout of the active window.
38 |If KeyName is an ASCII letter in the range A-Z and has no mapping within the keyboard layout, the corresponding virtual key in the range vk41-vk5A is used as a fallback.
39 |Some keyboard layouts do not define a 1:1 mapping of virtual key codes to scan codes. When multiple interpretations are possible, the underlying system functions most likely choose one based on the order defined in the keyboard layout, which is not always the most common or logical choice.
40 | 41 |GetKeySC, GetKeyName, GetKeyState, Key List, Format
43 |Retrieves and reports the hexadecimal virtual key code of Esc.
46 |vk_code := GetKeyVK("Esc") 47 | MsgBox Format("vk{:X}", vk_code) ; Reports vk1B48 |
Retrieves the implementation function of a method.
17 | 18 |Method := GetMethod(Value , Name, ParamCount)19 |
Type: Any
24 |Any value, of any type except ComObject.
25 |Type: String
29 |If omitted, validation is performed on Value itself and Value is returned if successful. Otherwise, specify the name of the method to retrieve.
30 | 31 |If omitted (or if the parameter count was not verified), a basic check is performed for a Call method to verify that the object is most likely callable.
36 |Otherwise, specify the number of parameters that would be passed to the method or function. If specified, the method's MinParams, MaxParams and IsVariadic properties may be queried to verify that it can accept this number of parameters. If those properties are not present, the parameter count is not verified.
37 |This count should not include the implicit this
parameter.
Type: Function Object
43 |This function returns the function object which contains the implementation of the method, or Value itself if Name was omitted.
44 | 45 |If the method is not found or cannot be retrieved without invoking a property getter, a MethodError is thrown.
47 |If validation is attempted, exceptions may be thrown as a result of querying the method's properties. A ValueError or MethodError is thrown if validation fails.
48 | 49 |Methods may be defined through one of the following:
51 |{Call: fn}
to DefineProp, where fn implements the method.When calling the function object, it is necessary to supply a value for the normally-hidden this parameter. For example, Method(Value, Parameters*)
.
Although the standard implementation of GetMethod has limitations as described above, if Value.GetMethod(Name)
is used instead of GetMethod(Value, Name)
, the object Value can define its own implementation of GetMethod.
GetMethod(Value, "Call", N)
is not the same as GetMethod(Value,, N)
, as the Call method takes the function object itself as a parameter, and its usage may otherwise differ from that of Value. For instance, Func.Prototype.Call
is a single method which applies to all built-in and user-defined functions, and as such must accept any number of parameters.
Objects, HasMethod, HasBase, HasProp
69 | 70 |Retrieves and reports information about the GetMethod method.
73 |74 | method := GetMethod({}, "GetMethod") ; It's also a method. 75 | MsgBox method.MaxParams ; Takes 2 parameters, including 'this'. 76 | MsgBox method = GetMethod ; Actually the same object in this case. 77 |78 |
Jumps to the specified label and continues execution.
16 | 17 |Goto Label 18 | Goto("Label")19 |
Label can be a variable or expression only if parentheses are used. For example, Goto MyLabel
and Goto("MyLabel")
both jump to MyLabel:
.
Performance is slightly reduced when using a dynamic label (that is, a variable or expression which returns a label name) because the target label must be "looked up" each time rather than only once when the script is first loaded. An error dialog will be displayed if the label does not exist. To avoid this, call IsLabel() beforehand. For example:
33 |if IsLabel(VarContainingLabelName) 34 | Goto(VarContainingLabelName)35 |
The use of Goto is discouraged because it generally makes scripts less readable and harder to maintain. Consider using Else, Blocks, Break, and Continue as substitutes for Goto.
36 |Return, IsLabel, Else, Blocks, Break, Continue
38 |Jumps to the label named "MyLabel" and continues execution.
41 |Goto MyLabel 42 | ; ... 43 | MyLabel: 44 | Sleep 100 45 | ; ...46 |
Activates the next window in a window group that was defined with GroupAdd.
16 | 17 |HWND := GroupActivate(GroupName , Mode)18 |
Type: String
24 |The name of the group to activate, as originally defined by GroupAdd.
25 |Type: String
30 |If blank or omitted, the function activates the oldest window in the series. Otherwise, specify the following letter:
31 |R: The newest window (the one most recently active) is activated, but only if no members of the group are active when the function is given. "R" is useful in cases where you temporarily switch to working on an unrelated task. When you return to the group via GroupActivate, GroupDeactivate, or GroupClose, the window you were most recently working with is activated rather than the oldest window.
32 |Type: Integer
38 |This function returns the HWND (unique ID) of the window selected for activation, or 0 if no matching windows were found to activate. If the current active window is the only match, the return value is 0.
39 | 40 |This function causes the first window that matches one of the group's window specifications to be activated. Using it a second time will activate the next window in the series and so on. Normally, it is assigned to a hotkey so that this window-traversal behavior is automated by pressing that key.
42 |Each window is evaluated against the window group as a whole, without distinguishing between window specifications. Mode affects the order of activation across the entire group.
43 |When a window is activated immediately after the activation of some other window, task bar buttons might start flashing on some systems (depending on OS and settings). To prevent this, use #WinActivateForce.
44 |See GroupAdd for more details about window groups.
45 | 46 |GroupAdd, GroupDeactivate, GroupClose, #WinActivateForce
48 |Activates the newest window (the one most recently active) in a window group.
51 |GroupActivate "MyGroup", "R"52 |
Adds a window specification to a window group, creating the group if necessary.
16 | 17 |GroupAdd GroupName , WinTitle, WinText, ExcludeTitle, ExcludeText18 |
Type: String
24 |The name of the group to which to add this window specification. If the group doesn't exist, it will be created. Group names are not case-sensitive.
25 |Type: String, Integer or Object
30 |Specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. Although DetectHiddenWindows, DetectHiddenText and SetTitleMatchMode do not directly affect the behavior of this function, they do affect the other group functions such as GroupActivate and GroupClose. They also affect the use of ahk_group in any other function's WinTitle.
33 |Each use of this function adds a new rule to a group. In other words, a group consists of a set of criteria rather than a fixed list of windows. Later, when a group is used by a function such as GroupActivate, each window on the desktop is checked against each of these criteria. If a window matches one of the criteria in the group, it is considered a match.
39 |A window group is typically used to bind together a collection of related windows, which is useful for tasks that involve many related windows, or an application that owns many subwindows. For example, if you frequently work with many instances of a graphics program or text editor, you can use GroupActivate on a hotkey to visit each instance of that program, one at a time, without having to use alt-tab or task bar buttons to locate them.
40 |Since the entries in each group need to be added only once, this function is typically used during script startup. Attempts to add duplicate entries to a group are ignored.
41 |To include all windows in a group (except the special Program Manager window), use this example:
42 |GroupAdd "AllWindows"43 |
All windowing functions can operate upon a window group by specifying ahk_group MyGroupName
for the WinTitle parameter. The functions WinMinimize, WinMaximize, WinRestore, WinHide, WinShow, WinClose, and WinKill will operate upon all the group's windows. To instead operate upon only the topmost window, follow this example:
WinHide WinExist("ahk_group MyGroup")45 |
By contrast, other windowing functions such as WinActivate and WinExist will operate only upon the topmost window of the group.
46 |GroupActivate, GroupDeactivate, GroupClose
48 |Press a hotkey to traverse all open MSIE windows.
51 |; In global code, to be evaluated at startup: 52 | GroupAdd "MSIE", "ahk_class IEFrame" ; Add only Internet Explorer windows to this group. 53 | 54 | ; Assign a hotkey to activate this group, which traverses 55 | ; through all open MSIE windows, one at a time (i.e. each 56 | ; press of the hotkey). 57 | Numpad1::GroupActivate "MSIE", "r"58 |
Press a hotkey to visit each MS Outlook 2002 window, one at a time.
62 |; In global code, to be evaluated at startup: 63 | SetTitleMatchMode 2 64 | GroupAdd "mail", "Message - Microsoft Word" ; This is for mails currently being composed 65 | GroupAdd "mail", "- Message (" ; This is for already opened items 66 | ; Need extra text to avoid activation of a phantom window: 67 | GroupAdd "mail", "Advanced Find", "Sear&ch for the word(s)" 68 | GroupAdd "mail", , "Recurrence:" 69 | GroupAdd "mail", "Reminder" 70 | GroupAdd "mail", "- Microsoft Outlook" 71 | 72 | ; Assign a hotkey to visit each Outlook window, one at a time. 73 | Numpad5::GroupActivate "mail"74 |
Closes the active window if it was just activated by GroupActivate or GroupDeactivate. It then activates the next window in the series. It can also close all windows in a group.
16 | 17 |GroupClose GroupName , Mode18 |
Type: String
24 |The name of the group as originally defined by GroupAdd.
25 |Type: String
30 |If blank or omitted, the function closes the active window and activates the oldest window in the series. Otherwise, specify one of the following letters:
31 |R: The newest window (the one most recently active) is activated, but only if no members of the group are active when the function is given. "R" is useful in cases where you temporarily switch to working on an unrelated task. When you return to the group via GroupActivate, GroupDeactivate, or GroupClose, the window you were most recently working with is activated rather than the oldest window.
32 |A: All members of the group will be closed. This is the same effect as WinClose "ahk_group GroupName"
.
When the Mode parameter is not "A", the behavior of this function is determined by whether the previous action on GroupName was GroupActivate or GroupDeactivate. If it was GroupDeactivate, this function will close the active window only if it is not a member of the group (otherwise it will do nothing). If it was GroupActivate or nothing, this function will close the active window only if it is a member of the group (otherwise it will do nothing). This behavior allows GroupClose to be assigned to a hotkey as a companion to GroupName's GroupActivate or GroupDeactivate hotkey.
39 |When the active window closes, the system typically activates the next most recently active window. If the newly active window is a match for the same window specification as the window that was just closed, it is left active even though the default Mode would normally dictate that the oldest window should be activated next. If the newly active window is a match for any of the group's window specifications, it is left active.
40 |See GroupAdd for more details about window groups.
41 | 42 |GroupAdd, GroupActivate, GroupDeactivate
44 |Closes the active window activated by GroupActivate or GroupDeactivate and activates the newest window (the one most recently active) in a window group.
47 |GroupClose "MyGroup", "R"48 |
Similar to GroupActivate except activates the next window not in the group.
16 | 17 |GroupDeactivate GroupName , Mode18 |
Type: String
24 |The name of the target group, as originally defined by GroupAdd.
25 |Type: String
30 |If blank or omitted, the function activates the oldest non-member window. Otherwise, specify the following letter:
31 |R: The newest non-member window (the one most recently active) is activated, but only if a member of the group is active when the function is given. "R" is useful in cases where you temporarily switch to working on an unrelated task. When you return to the group via GroupActivate, GroupDeactivate, or GroupClose, the window you were most recently working with is activated rather than the oldest window.
32 |GroupDeactivate causes the first window that does not match any of the group's window specifications to be activated. Using GroupDeactivate a second time will activate the next window in the series and so on. Normally, GroupDeactivate is assigned to a hotkey so that this window-traversal behavior is automated by pressing that key.
38 |This function is useful in cases where you have a collection of favorite windows that are almost always running. By adding these windows to a group, you can use GroupDeactivate to visit each window that isn't one of your favorites and decide whether to close it. This allows you to clean up your desktop much more quickly than doing it manually.
39 |GroupDeactivate selects windows in a manner similar to the Alt+Shift+Esc system hotkey. Specifically:
40 |Although the taskbar is skipped due to the WS_EX_TOPMOST style, it is activated if there are no other eligible windows and the active window matches the group.
49 |See GroupAdd for more details about window groups.
50 |GroupAdd, GroupActivate, GroupClose
52 |Activates the oldest window which is not a member of a window group.
55 |GroupDeactivate "MyFavoriteWindows" ; Visit non-favorite windows to clean up desktop.56 |
class Gui extends Object16 | 17 |
Provides an interface to create a window, add controls, modify the window, and retrieve information about the window. Such windows can be used as data entry forms or custom user interfaces.
18 |Gui objects can be created with Gui() and retrieved with GuiFromHwnd.
19 | 20 |"MyGui" is used below as a placeholder for any Gui object (and a variable name in examples), as "Gui" is the class itself.
21 |In addition to the methods and property inherited from Object, Gui objects have the following predefined methods and properties.
22 | 23 |Creates a new window.
79 |MyGui := Gui(Options, Title, EventObj) 80 | MyGui := Gui.Call(Options, Title, EventObj)81 |
Type: String
85 |Any of the options supported by Gui.Opt.
86 |Type: String
89 |If omitted, it defaults to A_ScriptName. Otherwise, specify the window title.
90 |Type: Object
93 |An "event sink", or object to bind events to. If EventObj is specified, OnEvent, OnNotify and OnCommand can be used to register methods of EventObj to be called when an event is raised.
94 |Type: Object
98 |This method or function returns a Gui object.
99 |Creates a new control and adds it to the window.
105 |GuiCtrl := MyGui.Add(ControlType , Options, Text) 106 | GuiCtrl := MyGui.AddControlType(Options, Text)107 |
Type: String
111 |This is one of the following: ActiveX, Button, CheckBox, ComboBox, Custom, DateTime, DropDownList (or DDL), Edit, GroupBox, Hotkey, Link, ListBox, ListView, MonthCal, Picture (or Pic), Progress, Radio, Slider, StatusBar, Tab, Tab2, Tab3, Text, TreeView, UpDown
112 |For example:
113 |MyGui := Gui() 114 | MyGui.Add("Text",, "Please enter your name:") 115 | MyGui.AddEdit("vName") 116 | MyGui.Show()
Type: String
119 |If blank or omitted, the control starts off at its defaults. Otherwise, specify one or more of the following options and styles, each separated from the next with one or more spaces or tabs.
120 |Positioning and Sizing of Controls
121 |If some dimensions and/or coordinates are omitted from Options, the control will be positioned relative to the previous control and/or sized automatically according to its nature and contents.
122 |The following options are supported:
123 |Rn: Rows of text (where n is any number, even a floating point number such as r2.5
). R is often preferable to specifying H (Height). If both the R and H options are present, R will take precedence. For a GroupBox, this setting is the number of controls for which to reserve space inside the box. For DropDownLists, ComboBoxes, and ListBoxes, it is the number of items visible at one time inside the list portion of the control (but it is often desirable to omit both the R and H options for DropDownList and ComboBox, as the popup list will automatically take advantage of the available height of the user's desktop). For other control types, R is the number of rows of text that can visibly fit inside the control.
Wn: Width (where n is any number in pixels). If omitted, the width is calculated automatically for some control types based on their contents; tab controls default to 30 times the current font size, plus 3 times the X-margin; vertical Progress Bars default to two times the current font size; and horizontal Progress Bars, horizontal Sliders, DropDownLists, ComboBoxes, ListBoxes, GroupBoxes, Edits, and Hotkeys default to 15 times the current font size (except GroupBoxes, which multiply by 18 to provide room inside for margins).
125 |Hn: Height (where n is any number in pixels). If both the H and R options are absent, DropDownLists, ComboBoxes, ListBoxes, and empty multi-line Edit controls default to 3 rows; GroupBoxes default to 2 rows; vertical Sliders and Progress Bars default to 5 rows; horizontal Sliders default to 30 pixels (except if a thickness has been specified); horizontal Progress Bars default to 2 times the current font size; Hotkey controls default to 1 row; and Tab controls default to 10 rows. For the other control types, the height is calculated automatically based on their contents. Note that for DropDownLists and ComboBoxes, H is the combined height of the control's always-visible portion and its list portion (but even if the height is set too low, at least one item will always be visible in the list). Also, for all types of controls, specifying the number of rows via the R option is usually preferable to using H because it prevents a control from showing partial/incomplete rows of text.
126 |WP±n, HP±n (where n is any number in pixels) can be used to set the width and/or height of a control equal to the previously added control's width or height, with an optional plus or minus adjustment. For example, wp
would set a control's width to that of the previous control, and wp-50
would set it equal to 50 less than that of the previous control.
Xn, Yn: X-position, Y-position (where n is any number in pixels). For example, specifying x0 y0
would position the control in the upper left corner of the window's client area, which is the area beneath the title bar and menu bar (if any).
X+n, Y+n (where n is any number in pixels): An optional plus sign can be included to position a control relative to the right or bottom edge (respectively) of the control that was previously added. For example, specifying y+10
would position the control 10 pixels beneath the bottom of the previous control rather than using the standard padding distance. Similarly, specifying x+10
would position the control 10 pixels to the right of the previous control's right edge. Since negative numbers such as x-10
are reserved for absolute positioning, to use a negative offset, include a plus sign in front of it. For example: x+-10
.
For X+ and Y+, the letter M can be used as a substitute for the window's current margin. For example, x+m
uses the right edge of the previous control plus the standard padding distance. xp y+m
positions a control below the previous control, whereas specifying a relative X coordinate on its own (with XP or X+) would normally imply yp
by default.
XP±n, YP±n (where n is any number in pixels) can be used to position controls relative to the previous control's upper left corner, which is often useful for enclosing controls in a GroupBox.
131 |XM±n and YM±n (where n is any number in pixels) can be used to position a control at the leftmost and topmost margins of the window, respectively, with an optional plus or minus adjustment.
132 |XS±n and YS±n (where n is any number in pixels): These are similar to XM and YM except that they refer to coordinates that were saved by having previously added a control with the word Section in its options (the first control of the window always starts a new section, even if that word isn't specified in its options). For example:
133 |MyGui := Gui() 134 | MyGui.Add("Edit", "w600") ; Add a fairly wide edit control at the top of the window. 135 | MyGui.Add("Text", "Section", "First Name:") ; Save this control's position and start a new section. 136 | MyGui.Add("Text",, "Last Name:") 137 | MyGui.Add("Edit", "ys") ; Start a new column within this section. 138 | MyGui.Add("Edit") 139 | MyGui.Show()140 |
XS and YS may optionally be followed by a plus/minus sign and a number. Also, it is possible to specify both the word Section and XS/YS in a control's options; this uses the previous section for itself but establishes a new section for subsequent controls.
141 |Omitting either X, Y or both is useful to make a GUI layout automatically adjust to any future changes you might make to the size of controls or font. By contrast, specifying an absolute position for every control might require you to manually shift the position of all controls that lie beneath and/or to the right of a control that is being enlarged or reduced.
142 |If both X and Y are omitted, the control will be positioned beneath the previous control using a standard padding distance (the current margin). Consecutive Text or Link controls are given additional vertical padding, so that they typically align better in cases where a column of Edit, DDL or similar-sized controls are later added to their right. To use only the standard vertical margin, specify y+m
or any value for X.
If only one component is omitted, its default value depends on which option was used to specify the other component:
144 |Specified X | Default for Y |
---|---|
Xn or XM | Beneath all previous controls (maximum Y extent plus margin). |
XS | Beneath all previous controls since the most recent use of the Section option. |
X+n or XP+nonzero | Same as the previous control's top edge (YP). |
XP or XP+0 | Below the previous control (bottom edge plus margin). |
Specified Y | Default for X |
Yn or YM | To the right of all previous controls (maximum X extent plus margin). |
YS | To the right of all previous controls since the most recent use of the Section option. |
Y+n or YP+nonzero | Same as the previous control's left edge (XP). |
YP or YP+0 | To the right of the previous control (right edge plus margin). |
Storing and Responding to User Input
158 |V: Sets the control's Name. Specify the name immediately after the letter V, which is not included in the name. For example, specifying vMyEdit
would name the control "MyEdit".
Events: Event handlers (such as a function which is called automatically when the user clicks or changes a control) cannot be set within the control's Options. Instead, OnEvent can be used to register a callback function or method for each event of interest.
160 | 161 |Common Options and Styles for Controls
162 |Note: In the absence of a preceding sign, a plus sign is assumed; for example, Wrap
is the same as +Wrap
. By contrast, -Wrap
would remove the word-wrapping property.
AltSubmit: Uses alternate submit method. For DropDownList, ComboBox, ListBox and Tab, this causes Gui.Submit to store the position of the selected item rather than its text. If no item is selected, a ComboBox will still store the text of its edit field.
164 |C: Color of text (has no effect on buttons and status bars). Specify the letter C followed immediately by a color name (see color chart) or RGB value (the 0x prefix is optional). Examples: cRed
, cFF2211
, c0xFF2211
, cDefault
.
Disabled: Makes an input-capable control appear in a disabled state, which prevents the user from focusing or modifying its contents. Use GuiControl.Enabled to enable it later. Note: To make an Edit control read-only, specify the string ReadOnly
instead. Also, the word Disabled may optionally be followed immediately by a 0 or 1 to indicate the starting state (0 for enabled and 1 for disabled). In other words, Disabled
and "Disabled" VarContainingOne
are the same.
Hidden: The control is initially invisible. Use GuiControl.Visible to show it later. The word Hidden may optionally be followed immediately by a 0 or 1 to indicate the starting state (0 for visible and 1 for hidden). In other words, Hidden
and "Hidden" VarContainingOne
are the same.
Left: Left-justifies the control's text within its available width. This option affects the following controls: Text, Edit, Button, CheckBox, Radio, UpDown, Slider, Tab, Tab2, GroupBox, DateTime.
168 |Right: Right-justifies the control's text within its available width. For checkboxes and radio buttons, this also puts the box itself on the right side of the control rather than the left. This option affects the following controls: Text, Edit, Button, CheckBox, Radio, UpDown, Slider, Tab, Tab2, GroupBox, DateTime, Link.
169 |Center: Centers the control's text within its available width. This option affects the following controls: Text, Edit, Button, CheckBox, Radio, Slider, GroupBox.
170 |Section: Starts a new section and saves this control's position for later use with the XS and YS positioning options described above.
171 |Tabstop: Use -Tabstop
(minus Tabstop) to have an input-capable control skipped over when the user presses Tab to navigate.
Wrap: Enables word-wrapping of the control's contents within its available width. Since nearly all control types start off with word-wrapping enabled, use -Wrap
to disable word-wrapping.
VScroll: Provides a vertical scroll bar if appropriate for this type of control.
174 |HScroll: Provides a horizontal scroll bar if appropriate for this type of control. The rest of this paragraph applies to ListBox only. The horizontal scrolling width defaults to 3 times the width of the ListBox. To specify a different scrolling width, include a number immediately after the word HScroll. For example, HScroll500
would allow 500 pixels of scrolling inside the ListBox. However, if the specified scrolling width is smaller than the width of the ListBox, no scroll bar will be shown (though the mere presence of HScroll
makes it possible for the horizontal scroll bar to be added later via MyScrollBar.Opt("+HScroll500")
, which is otherwise impossible).
Uncommon Options and Styles for Controls
177 |BackgroundTrans: Uses a transparent background, which allows any control that lies behind a Text, Picture, or GroupBox control to show through. For example, a transparent Text control displayed on top of a Picture control would make the text appear to be part of the picture. Use GuiCtrl.Opt("+Background")
to remove this option later. See Picture control's AltSubmit section for more information about transparent images. Known limitation: BackgroundTrans might not work properly for controls inside a Tab control that contains a ListView. If a control type does not support this option, an error is thrown.
BackgroundColor: Changes the background color of the control. Replace Color with a color name (see color chart) or RGB value (the 0x prefix is optional). Examples: BackgroundSilver
, BackgroundFFDD99
. If this option is not used, or if +Background
is used with no suffix, a Text, Picture, GroupBox, CheckBox, Radio, Slider, Tab or Link control uses the background color set by Gui.BackColor (or if none or other control type, the system's default background color). Specifying BackgroundDefault
or -Background
applies the system's default background color. For example, a control can be restored to the system's default color via LV.Opt("+BackgroundDefault")
. If a control type does not support this option, an error is thrown.
Border: Provides a thin-line border around the control. Most controls do not need this because they already have a type-specific border. When adding a border to an existing control, it might be necessary to increase the control's width and height by 1 pixel.
180 |Redraw: When used with GuiControl.Opt, this option enables or disables redraw (visual updates) for a control by sending it a WM_SETREDRAW message. See Redraw for more details.
181 |Theme: This option can be used to override the window's current theme setting for the newly created control. It has no effect when used on an existing control; however, this may change in a future version. See GUI's +/-Theme option for details.
182 |(Unnamed Style): Specify a plus or minus sign followed immediately by a decimal or hexadecimal style number. If the sign is omitted, a plus sign is assumed.
183 |(Unnamed ExStyle): Specify a plus or minus sign followed immediately by the letter E and a decimal or hexadecimal extended style number. If the sign is omitted, a plus sign is assumed. For example, E0x200
would add the WS_EX_CLIENTEDGE style, which provides a border with a sunken edge that might be appropriate for pictures and other controls. For other extended styles not documented here (since they are rarely used), see Extended Window Styles | Microsoft Docs for a complete list.
Type: Object
188 |This method returns a GuiControl object.
189 |Removes the window and all its controls, freeing the corresponding memory and system resources.
194 |MyGui.Destroy()
195 | If MyGui.Destroy()
is not used, the window is automatically destroyed when the Gui object is deleted (see General Remarks for details). All GUI windows are automatically destroyed when the script exits.
Blinks the window's button in the taskbar.
201 |MyGui.Flash(Blink)202 |
Type: Boolean
206 |If omitted, it defaults to true.
207 |If true, the window's button in the taskbar will blink. This is done by inverting the color of the window's title bar and/or taskbar button (if it has one).
208 |If false, the original colors of the title bar and taskbar button will be restored (but the actual behavior might vary depending on OS version).
209 |In the below example, the window will blink three times because each pair of flashes inverts then restores its appearance:
213 |Loop 6 214 | { 215 | MyGui.Flash() 216 | Sleep 500 ; It's quite sensitive to this value; altering it may change the behavior in unexpected ways. 217 | }218 |
Retrieves the position and size of the window's client area.
223 |MyGui.GetClientPos(&X, &Y, &Width, &Height)224 |
Type: VarRef
229 |If omitted, the corresponding values will not be stored. Otherwise, specify references to the output variables in which to store the X and Y coordinates of the client area's upper left corner.
230 |Type: VarRef
234 |If omitted, the corresponding values will not be stored. Otherwise, specify references to the output variables in which to store the width and height of the client area.
235 |Width is the horizontal distance between the left and right side of the client area, and height the vertical distance between the top and bottom side (in pixels).
236 |The client area is the part of the window which can contain controls. It excludes the window's title bar, menu (if it has a standard one) and borders. The position and size of the client area are less dependent on OS version and theme than the values returned by Gui.GetPos.
240 |Unlike WinGetClientPos, this method applies DPI scaling to Width and Height (unless the -DPIScale
option was used).
Retrieves the position and size of the window.
246 |MyGui.GetPos(&X, &Y, &Width, &Height)247 |
Type: VarRef
252 |If omitted, the corresponding values will not be stored. Otherwise, specify references to the output variables in which to store the X and Y coordinates of the window's upper left corner, in screen coordinates.
253 |Type: VarRef
257 |If omitted, the corresponding values will not be stored. Otherwise, specify references to the output variables in which to store the width and height of the window.
258 |Width is the horizontal distance between the left and right side of the window, and height the vertical distance between the top and bottom side (in pixels).
259 |As the coordinates returned by this method include the window's title bar, menu and borders, they may be dependent on OS version and theme. To get more consistent values across different systems, consider using Gui.GetClientPos instead.
263 |Unlike WinGetPos, this method applies DPI scaling to Width and Height (unless the -DPIScale
option was used).
Hides the window.
269 |MyGui.Hide()
270 | Unhides the window (if necessary) and maximizes it.
275 |MyGui.Maximize()
276 | Unhides the window (if necessary) and minimizes it.
281 |MyGui.Minimize()
282 | Moves and/or resizes the window.
287 |MyGui.Move(X, Y, Width, Height)288 |
Type: Integer
293 |If either is omitted, the position in that dimension will not be changed. Otherwise, specify the X and Y coordinates of the upper left corner of the window's new location, in screen coordinates.
294 |Type: Integer
298 |If either is omitted, the size in that dimension will not be changed. Otherwise, specify the new width and height of the window (in pixels).
299 |Unlike WinMove, this method applies DPI scaling to Width and Height (unless the -DPIScale
option was used).
MyGui.Move(10, 20, 200, 100) 305 | MyGui.Move(VarX+10, VarY+5, VarW*2, VarH*1.5) 306 | 307 | ; Expand the left and right side by 10 pixels. 308 | MyGui.GetPos(&x,, &w) 309 | MyGui.Move(x-10,, w+20)310 |
Registers a function or method to be called when the given event is raised.
315 |MyGui.OnEvent(EventName, Callback , AddRemove)316 |
See OnEvent for details.
317 |Sets various options and styles for the appearance and behavior of the window.
322 |MyGui.Opt(Options)
323 | Type: String
327 |Zero or more of the following options and styles, each separated from the next with one or more spaces or tabs.
328 |For performance reasons, it is better to set all options in a single line, and to do so before creating the window (that is, before any use of other methods such as Gui.Add).
329 |The effect of this parameter is cumulative; that is, it alters only those settings that are explicitly specified, leaving all the others unchanged.
330 |Specify a plus sign to add the option and a minus sign to remove it. For example: MyGui.Opt("+Resize -MaximizeBox")
.
AlwaysOnTop: Makes the window stay on top of all other windows, which is the same effect as WinSetAlwaysOnTop.
332 |Border: Provides a thin-line border around the window. This is not common.
333 |Caption (present by default): Provides a title bar and a thick window border/edge. When removing the caption from a window that will use WinSetTransColor, remove it only after setting the TransColor.
334 |Disabled: Disables the window, which prevents the user from interacting with its controls. This is often used on a window that owns other windows (see Owner).
335 |DPIScale: Use MyGui.Opt("-DPIScale")
to disable DPI scaling, which is enabled by default. If DPI scaling is enabled, coordinates and sizes passed to or retrieved from the Gui and GuiControl methods/properties are automatically scaled based on screen DPI. For example, with a DPI of 144 (150 %), MyGui.Show("w100")
would make the Gui 150 (100 * 1.5) pixels wide, and resizing the window to 200 pixels wide via the mouse or WinMove would cause MyGui.GetClientPos(,,&W)
to set W to 133 (200 // 1.5). A_ScreenDPI contains the system's current DPI.
DPI scaling only applies to the Gui and GuiControl methods/properties, so coordinates coming directly from other sources such as ControlGetPos or WinGetPos will not work. There are a number of ways to deal with this:
337 |MyGui.Opt("+DPIScale")
) and disable (MyGui.Opt("-DPIScale")
) scaling on the fly, as needed. Changing the setting does not affect positions or sizes which have already been set.x*(A_ScreenDPI/96)
converts x from logical/GUI coordinates to physical/non-GUI coordinates.LastFound: Sets the window to be the last found window (though this is unnecessary in a GUI thread because it is done automatically), which allows functions such as WinGetStyle and WinSetTransparent to operate on it even if it is hidden (that is, DetectHiddenWindows is not necessary). This is especially useful for changing the properties of the window before showing it. For example:
343 |MyGui.Opt("+LastFound") 344 | WinSetTransColor(CustomColor " 150") 345 | MyGui.Show()346 |
MaximizeBox: Enables the maximize button in the title bar. This is also included as part of Resize below.
347 |MinimizeBox (present by default): Enables the minimize button in the title bar.
348 |MinSize and MaxSize: Determines the minimum and/or maximum size of the window, such as when the user drags its edges to resize it. Specify +MinSize
and/or +MaxSize
(i.e. without suffix) to use the window's current size as the limit (if the window has no current size, it will use the size from the first use of Gui.Show). Alternatively, append the width, followed by an X, followed by the height; for example: MyGui.Opt("+Resize +MinSize640x480")
. The dimensions are in pixels, and they specify the size of the window's client area (which excludes borders, title bar, and menu bar). Specify each number as decimal, not hexadecimal.
Either the width or the height may be omitted to leave it unchanged (e.g. +MinSize640x
or +MinSizex480
). Furthermore, Min/MaxSize can be specified more than once to use the window's current size for one dimension and an explicit size for the other. For example, +MinSize +MinSize640x
would use the window's current size for the height and 640 for the width.
If MinSize and MaxSize are never used, the operating system's defaults are used (similarly, MyGui.Opt("-MinSize -MaxSize")
can be used to return to the defaults). Note: the window must have +Resize to allow resizing by the user.
OwnDialogs: MyGui.Opt("+OwnDialogs")
should be specified in each thread (such as a event handling function of a Button control) for which subsequently displayed MsgBox, InputBox, FileSelect, and DirSelect dialogs should be owned by the window. Such dialogs are modal, meaning that the user cannot interact with the GUI window until dismissing the dialog. By contrast, ToolTip windows do not become modal even though they become owned; they will merely stay always on top of their owner. In either case, any owned dialog or window is automatically destroyed when its GUI window is destroyed.
There is typically no need to turn this setting back off because it does not affect other threads. However, if a thread needs to display both owned and unowned dialogs, it may turn off this setting via MyGui.Opt("-OwnDialogs")
.
Owner: Use +Owner
to make the window owned by another. An owned window has no taskbar button by default, and when visible it is always on top of its owner. It is also automatically destroyed when its owner is destroyed, as long as the owner was created by the same script (i.e. has the same process ID). +Owner
can be used before or after the owned window is created. There are two ways to use +Owner
, as shown below:
MyGui.Opt("+Owner" OtherGui.Hwnd) ; Make the GUI owned by OtherGui. 355 | MyGui.Opt("+Owner") ; Make the GUI owned by the script's main window to prevent display of a taskbar button.356 |
+Owner
can be immediately followed by the HWND of any top-level window.
To prevent the user from interacting with the owner while one of its owned window is visible, disable the owner via MyGui.Opt("+Disabled")
. Later (when the time comes to cancel or destroy the owned window), re-enable the owner via MyGui.Opt("-Disabled")
. Do this prior to cancel/destroy so that the owner will be reactivated automatically.
Parent: Use +Parent
immediately followed by the HWND of any window or control to use it as the parent of this window. To convert the GUI back into a top-level window, use -Parent
. This option works even after the window is created. Known limitations:
+Parent
option from working on an existing window if the new parent is always-on-top and the child window is not.+Parent
option may fail during GUI creation if the parent window is external, but may work after the GUI is created. This is due to differences in how styles are applied.Resize: Makes the window resizable and enables its maximize button in the title bar. To avoid enabling the maximize button, specify +Resize -MaximizeBox
.
SysMenu (present by default): Specify -SysMenu
(minus SysMenu) to omit the system menu and icon in the window's upper left corner. This will also omit the minimize, maximize, and close buttons in the title bar.
Theme: By specifying -Theme
, all subsequently created controls in the window will have the Classic Theme appearance. To later create additional controls that obey the current theme, turn it back on via +Theme
. Note: This option has no effect if the Classic Theme is in effect. Finally, this setting may be changed for an individual control by specifying +Theme
or -Theme
in its options when it is created.
ToolWindow: Provides a narrower title bar but the window will have no taskbar button. This always hides the maximize and minimize buttons, regardless of whether the WS_MAXIMIZEBOX and WS_MINIMIZEBOX styles are present.
367 |(Unnamed Style): Specify a plus or minus sign followed immediately by a decimal or hexadecimal style number.
368 |(Unnamed ExStyle): Specify a plus or minus sign followed immediately by the letter E and a decimal or hexadecimal extended style number. For example, +E0x40000
would add the WS_EX_APPWINDOW style, which provides a taskbar button for a window that would otherwise lack one. For other extended styles not documented here (since they are rarely used), see Extended Window Styles | Microsoft Docs for a complete list.
Unhides the window (if necessary) and unminimizes or unmaximizes it.
375 |MyGui.Restore()
376 | Sets the font typeface, size, style, and/or color for controls added to the window from this point onward.
381 |MyGui.SetFont(Options, FontName)382 |
Type: String
386 |Zero or more options. Each option is either a single letter immediately followed by a value, or a single word. To specify more than one option, include a space between each. For example: cBlue s12 bold
.
The following words are supported: bold, italic, strike, underline, and norm. Norm returns the font to normal weight/boldness and turns off italic, strike, and underline (but it retains the existing color and size). It is possible to use norm to turn off all attributes and then selectively turn on others. For example, specifying norm italic
would set the font to normal then to italic.
C: Color name (see color chart) or RGB value -- or specify the word Default to return to the system's default color (black on most systems). Example values: cRed
, cFFFFAA
, cDefault
. Note: Buttons and status bars do not obey custom colors. Also, an individual control can be created with a font color other than the current one by including the C option. For example: MyGui.Add("Text", "cRed", "My Text")
.
S: Size (in points). For example: s12
(specify decimal, not hexadecimal)
W: Weight (boldness), which is a number between 1 and 1000 (400 is normal and 700 is bold). For example: w600
(specify decimal, not hexadecimal)
Q: Text rendering quality. For example: q3
. Q should be followed by a number from the following table:
Number | 395 |Windows Constant | 396 |Description | 397 |
---|---|---|
0 | 400 |DEFAULT_QUALITY | 401 |Appearance of the font does not matter. | 402 |
1 | 405 |DRAFT_QUALITY | 406 |Appearance of the font is less important than when the PROOF_QUALITY value is used. | 407 |
2 | 410 |PROOF_QUALITY | 411 |Character quality of the font is more important than exact matching of the logical-font attributes. | 412 |
3 | 415 |NONANTIALIASED_QUALITY | 416 |Font is never antialiased, that is, font smoothing is not done. | 417 |
4 | 420 |ANTIALIASED_QUALITY | 421 |Font is antialiased, or smoothed, if the font supports it and the size of the font is not too small or too large. | 422 |
5 | 425 |CLEARTYPE_QUALITY | 426 |If set, text is rendered (when possible) using ClearType antialiasing method. | 427 |
For more details of what these values mean, see Microsoft Docs: CreateFont.
430 |Since the highest quality setting is usually the default, this feature is more typically used to disable anti-aliasing in specific cases where doing so makes the text clearer.
Type: String
433 |FontName may be the name of any font, such as one from the font table. If FontName is omitted or does not exist on the system, the previous font's typeface will be used (or if none, the system's default GUI typeface). This behavior is useful to make a GUI window have a similar font on multiple systems, even if some of those systems lack the preferred font. For example, by using the following methods in order, Verdana will be given preference over Arial, which in turn is given preference over MS Sans Serif:
434 |MyGui.SetFont(, "MS Sans Serif") 435 | MyGui.SetFont(, "Arial") 436 | MyGui.SetFont(, "Verdana") ; Preferred font.
Omit both parameters to restore the font to the system's default GUI typeface, size, and color. Otherwise, any font attributes which are not specified will be copied from the previous font.
440 |On a related note, the operating system offers standard dialog boxes that prompt the user to pick a font, color, or icon. These dialogs can be displayed via DllCall in combination with comdlg32\ChooseFont, comdlg32\ChooseColor, or shell32\PickIconDlg. Search the forums for examples.
441 |By default, this makes the window visible, unminimizes it (if necessary) and activates it.
446 |MyGui.Show(Options)447 |
Type: String
451 |Omit the X, Y, W, and H options below to have the window retain its previous size and position. If there is no previous position, the window will be auto-centered in one or both dimensions if the X and/or Y options mentioned below are absent. If there is no previous size, the window will be auto-sized according to the size and positions of the controls it contains.
452 |Zero or more of the following strings may be present in Options (specify each number as decimal, not hexadecimal):
453 |Wn: Specify for n the width (in pixels) of the window's client area (the client area excludes the window's borders, title bar, and menu bar).
454 |Hn: Specify for n the height of the window's client area, in pixels.
455 |Xn: Specify for n the window's X-position on the screen, in pixels. Position 0 is the leftmost column of pixels visible on the screen.
456 |Yn: Specify for n the window's Y-position on the screen, in pixels. Position 0 is the topmost row of pixels visible on the screen.
457 |Center: Centers the window horizontally and vertically on the screen.
458 |xCenter: Centers the window horizontally on the screen. For example: MyGui.Show("xCenter y0")
.
yCenter: Centers the window vertically on the screen.
460 |AutoSize: Resizes the window to accommodate only its currently visible controls. This is useful to resize the window after new controls are added, or existing controls are resized, hidden, or unhidden. For example: MyGui.Show("AutoSize Center")
.
One of the following may also be present:
462 |Minimize: Minimizes the window and activates the one beneath it.
463 |Maximize: Maximizes and activates the window.
464 |Restore: Unminimizes or unmaximizes the window, if necessary. The window is also shown and activated, if necessary.
465 |NoActivate: Unminimizes or unmaximizes the window, if necessary. The window is also shown without activating it.
466 |NA: Shows the window without activating it. If the window is minimized, it will stay that way but will probably rise higher in the z-order (which is the order seen in the alt-tab selector). If the window was previously hidden, this will probably cause it to appear on top of the active window even though the active window is not deactivated.
467 |Hide: Hides the window and activates the one beneath it. This is identical in function to Gui.Hide except that it allows a hidden window to be moved or resized without showing it. For example: MyGui.Show("Hide x55 y66 w300 h200")
.
Collects the values from named controls and composes them into an Object. Optionally hides the window.
474 |NamedCtrlValues := MyGui.Submit(Hide)475 |
Type: Boolean
479 |If omitted, it defaults to true.
480 |If true, the window will be hidden.
481 |If false, the window will not be hidden.
482 |Type: Object
486 |This method returns an object that contains one own property per named control, like NamedCtrlValues.%GuiCtrl.Name% := GuiCtrl.Value
, with the exceptions noted below. Only input-capable controls which support GuiControl.Value and have been given a name are included. Use NamedCtrlValues.NameOfControl
to retrieve an individual value or OwnProps to enumerate them all.
For DropDownList, ComboBox, ListBox and Tab, the text of the selected item/tab is stored instead of its position number if the control lacks the AltSubmit option, or if the ComboBox's text does not match a list item. Otherwise, Value (the item's position number) is stored.
488 |If only one Radio button in a radio group has a name, Submit stores the number of the currently selected button instead of the control's Value. 1 is the first radio button (according to original creation order), 2 is the second, and so on. If there is no button selected, 0 is stored.
489 |Excluded because they are not input-capable: Text, Pic, GroupBox, Button, Progress, Link, StatusBar.
490 | 491 |Enumerates the window's controls.
496 |For Ctrl in MyGui497 |
For Hwnd, Ctrl in MyGui498 |
Returns a new enumerator. This method is typically not called directly. Instead, the Gui object is passed directly to a for-loop, which calls __Enum once and then calls the enumerator once for each iteration of the loop. Each call to the enumerator returns the next control. The for-loop's variables correspond to the enumerator's parameters, which are:
499 |Type: Integer
503 |The control's HWND. This is present only in the two-parameter mode.
504 |Type: Object
508 |The control's GuiControl object.
509 |For example:
512 |For Hwnd, GuiCtrlObj in MyGui 513 | MsgBox "Control #" A_Index " is " GuiCtrlObj.ClassNN514 |
Constructs a new Gui instance.
519 |MyGui.__New(Options, Title, EventObj)520 |
A Gui subclass may override __New and call super.__New(Options, Title, this)
to handle its own events. In such cases, events for the main window (such as Close) do not pass an explicit Gui parameter, as this
already contains a reference to the Gui.
The Gui retains a reference to EventObj for the purpose of calling event handlers, and releases it when the window is destroyed. If EventObj itself contains a reference to the Gui, this would typically create a circular reference which prevents the Gui from being automatically destroyed. However, an exception is made for when EventObj is the Gui itself, to avoid a circular reference in that case.
522 |An exception is thrown if the window has already been constructed or destroyed.
523 |Retrieves or sets the background color of the window.
529 |CurrentColor := MyGui.BackColor
530 | MyGui.BackColor := NewColor
531 | CurrentColor is a 6-digit RGB value of the current color previously set by this property, or an empty string if the default color is being used.
532 |NewColor is one of the 16 primary HTML color names, a hexadecimal RGB color value (the 0x prefix is optional), a pure numeric RGB color value, or the word Default (or an empty string) for its default color. Example values: "Silver"
, "FFFFAA"
, 0xFFFFAA
, "Default"
, ""
.
By default, the window's background color is the system's color for the face of buttons.
534 |The color of the menu bar and its submenus can be changed as in this example: MyMenuBar.SetColor "White"
.
To make the background transparent, use WinSetTransColor. However, if you do this without first having assigned a custom window via Gui.BackColor, buttons will also become transparent. To prevent this, first assign a custom color and then make that color transparent. For example:
536 |MyGui.BackColor := "EEAA99" 537 | WinSetTransColor("EEAA99", MyGui)538 |
To additionally remove the border and title bar from a window with a transparent background, use the following: MyGui.Opt("-Caption")
To illustrate the above, there is an example of an on-screen display (OSD) near the bottom of this page.
540 |Retrieves the GuiControl object of the window's focused control.
545 |GuiCtrlObj := MyGui.FocusedCtrl
546 | Note: To be effective, the window generally must not be minimized or hidden.
547 |Retrieves the window handle (HWND) of the window.
552 |CurrentHwnd := MyGui.Hwnd
553 | A GUI's HWND is often used with PostMessage, SendMessage, and DllCall. It can also be used directly in a WinTitle parameter.
Retrieves or sets the size of horizontal margins between sides and subsequently created controls.
558 |CurrentValue := MyGui.MarginX
559 | MyGui.MarginX := NewValue
560 | CurrentValue is the number of pixels of the current horizontal margin.
561 |NewValue is the number of pixels of space to leave at the left and right side of the window when auto-positioning any control that lacks an explicit X coordinate. Also, the margin is used to determine the horizontal distance that separates auto-positioned controls from each other. Finally, the margin is taken into account by the first use of Gui.Show to calculate the window's size (when no explicit size is specified).
562 |If not set by the script, MarginX acquires a default value of 1.25 times the current font's height the first time Gui.Add or Gui.Show is called or Gui.MarginX or Gui.MarginY is retrieved (whichever occurs first).
563 |Retrieves or sets the size of vertical margins between sides and subsequently created controls.
568 |CurrentValue := MyGui.MarginY
569 | MyGui.MarginY := NewValue
570 | CurrentValue is the number of pixels of the current vertical margin.
571 |NewValue is the number of pixels of space to leave at the top and bottom side of the window when auto-positioning any control that lacks an explicit Y coordinate. Also, the margin is used to determine the vertical distance that separates auto-positioned controls from each other. Finally, the margin is taken into account by the first use of Gui.Show to calculate the window's size (when no explicit size is specified).
572 |If not set by the script, MarginY acquires a default value of 0.75 times the current font's height the first time Gui.Add or Gui.Show is called or Gui.MarginX or Gui.MarginY is retrieved (whichever occurs first).
573 |Retrieves or sets the window's menu bar.
578 |CurrentBar := MyGui.MenuBar
579 | MyGui.MenuBar := NewBar
580 | CurrentBar and NewBar are a MenuBar object created by MenuBar(). For example:
581 |FileMenu := Menu() 582 | FileMenu.Add("&Open`tCtrl+O", (*) => FileSelect()) ; See remarks below about Ctrl+O. 583 | FileMenu.Add("E&xit", (*) => ExitApp()) 584 | HelpMenu := Menu() 585 | HelpMenu.Add("&About", (*) => MsgBox("Not implemented")) 586 | Menus := MenuBar() 587 | Menus.Add("&File", FileMenu) ; Attach the two submenus that were created above. 588 | Menus.Add("&Help", HelpMenu) 589 | MyGui := Gui() 590 | MyGui.MenuBar := Menus 591 | MyGui.Show("w300 h200")592 |
In the first line above, notice that &Open
is followed by Ctrl+O
(with a tab character in between). This indicates a keyboard shortcut that the user may press instead of selecting the menu item. If the shortcut uses only the standard modifier key names Ctrl, Alt and Shift, it is automatically registered as a keyboard accelerator for the GUI. Single-character accelerators with no modifiers are case-sensitive and can be triggered by unusual means such as IME or Alt+NNNN.
If a particular key combination does not work automatically, the use of a context-sensitive hotkey may be required. However, such hotkeys typically cannot be triggered by Send and are more likely to interfere with other scripts than a standard keyboard accelerator.
594 |To remove a window's current menu bar, use MyGui.MenuBar := ""
(that is, assign an empty string).
Retrieves or sets a custom name for the window.
600 |CurrentName := MyGui.Name
601 | MyGui.Name := NewName
602 | Retrieves or sets the window's title.
607 |CurrentTitle := MyGui.Title
608 | MyGui.Title := NewTitle
609 | Retrieves the GuiControl object associated with the specified name, text, ClassNN or HWND.
614 |GuiCtrlObj := MyGui[Name]
615 | GuiCtrlObj := MyGui.__Item[Name]
616 | A GUI window may be navigated via Tab, which moves keyboard focus to the next input-capable control (controls from which the Tabstop style has been removed are skipped). The order of navigation is determined by the order in which the controls were originally added. When the window is shown for the first time, the first input-capable control that has the Tabstop style (which most control types have by default) will have keyboard focus, unless that control is a Button and there is a Default button, in which case the latter is focused instead.
620 |Certain controls may contain an ampersand (&) to create a keyboard shortcut, which might be displayed in the control's text as an underlined character (depending on system settings). A user activates the shortcut by holding down Alt then typing the corresponding character. For buttons, checkboxes, and radio buttons, pressing the shortcut is the same as clicking the control. For GroupBoxes and Text controls, pressing the shortcut causes keyboard focus to jump to the first input-capable tabstop control that was created after it. However, if more than one control has the same shortcut key, pressing the shortcut will alternate keyboard focus among all controls with the same shortcut.
621 |To display a literal ampersand inside the control types mentioned above, specify two consecutive ampersands as in this example: MyGui.Add("Button",, "Save && Exit")
.
For its icon, a GUI window uses the tray icon that was in effect at the time the window was created. Thus, to have a different icon, change the tray icon before creating the window. For example: TraySetIcon("MyIcon.ico")
. It is also possible to have a different large icon for a window than its small icon (the large icon is displayed in the alt-tab task switcher). This can be done via LoadPicture and SendMessage; for example:
iconsize := 32 ; Ideal size for alt-tab varies between systems and OS versions. 626 | hIcon := LoadPicture("My Icon.ico", "Icon1 w" iconsize " h" iconsize, &imgtype) 627 | MyGui := Gui() 628 | SendMessage(0x0080, 1, hIcon, MyGui) ; 0x0080 is WM_SETICON; and 1 means ICON_BIG (vs. 0 for ICON_SMALL). 629 | MyGui.Show()630 |
Due to OS limitations, Checkboxes, Radio buttons, and GroupBoxes for which a non-default text color was specified will take on the Classic Theme appearance.
631 |Related topic: window's margin.
632 | 633 |Use the GuiControl object to operate upon individual controls in a GUI window.
635 |Each GUI window may have up to 11,000 controls. However, use caution when creating more than 5000 controls because system instability may occur for certain control types.
636 |The GUI window is automatically destroyed when the Gui object is deleted, which occurs when its reference count reaches zero. However, this does not typically occur while the window is visible, as Show automatically increments the reference count. While the window is visible, the user can interact with it and raise events which are handled by the script. When the user closes the window or it is hidden by Hide, Show or Submit, this extra reference is released.
637 |To keep a GUI window "alive" without calling Show or retaining a reference to its Gui object, the script can increment the object's reference count with ObjAddRef (in which case ObjRelease must be called when the window is no longer needed). For example, this might be done when using a hidden GUI window to receive messages, or if the window is shown by "external" means such as WinShow (by this script or any other).
638 |If the script is not persistent for any other reason, it will exit after the last visible GUI is closed; either when the last thread completes or immediately if no threads are running.
639 | 640 |GuiControl object, GuiFromHwnd, GuiCtrlFromHwnd, Control Types, ListView, TreeView, Menu object, Control functions, MsgBox, FileSelect, DirSelect
642 | 643 |MyGui := Gui(, "Title of Window") 648 | MyGui.Opt("+AlwaysOnTop +Disabled -SysMenu +Owner") ; +Owner avoids a taskbar button. 649 | MyGui.Add("Text",, "Some text to display.") 650 | MyGui.Show("NoActivate") ; NoActivate avoids deactivating the currently active window.651 |
Creates a simple input-box that asks for the first and last name.
655 |MyGui := Gui(, "Simple Input Example") 656 | MyGui.Add("Text",, "First name:") 657 | MyGui.Add("Text",, "Last name:") 658 | MyGui.Add("Edit", "vFirstName ym") ; The ym option starts a new column of controls. 659 | MyGui.Add("Edit", "vLastName") 660 | MyGui.Add("Button", "default", "OK").OnEvent("Click", ProcessUserInput) 661 | MyGui.OnEvent("Close", ProcessUserInput) 662 | MyGui.Show() 663 | 664 | ProcessUserInput(*) 665 | { 666 | Saved := MyGui.Submit() ; Save the contents of named controls into an object. 667 | MsgBox("You entered '" Saved.FirstName " " Saved.LastName "'.") 668 | }669 |
Creates a tab control with multiple tabs, each containing different controls to interact with.
673 |MyGui := Gui() 674 | Tab := MyGui.Add("Tab3",, ["First Tab", "Second Tab", "Third Tab"]) 675 | MyGui.Add("CheckBox", "vMyCheckBox", "Sample checkbox") 676 | Tab.UseTab(2) 677 | MyGui.Add("Radio", "vMyRadio", "Sample radio1") 678 | MyGui.Add("Radio",, "Sample radio2") 679 | Tab.UseTab(3) 680 | MyGui.Add("Edit", "vMyEdit r5") ; r5 means 5 rows tall. 681 | Tab.UseTab() ; i.e. subsequently-added controls will not belong to the tab control. 682 | Btn := MyGui.Add("Button", "default xm", "OK") ; xm puts it at the bottom left corner. 683 | Btn.OnEvent("Click", ProcessUserInput) 684 | MyGui.OnEvent("Close", ProcessUserInput) 685 | MyGui.OnEvent("Escape", ProcessUserInput) 686 | MyGui.Show() 687 | 688 | ProcessUserInput(*) 689 | { 690 | Saved := MyGui.Submit() ; Save the contents of named controls into an object. 691 | MsgBox("You entered:`n" Saved.MyCheckBox "`n" Saved.MyRadio "`n" Saved.MyEdit) 692 | }693 |
Creates a ListBox control containing files in a directory.
697 |MyGui := Gui() 698 | MyGui.Add("Text",, "Pick a file to launch from the list below.") 699 | LB := MyGui.Add("ListBox", "w640 r10") 700 | LB.OnEvent("DoubleClick", LaunchFile) 701 | Loop Files, "C:\*.*" ; Change this folder and wildcard pattern to suit your preferences. 702 | LB.Add([A_LoopFilePath]) 703 | MyGui.Add("Button", "Default", "OK").OnEvent("Click", LaunchFile) 704 | MyGui.Show() 705 | 706 | LaunchFile(*) 707 | { 708 | if MsgBox("Would you like to launch the file or document below?`n`n" LB.Text,, 4) = "No" 709 | return 710 | ; Otherwise, try to launch it: 711 | try Run(LB.Text) 712 | if A_LastError 713 | MsgBox("Could not launch the specified file. Perhaps it is not associated with anything.") 714 | }715 |
Displays a context-sensitive help (via ToolTip) whenever the user moves the mouse over a particular control.
719 |720 | MyGui := Gui() 721 | MyEdit := MyGui.Add("Edit") 722 | ; Store the tooltip text in a custom property: 723 | MyEdit.ToolTip := "This is a tooltip for the control whose name is MyEdit." 724 | MyDDL := MyGui.Add("DropDownList",, ["Red", "Green", "Blue"]) 725 | MyDDL.ToolTip := "Choose a color from the drop-down list." 726 | MyGui.Add("CheckBox",, "This control has no tooltip.") 727 | MyGui.Show() 728 | OnMessage(0x0200, On_WM_MOUSEMOVE) 729 | 730 | On_WM_MOUSEMOVE(wParam, lParam, msg, Hwnd) 731 | { 732 | static PrevHwnd := 0 733 | if (Hwnd != PrevHwnd) 734 | { 735 | Text := "", ToolTip() ; Turn off any previous tooltip. 736 | CurrControl := GuiCtrlFromHwnd(Hwnd) 737 | if CurrControl 738 | { 739 | if !CurrControl.HasProp("ToolTip") 740 | return ; No tooltip for this control. 741 | Text := CurrControl.ToolTip 742 | SetTimer () => ToolTip(Text), -1000 743 | SetTimer () => ToolTip(), -4000 ; Remove the tooltip. 744 | } 745 | PrevHwnd := Hwnd 746 | } 747 | }748 |
Creates an On-screen display (OSD) via transparent window.
752 |MyGui := Gui() 753 | MyGui.Opt("+AlwaysOnTop -Caption +ToolWindow") ; +ToolWindow avoids a taskbar button and an alt-tab menu item. 754 | MyGui.BackColor := "EEAA99" ; Can be any RGB color (it will be made transparent below). 755 | MyGui.SetFont("s32") ; Set a large font size (32-point). 756 | CoordText := MyGui.Add("Text", "cLime", "XXXXX YYYYY") ; XX & YY serve to auto-size the window. 757 | ; Make all pixels of this color transparent and make the text itself translucent (150): 758 | WinSetTransColor(MyGui.BackColor " 150", MyGui) 759 | SetTimer(UpdateOSD, 200) 760 | UpdateOSD() ; Make the first update immediate rather than waiting for the timer. 761 | MyGui.Show("x0 y400 NoActivate") ; NoActivate avoids deactivating the currently active window. 762 | 763 | UpdateOSD(*) 764 | { 765 | MouseGetPos &MouseX, &MouseY 766 | CoordText.Value := "X" MouseX ", Y" MouseY 767 | }768 |
Creates a moving progress bar overlayed on a background image.
772 |MyGui := Gui() 773 | MyGui.BackColor := "White" 774 | MyGui.Add("Picture", "x0 y0 h350 w450", A_WinDir "\Web\Wallpaper\Windows\img0.jpg") 775 | MyBtn := MyGui.Add("Button", "Default xp+20 yp+250", "Start the Bar Moving") 776 | MyBtn.OnEvent("Click", MoveBar) 777 | MyProgress := MyGui.Add("Progress", "w416") 778 | MyText := MyGui.Add("Text", "wp") ; wp means "use width of previous". 779 | MyGui.Show() 780 | 781 | MoveBar(*) 782 | { 783 | Loop Files, A_WinDir "\*.*", "R" 784 | { 785 | if (A_Index > 100) 786 | break 787 | MyProgress.Value := A_Index 788 | MyText.Value := A_LoopFileName 789 | Sleep 50 790 | } 791 | MyText.Value := "Bar finished." 792 | }793 |
Creates a simple image viewer.
797 |MyGui := Gui("+Resize") 798 | MyBtn := MyGui.Add("Button", "default", "&Load New Image") 799 | MyBtn.OnEvent("Click", LoadNewImage) 800 | MyRadio := MyGui.Add("Radio", "ym+5 x+10 checked", "Load &actual size") 801 | MyGui.Add("Radio", "ym+5 x+10", "Load to &fit screen") 802 | MyPic := MyGui.Add("Pic", "xm") 803 | MyGui.Show() 804 | 805 | LoadNewImage(*) 806 | { 807 | Image := FileSelect(,, "Select an image:", "Images (*.gif; *.jpg; *.bmp; *.png; *.tif; *.ico; *.cur; *.ani; *.exe; *.dll)") 808 | if Image = "" 809 | return 810 | if (MyRadio.Value) ; Display image at its actual size. 811 | { 812 | Width := 0 813 | Height := 0 814 | } 815 | else ; Second radio is selected: Resize the image to fit the screen. 816 | { 817 | Width := A_ScreenWidth - 28 ; Minus 28 to allow room for borders and margins inside. 818 | Height := -1 ; "Keep aspect ratio" seems best. 819 | } 820 | MyPic.Value := Format("*w{1} *h{2} {3}", Width, Height, Image) ; Load the image. 821 | MyGui.Title := Image 822 | MyGui.Show("xCenter y0 AutoSize") ; Resize the window to match the picture size. 823 | }824 |
Creates a simple text editor with menu bar.
828 |829 | ; Create the MyGui window: 830 | MyGui := Gui("+Resize", "Untitled") ; Make the window resizable. 831 | 832 | ; Create the submenus for the menu bar: 833 | FileMenu := Menu() 834 | FileMenu.Add("&New", MenuFileNew) 835 | FileMenu.Add("&Open", MenuFileOpen) 836 | FileMenu.Add("&Save", MenuFileSave) 837 | FileMenu.Add("Save &As", MenuFileSaveAs) 838 | FileMenu.Add() ; Separator line. 839 | FileMenu.Add("E&xit", MenuFileExit) 840 | HelpMenu := Menu() 841 | HelpMenu.Add("&About", MenuHelpAbout) 842 | 843 | ; Create the menu bar by attaching the submenus to it: 844 | MyMenuBar := MenuBar() 845 | MyMenuBar.Add("&File", FileMenu) 846 | MyMenuBar.Add("&Help", HelpMenu) 847 | 848 | ; Attach the menu bar to the window: 849 | MyGui.MenuBar := MyMenuBar 850 | 851 | ; Create the main Edit control: 852 | MainEdit := MyGui.Add("Edit", "WantTab W600 R20") 853 | 854 | ; Apply events: 855 | MyGui.OnEvent("DropFiles", Gui_DropFiles) 856 | MyGui.OnEvent("Size", Gui_Size) 857 | 858 | MenuFileNew() ; Apply default settings. 859 | MyGui.Show() ; Display the window. 860 | 861 | MenuFileNew(*) 862 | { 863 | MainEdit.Value := "" ; Clear the Edit control. 864 | FileMenu.Disable("3&") ; Gray out &Save. 865 | MyGui.Title := "Untitled" 866 | } 867 | 868 | MenuFileOpen(*) 869 | { 870 | MyGui.Opt("+OwnDialogs") ; Force the user to dismiss the FileSelect dialog before returning to the main window. 871 | SelectedFileName := FileSelect(3,, "Open File", "Text Documents (*.txt)") 872 | if SelectedFileName = "" ; No file selected. 873 | return 874 | global CurrentFileName := readContent(SelectedFileName) 875 | } 876 | 877 | MenuFileSave(*) 878 | { 879 | saveContent(CurrentFileName) 880 | } 881 | 882 | MenuFileSaveAs(*) 883 | { 884 | MyGui.Opt("+OwnDialogs") ; Force the user to dismiss the FileSelect dialog before returning to the main window. 885 | SelectedFileName := FileSelect("S16",, "Save File", "Text Documents (*.txt)") 886 | if SelectedFileName = "" ; No file selected. 887 | return 888 | global CurrentFileName := saveContent(SelectedFileName) 889 | } 890 | 891 | MenuFileExit(*) ; User chose "Exit" from the File menu. 892 | { 893 | WinClose() 894 | } 895 | 896 | MenuHelpAbout(*) 897 | { 898 | About := Gui("+owner" MyGui.Hwnd) ; Make the main window the owner of the "about box". 899 | MyGui.Opt("+Disabled") ; Disable main window. 900 | About.Add("Text",, "Text for about box.") 901 | About.Add("Button", "Default", "OK").OnEvent("Click", About_Close) 902 | About.OnEvent("Close", About_Close) 903 | About.OnEvent("Escape", About_Close) 904 | About.Show() 905 | 906 | About_Close(*) 907 | { 908 | MyGui.Opt("-Disabled") ; Re-enable the main window (must be done prior to the next step). 909 | About.Destroy() ; Destroy the about box. 910 | } 911 | } 912 | 913 | readContent(FileName) 914 | { 915 | try 916 | FileContent := FileRead(FileName) ; Read the file's contents into the variable. 917 | catch 918 | { 919 | MsgBox("Could not open '" FileName "'.") 920 | return 921 | } 922 | MainEdit.Value := FileContent ; Put the text into the control. 923 | FileMenu.Enable("3&") ; Re-enable &Save. 924 | MyGui.Title := FileName ; Show file name in title bar. 925 | return FileName 926 | } 927 | 928 | saveContent(FileName) 929 | { 930 | try 931 | { 932 | if FileExist(FileName) 933 | FileDelete(FileName) 934 | FileAppend(MainEdit.Value, FileName) ; Save the contents to the file. 935 | } 936 | catch 937 | { 938 | MsgBox("The attempt to overwrite '" FileName "' failed.") 939 | return 940 | } 941 | ; Upon success, Show file name in title bar (in case we were called by MenuFileSaveAs): 942 | MyGui.Title := FileName 943 | return FileName 944 | } 945 | 946 | Gui_DropFiles(thisGui, Ctrl, FileArray, *) ; Support drag & drop. 947 | { 948 | CurrentFileName := readContent(FileArray[1]) ; Read the first file only (in case there's more than one). 949 | } 950 | 951 | Gui_Size(thisGui, MinMax, Width, Height) 952 | { 953 | if MinMax = -1 ; The window has been minimized. No action needed. 954 | return 955 | ; Otherwise, the window has been resized or maximized. Resize the Edit control to match. 956 | MainEdit.Move(,, Width-20, Height-20) 957 | }958 |
Demonstrates problems caused by reference cycles.
962 |963 | ; Click Open or double-click tray icon to show another GUI. 964 | ; Use the menu items, Escape or Close button to see how it responds. 965 | A_TrayMenu.Add("&Open", ShowRefCycleGui) 966 | Persistent 967 | 968 | ShowRefCycleGui(*) { 969 | static n := 0 970 | g := Gui(, "GUI #" (++n)), g.n := n 971 | g.MenuBar := mb := MenuBar() ; g -> mb 972 | mb.Add("Gui", m := Menu()) ; mb -> m 973 | m.Add("Hide", (*) => g.Hide()) ; (*) -> g 974 | m.Add("Destroy", (*) => g.Destroy()) 975 | ; For a GUI event, the callback parameter can be used to avoid a 976 | ; reference cycle (using the same name prevents accidental capture). 977 | ; However, Hide() doesn't break the *other* reference cycles. 978 | g.OnEvent("Escape", (g, *) => g.Hide()) 979 | ; Capturing the variable can work out in our favour. 980 | g.OnEvent("Close", (*) => g := unset) 981 | g.Show("w300 h200") 982 | ; __Delete is not called due to the reference cycle: 983 | ; g -> mb -> m -> (*) -> g 984 | ; unless g is unset by triggering the Close event, 985 | ; or MenuBar and event handlers are released by Destroy. 986 | g.__Delete := this => MsgBox("GUI #" this.n " deleted") 987 | } 988 |989 |
class Gui.Control extends Object16 | 17 |
Provides an interface for modifying GUI controls and retrieving information about them. Gui.Add, Gui.__Item and GuiCtrlFromHwnd return an object of this type.
18 | 19 |"GuiCtrl" is used below as a placeholder for instances of the Gui.Control
class.
Gui.Control
serves as the base class for all GUI controls, but each type of control has its own class. Some of the following methods are defined by the prototype of the appropriate class, or the Gui.List
base class. See Built-in Classes for a full list.
In addition to the methods and property inherited from Object, GuiControl objects may have the following predefined methods and properties.
22 | 23 |Appends items to a multi-item control (ListBox, DropDownList, ComboBox, or Tab).
66 |GuiCtrl.Add(Items)
67 | Type: Array
71 |An array of strings to be inserted as items at the end of the control's list, e.g. ["Red", "Green", "Blue"]
.
To replace (overwrite) the list instead, use the Delete method beforehand. To select an item, use the Choose method.
76 |Selects an item in a multi-item control (ListBox, DropDownList, ComboBox, or Tab).
83 |GuiCtrl.Choose(Value)
84 | Specify 1 for the first item, 2 for the second, etc.
89 |If Value is a string (even a numeric string), the item whose leading name part matches Value will be selected. The search is not case-sensitive. For example, if the control contains the item "UNIX Text", specifying the word unix (lowercase) would be enough to select it. For a multi-select ListBox, all matching items are selected.
90 |If Value is zero or empty, the current selection is removed.
To select or deselect all items in a multi-select ListBox, follow this example:
94 |PostMessage 0x0185, 1, -1, ListBox ; Select all items. 0x0185 is LB_SETSEL. 95 | PostMessage 0x0185, 0, -1, ListBox ; Deselect all items. 96 | ListBox.Choose(0) ; Deselect all items.97 |
Unlike ControlChooseIndex, this method does not raise a Change or DoubleClick event.
98 |Deletes one or all items from a multi-item control (ListBox, DropDownList, ComboBox, or Tab).
103 |GuiCtrl.Delete(Value)104 |
Type: Integer
108 |If omitted, all items will be deleted. Otherwise, specify 1 for the first item, 2 for the second, etc.
109 |For Tab controls, a tab's sub-controls stay associated with their original tab number; that is, they are never associated with their tab's actual display-name. For this reason, renaming or removing a tab will not change the tab number to which the sub-controls belong. For example, if there are three tabs ["Red", "Green", "Blue"]
and the second tab is removed by means of MyTab.Delete(2)
, the sub-controls originally associated with Green will now be associated with Blue. Because of this behavior, only tabs at the end should generally be removed. Tabs that are removed in this way can be added back later, at which time they will reclaim their original set of controls.
Sets keyboard focus to the control.
120 |GuiCtrl.Focus()
121 | To be effective, the window generally must not be minimized or hidden.
122 |To retrieve the focus state of the control, use the Focused property.
123 |Retrieves the position and size of the control.
128 |GuiCtrl.GetPos(&X, &Y, &Width, &Height)129 |
Type: VarRef
134 |If omitted, the corresponding value will not be stored. Otherwise, specify references to the output variables in which to store the X and Y coordinates (in pixels) of the control's upper left corner. These coordinates are relative to the upper-left corner of the window's client area, which is the area not including title bar, menu bar, and borders.
135 |Type: VarRef
139 |If omitted, the corresponding value will not be stored. Otherwise, specify references to the output variables in which to store the control's width and height (in pixels).
140 |Unlike ControlGetPos, this method applies DPI scaling to the returned coordinates (unless the -DPIScale
option was used).
MyEdit.GetPos(&x, &y, &w, &h) 146 | MsgBox "The X coordinate is " x ". The Y coordinate is " y ". The width is " w ". The height is " h "." 147 |148 |
Moves and/or resizes the control.
153 |GuiCtrl.Move(X, Y, Width, Height)154 |
Type: Integer
159 |If either is omitted, the control's position in that dimension will not be changed. Otherwise, specify the X and Y coordinates (in pixels) of the upper left corner of the control's new location. The coordinates are relative to the upper-left corner of the window's client area, which is the area not including title bar, menu bar, and borders.
160 |Type: Integer
164 |If either is omitted, the control's size in that dimension will not be changed. Otherwise, specify the new width and height of the control (in pixels).
165 |Unlike ControlMove, this method applies DPI scaling to the coordinates (unless the -DPIScale
option was used).
MyEdit.Move(10, 20, 200, 100) 171 | MyEdit.Move(VarX+10, VarY+5, VarW*2, VarH*1.5)172 |
Registers a function or method to be called when a control notification is received via the WM_COMMAND message.
177 |GuiCtrl.OnCommand(NotifyCode, Callback , AddRemove)178 |
See OnCommand for details.
179 |Registers a function or method to be called when the given event is raised.
184 |GuiCtrl.OnEvent(EventName, Callback , AddRemove)185 |
See OnEvent for details.
186 |Registers a function or method to be called when a control notification is received via the WM_NOTIFY message.
191 |GuiCtrl.OnNotify(NotifyCode, Callback , AddRemove)192 |
See OnNotify for details.
193 |Sets various options and styles for the appearance and behavior of the control.
198 |GuiCtrl.Opt(Options)
199 | Type: String
203 |Specify one or more control-specific or general options and styles, each separated from the next with one or more spaces or tabs.
204 |In the following example, the control is disabled and its background is restored to the system default:
208 |MyEdit.Opt("+Disabled -Background")209 |
In the next example, the OK button is made the new default button:
210 |OKButton.Opt("+Default")211 |
Although styles and extended styles are also recognized, some of them cannot be applied or removed after a control has been created. Even if a change is successfully applied, the control might choose to ignore it.
212 |Redraws the region of the GUI window occupied by the control.
217 |GuiCtrl.Redraw()
218 | Although this may cause an unwanted flickering effect when called repeatedly and rapidly, it solves display artifacts for certain control types such as GroupBoxes.
219 |Sets the font typeface, size, style, and/or color for the control.
224 |GuiCtrl.SetFont(Options, FontName)225 |
Omit both parameters to set the font to the GUI's current font, as set by Gui.SetFont. Otherwise, any font attributes which are not specified will be copied from the control's previous font. Text color is changed only if specified in Options.
226 |For details about both parameters, see Gui.SetFont.
227 |Retrieves the class name and sequence number (ClassNN) of the control.
233 |ClassNN := GuiCtrl.ClassNN
234 | A control's ClassNN is the name of its window class followed by its sequence number within the top-level window which contains it. For example, "Edit1" is the first Edit control on a window and "Button12" is the twelth button.
235 |Related: ControlGetClassNN
236 |Retrieves or sets the interaction state of the control.
241 |CurrentSetting := GuiCtrl.Enabled
242 | GuiCtrl.Enabled := NewSetting
243 | CurrentSetting is NewSetting if assigned, otherwise 1 (true) by default unless overwritten by the Disabled option.
244 |NewSetting is a boolean value that enables or disables this setting. If true, the control is enabled. If false, the control is disabled.
245 |For Tab controls, this will also enable or disable all of the tab's sub-controls. However, any sub-control explicitly disabled via GuiCtrl.Enabled := false
will remember that setting and thus remain disabled even after its Tab control is re-enabled.
Retrieves the focus state of the control.
251 |IsFocused := GuiCtrl.Focused
252 | IsFocused is 1 (true) if the control has the keyboard focus, otherwise 0 (false).
253 |To be effective, the window generally must not be minimized or hidden.
254 |To focus the control, use the Focus method.
255 |Retrieves the Gui object of the control's parent window.
260 |GuiObj := GuiCtrl.Gui
261 | Retrieves the window handle (HWND) of the control.
266 |Hwnd := GuiCtrl.Hwnd
267 | A control's HWND is often used with PostMessage, SendMessage, and DllCall. It can also be used directly in a Control parameter.
268 |Retrieves or sets the explicit name of the control.
273 |CurrentName := GuiCtrl.Name
274 | GuiCtrl.Name := NewName
275 | CurrentName is NewName if assigned, otherwise an empty string by default unless overwritten by the V option.
276 |NewName is the control's new name, which can be used with Gui.__Item to retrieve the GuiControl object. For most input-capable controls, the name is also used by Gui.Submit.
277 |Retrieves or sets the text/caption of the control.
282 |CurrentText := GuiCtrl.Text
283 | GuiCtrl.Text := NewText
284 | Note: If the control has no visible caption text and no (single) text value, this property corresponds to the control's hidden caption text (like ControlGetText/ControlSetText).
285 |CurrentText and NewText depend on the control type:
286 | 287 |Button / CheckBox / Edit / GroupBox / Link / Radio / Text
288 |CurrentText and NewText are the caption/display text of the Button, CheckBox, Edit, GroupBox, Link, Radio or Text control. Since the control will not expand automatically, use GuiCtrl.Move(,, 300)
or similar if the control needs to be widened.
DateTime
291 |CurrentText and NewText are the formatted text displayed by the DateTime control. Assigning a formatted date/time string to the control is not supported. To change the date/time being displayed, assign the Value property a date-time stamp in YYYYMMDDHH24MISS format.
292 | 293 |DropDownList / ComboBox / ListBox / Tab
294 |CurrentText and NewText are the text of the currently selected item/tab of the DropDownList, ComboBox, ListBox or Tab control.
295 |NewText should be the full text (case-insensitive) of the item/tab to select.
296 |For a ComboBox, if there is no selected item, the text in the control's edit field is retrieved instead. For other controls, CurrentText is empty/blank. Similarly, if NewText is empty/blank, the current item/tab will be deselected.
297 |For a multi-select ListBox, CurrentText is an array. NewText cannot be an array, but if multiple items match, they are all selected. To select multiple items with different text, call the Choose method repeatedly.
298 |To select an item by its position number instead of its text, use the Value property.
299 | 300 |Edit
301 |CurrentText and NewText are the text of the Edit control. As with other controls, the text is retrieved or set as-is; no end-of-line translation is performed. To retrieve or set the text of a multi-line Edit control while also translating between `r`n
and `n
, use the Value property.
StatusBar
304 |CurrentText and NewText are the text of the StatusBar control's first part only (use SB.SetText for greater flexibility).
305 |Retrieves the type of the control.
310 |CurrentType := GuiCtrl.Type
311 | Depending on the control type, CurrentType is one of the following strings: ActiveX, Button, CheckBox, ComboBox, Custom, DateTime, DDL, Edit, GroupBox, Hotkey, Link, ListBox, ListView, MonthCal, Pic, Progress, Radio, Slider, StatusBar, Tab, Tab2, Tab3, Text, TreeView, UpDown.
312 |Retrieves or sets the contents of a value-capable control.
317 |CurrentValue := GuiCtrl.Value
318 | GuiCtrl.Value := NewValue
319 | Note: If the control is not value-capable, CurrentValue will be blank and assigning NewValue will raise an error. Invalid values throw an exception.
320 |CurrentValue and NewValue depend on the control type:
321 | 322 |ActiveX
323 |CurrentValue is the ActiveX object of the ActiveX control. For example, if the control was created with the text Shell.Explorer, this is a WebBrowser object. The same wrapper object is returned each time.
324 |NewValue is invalid and throws an exception.
325 | 326 |CheckBox / Radio
327 |CurrentValue is 1 if the CheckBox or Radio control is checked, 0 if it is unchecked, or -1 if it has a gray checkmark.
328 |NewValue can be 0 to uncheck the button, 1 to check it, or -1 to give it a gray checkmark. For Radio buttons, if one is being checked (turned on) and it is a member of a multi-radio group, the other radio buttons in its group will be automatically unchecked.
329 |To get or set control's text/caption instead, use the Text property.
330 | 331 |ComboBox / DropDownList / ListBox / Tab
332 |CurrentValue is the position number of the currently selected item/tab in the ComboBox, DropDownList, ListBox or Tab control. If none is selected, zero is returned. If text is entered into a ComboBox, the first item with matching text is used. If there is no matching item, the result is zero even if there is text in the control. For a multi-select ListBox, the result is an array of numbers (which is empty if no items are selected).
333 |NewValue is the position number of a single item/tab to select, or zero to clear the current selection (this is valid even for Tab controls). To select multiple items, call the Choose method repeatedly.
334 |To get or set the selected item given its text instead of its position, use the Text property.
335 | 336 |DateTime / MonthCal
337 |CurrentValue is a date-time stamp in YYYYMMDDHH24MISS format currently selected in the DateTime or MonthCal control.
338 |NewValue is a date-time stamp in YYYYMMDDHH24MISS format. Specify A_Now
to use the current date and time (today). For DateTime controls, NewValue may be an empty string to cause the control to have no date/time selected (if it was created with that ability). For MonthCal controls, a range may be specified if the control is multi-select.
Edit
341 |CurrentValue is the current content of the Edit control. For multi-line controls, any line breaks in the text will be represented as plain linefeeds (`n) rather than the traditional CR+LF (`r`n) used by non-GUI functions such as ControlGetText and ControlSetText.
342 |NewValue is the new content. For multi-line controls, Any linefeeds (`n) in NewValue that lack a preceding carriage return (`r) are automatically translated to CR+LF (`r`n) to make them display properly. However, this is usually not a concern because when using Gui.Submit or when retrieving this value this translation will be reversed automatically by replacing CR+LF with LF (`n).
343 |To retrieve or set the text without translating `n to or from `r`n, use the Text property.
344 | 345 |Hotkey
346 |CurrentValue is the modifiers and key name if there is a hotkey in the Hotkey control; otherwise blank. Examples: ^!C
, ^Home
, +^NumpadHome
.
NewValue can be a set of modifiers with a key name, or blank to clear the control. Examples: ^!c
, ^Numpad1
, +Home
. The only modifiers supported are ^ (Control), ! (Alt), and + (Shift). See the key list for available key names.
Picture
350 |CurrentValue is the picture's file name as it was originally specified when the Picture control was created. This name does not change even if a new picture file name is specified.
351 |NewValue is the filename (or handle) of the new image to load (see Picture for supported file types). Zero or more of the following options may be specified immediately in front of the filename: *wN
(width N), *hN
(height N), and *IconN
(icon group number N in a DLL or EXE file). In the following example, the default icon from the second icon group is loaded with a width of 100 and an automatic height via "keep aspect ratio": MyPic.Value := "*icon2 *w100 *h-1 C:\My Application.exe"
. Specify *w0 *h0
to use the image's actual width and height. If *w
and *h
are omitted, the image will be scaled to fit the current size of the control. When loading from a multi-icon .ICO file, specifying a width and height also determines which icon to load. Note: Use only one space or tab between the final option and the filename itself; any other spaces and tabs are treated as part of the filename.
Progress / Slider / UpDown
354 |CurrentValue is the current position of the Progress, Slider or UpDown control.
355 |NewValue is the new position of the control, for example MySlider.Value := 10
. To adjust the value by a relative amount, use the operators +=
, -=
, ++
or --
instead of :=
. If the new position would be outside the range of the control, the control is generally set to the nearest valid value.
Text
358 |CurrentValue is the text/caption of the Text control.
359 |NewValue is the control's new text. Since the control will not expand automatically, use GuiCtrl.Move(,, 300)
if the control needs to be widened.
Retrieves or sets the visibility state of the control.
365 |CurrentSetting := GuiCtrl.Visible
366 | GuiCtrl.Visible := NewSetting
367 | CurrentSetting is NewSetting if assigned, otherwise 1 (true) by default unless overwritten by the Hidden option.
368 |NewSetting is a boolean value that enables or disables this setting. If true, the control is visible. If false, the control is hidden.
369 |For Tab controls, this will also show or hide all of the tab's sub-controls. If you additionally want to prevent a control's shortcut key (underlined letter) from working, disable the control via GuiCtrl.Enabled := false
.
When adding a large number of items to a control (such as a ListView, TreeView or ListBox), performance can be improved by preventing the control from being redrawn while the changes are being made. This is done by using GuiCtrl.Opt("-Redraw")
before adding the items and GuiCtrl.Opt("+Redraw")
afterward. Changes to the control which have not yet become visible prior to disabling redraw will generally not become visible until after redraw is re-enabled.
For performance reasons, changes to a control's content generally do not cause the control to be immediately redrawn even if redraw is enabled. Instead, a portion of the control is "invalidated" and is usually repainted after a brief delay, when the program checks its internal message queue. The script can force this to take place immediately by calling Sleep -1
.
GUI control types are elements of interaction which can be added to a GUI window using Gui.Add.
25 | 26 |ActiveX components such as the MSIE browser control can be embedded into a GUI window as follows. For details about the ActiveX component and its method used below, see WebBrowser object (Microsoft Docs) and Navigate method (Microsoft Docs).
55 |MyGui := Gui() 56 | WB := MyGui.Add("ActiveX", "w980 h640", "Shell.Explorer").Value ; The last parameter is the name of the ActiveX component. 57 | WB.Navigate("https://www.autohotkey.com/docs/") ; This is specific to the web browser control. 58 | MyGui.Show()59 |
When the control is created, the ActiveX object can be retrieved via GuiControl.Value.
60 |To handle events exposed by the object, use ComObjConnect as follows. For details about the event used below, see NavigateComplete2 event (Microsoft Docs).
61 |MyGui := Gui() 62 | URL := MyGui.Add("Edit", "w930 r1", "https://www.autohotkey.com/docs/") 63 | MyGui.Add("Button", "x+6 yp w44 Default", "Go").OnEvent("Click", ButtonGo) 64 | WB := MyGui.Add("ActiveX", "xm w980 h640", "Shell.Explorer").Value 65 | ComObjConnect(WB, WB_events) ; Connect WB's events to the WB_events class object. 66 | MyGui.Show() 67 | ; Continue on to load the initial page: 68 | ButtonGo() 69 | 70 | ButtonGo(*) { 71 | WB.Navigate(URL.Value) 72 | } 73 | 74 | class WB_events { 75 | static NavigateComplete2(wb, &NewURL, *) { 76 | URL.Value := NewURL ; Update the URL edit control. 77 | } 78 | }79 |
ComObjType can be used to determine the type of the retrieved object.
80 | 81 |A pushbutton, which can be pressed to trigger an action. In this case, the last parameter is the name of the button (shown on the button itself), which may include linefeeds (`n) to start new lines.
83 |For example:
84 |MyBtn := MyGui.Add("Button", "Default w80", "OK") 85 | MyBtn.OnEvent("Click", MyBtn_Click) ; Call MyBtn_Click when clicked.86 |
Or:
87 |MyBtn := MyGui.AddButton("Default w80", "OK") 88 | MyBtn.OnEvent("Click", MyBtn_Click) ; Call MyBtn_Click when clicked. 89 |90 |
Appearance:
91 | 92 |Whenever the user clicks the button or presses Space or Enter while it has the focus, the Click event is raised.
93 |The DoubleClick, Focus and LoseFocus events are also supported. As these events are only raised if the control has the BS_NOTIFY (0x4000) style, it is added automatically by OnEvent.
94 |The example above includes the word Default in its Options to make "OK" the default button. The default button's Click event is automatically triggered whenever the user presses Enter, except when the keyboard focus is on a different button or a multi-line edit control having the WantReturn style. To later change the default button to another button, follow this example, which makes the Cancel button become the default: MyGui["Cancel"].Opt("+Default")
. To later change the window to have no default button, follow this example: MyGui["OK"].Opt("-Default")
.
An ampersand (&) may be used in the button name to underline one of its letters. For example:
96 |MyGui.Add("Button",, "&Pause")97 |
In the example above, the letter P will be underlined, which allows the user to press Alt+P as shortcut key. To display a literal ampersand, specify two consecutive ampersands (&&).
98 | 99 |Known limitation: Certain desktop themes might not display a button's text properly. If this occurs, try including -Wrap
(minus Wrap) in the control's options. However, this also prevents having more than one line of text.
A small box that can be checked or unchecked to represent On/Off, Yes/No, etc.
103 |For example:
104 |MyGui.Add("CheckBox", "vShipToBillingAddress", "Ship to billing address?")105 |
Or:
106 |MyGui.AddCheckBox("vShipToBillingAddress", "Ship to billing address?")107 |
Appearance:
108 | 109 |For the last parameter, specify the label to display to the right of the box. This label is typically used as a prompt or description, and it may include linefeeds (`n) to start new lines. If a width (W) is specified in Options but no rows (R) or height (H), the control's text will be word-wrapped as needed, and the control's height will be set automatically.
110 |GuiControl.Value returns the number 1 for checked, 0 for unchecked, and -1 for gray/indeterminate.
111 |Specify the word Check3 in Options to enable a third "indeterminate" state that displays a gray checkmark or a square instead of a black checkmark (the indeterminate state indicates that the checkbox is neither checked nor unchecked). Specify the word Checked or CheckedGray in Options to have the checkbox start off checked or indeterminate, respectively. The word Checked may optionally be followed immediately by a 0, 1, or -1 to indicate the starting state. In other words, "Checked"
and "Checked" VarContainingOne
are the same.
Whenever the checkbox is clicked, it automatically cycles between its two or three possible states, and then raises the Click event, allowing the script to immediately respond to the user's input.
113 |The DoubleClick, Focus and LoseFocus events are also supported. As these events are only raised if the control has the BS_NOTIFY (0x4000) style, it is added automatically by OnEvent. This style is not applied by default as it prevents rapid clicks from changing the state of the checkmark (such as if the user clicks twice to toggle from unchecked to checked and then to indeterminate).
114 |Known limitation: Certain desktop themes might not display a checkbox's text properly. If this occurs, try including -Wrap
(minus Wrap) in the control's options. However, this also prevents having more than one line of text.
Same as DropDownList but also permits free-form text to be entered as an alternative to picking an item from the list. In this case, the last parameter of Gui.Add is an Array like ["Choice1", "Choice2", "Choice3"]
.
For example:
119 |MyGui.Add("ComboBox", "vColorChoice", ["Red", "Green", "Blue", "Black", "White"])120 |
Or:
121 |MyGui.AddComboBox("vColorChoice", ["Red", "Green", "Blue", "Black", "White"])122 |
Appearance:
123 | 124 |In addition to allowing all the same options as DropDownList, the word Limit may be included in Options to restrict the user's input to the visible width of the ComboBox's edit field. Also, the word Simple may be specified to make the ComboBox behave as though it is an Edit field with a ListBox beneath it.
125 |GuiControl.Value returns the position number of the currently selected item (the first item is 1, the second is 2, etc.) or 0 if the control contains text which does not match a list item, while GuiControl.Text returns the contents of the ComboBox's edit field. Gui.Submit stores the text, unless the word AltSubmit is in the control's Options and the text matches a list item, in which case it stores the position number of the item.
126 |Whenever the user selects a new item or changes the control's text, the Change event is raised. The Focus and LoseFocus events are also supported.
127 | 128 |Other controls which are not directly supported by AutoHotkey can be also embedded into a GUI window. In order to do so, include in Options the word Class followed by the Win32 class name of the desired control. Examples:
130 |MyGui.Add("Custom", "ClassComboBoxEx32") ; Adds a ComboBoxEx control. 131 | MyGui.Add("Custom", "ClassScintilla") ; Adds a Scintilla control. Note that the SciLexer.dll library must be loaded before the control can be added.132 |
AutoHotkey uses the standard Windows control text routines when text is to be retrieved/replaced in the control via Gui.Add or GuiControl.Value.
133 |Events: Since the meaning of each notification code depends on the control which sent it, OnEvent is not supported for Custom controls. However, if the control sends notifications in the form of a WM_NOTIFY or WM_COMMAND message, the script can use OnNotify or OnCommand to detect them.
134 |Here is an example that shows how to add and use an IP address control:
135 |MyGui := Gui() 136 | IP := MyGui.Add("Custom", "ClassSysIPAddress32 r1 w150") 137 | IP.OnCommand(0x300, IP_EditChange) ; 0x300 = EN_CHANGE 138 | IP.OnNotify(-860, IP_FieldChange) ; -860 = IPN_FIELDCHANGED 139 | IPText := MyGui.Add("Text", "wp") 140 | IPField := MyGui.Add("Text", "wp y+m") 141 | MyGui.Add("Button", "Default", "OK").OnEvent("Click", OK_Click) 142 | MyGui.Show() 143 | 144 | IPCtrlSetAddress(IP, SysGetIPAddresses()[1]) 145 | 146 | OK_Click(*) 147 | { 148 | MyGui.Hide() 149 | MsgBox("You chose " IPCtrlGetAddress(IP)) 150 | ExitApp() 151 | } 152 | 153 | IP_EditChange(*) 154 | { 155 | IPText.Text := "New text: " IP.Text 156 | } 157 | 158 | IP_FieldChange(thisCtrl, NMIPAddress) 159 | { 160 | ; Extract info from the NMIPAddress structure. 161 | iField := NumGet(NMIPAddress, 3*A_PtrSize + 0, "int") 162 | iValue := NumGet(NMIPAddress, 3*A_PtrSize + 4, "int") 163 | if (iValue >= 0) 164 | IPField.Text := "Field #" iField " modified: " iValue 165 | else 166 | IPField.Text := "Field #" iField " left empty" 167 | } 168 | 169 | IPCtrlSetAddress(GuiCtrl, IPAddress) 170 | { 171 | static WM_USER := 0x0400 172 | static IPM_SETADDRESS := WM_USER + 101 173 | 174 | ; Pack the IP address into a 32-bit word for use with SendMessage. 175 | IPAddrWord := 0 176 | Loop Parse IPAddress, "." 177 | IPAddrWord := (IPAddrWord * 256) + A_LoopField 178 | SendMessage(IPM_SETADDRESS, 0, IPAddrWord, GuiCtrl) 179 | } 180 | 181 | IPCtrlGetAddress(GuiCtrl) 182 | { 183 | static WM_USER := 0x0400 184 | static IPM_GETADDRESS := WM_USER + 102 185 | 186 | AddrWord := Buffer(4) 187 | SendMessage(IPM_GETADDRESS, 0, AddrWord, GuiCtrl) 188 | IPPart := [] 189 | Loop 4 190 | IPPart.Push(NumGet(AddrWord, 4 - A_Index, "UChar")) 191 | return IPPart[1] "." IPPart[2] "." IPPart[3] "." IPPart[4] 192 | }193 | 194 |
A box that looks like a single-line edit control but instead accepts a date and/or time. A drop-down calendar is also provided.
196 |For example:
197 |MyGui.Add("DateTime", "vMyDateTime", "LongDate")198 |
Or:
199 |MyGui.AddDateTime("vMyDateTime", "LongDate")200 |
Appearance:
201 | 202 |The last parameter is a format string, as described in the SetFormat method below. This method allows to change the display format after the DateTime control is created.
203 | 204 |Sets the display format of a DateTime control.
208 |GuiCtrl.SetFormat(Format)209 |
Type: String
212 |If blank or omitted, it defaults to ShortDate. Otherwise, specify one of the following formats:
213 |ShortDate: Uses the locale's short date format. For example, in some locales it would look like: 6/1/2005
214 |LongDate: Uses the locale's long date format. For example, in some locales it would look like: Wednesday, June 01, 2005
215 |Time: Shows only the time using the locale's time format. Although the date is not shown, it is still present in the control and will be retrieved along with the time in the YYYYMMDDHH24MISS format. For example, in some locales it would look like: 9:37:45 PM
216 |(custom format): Specify any combination of date and time formats. For example, "M/d/yy HH:mm"
would look like 6/1/05 21:37. Similarly, "dddd MMMM d, yyyy hh:mm:ss tt"
would look like Wednesday June 1, 2005 09:37:45 PM. Letters and numbers to be displayed literally should be enclosed in single quotes as in this example: "'Date:' MM/dd/yy 'Time:' hh:mm:ss tt"
. By contrast, non-alphanumeric characters such as spaces, tabs, slashes, colons, commas, and other punctuation do not need to be enclosed in single quotes. The exception to this is the single quote character itself: to produce it literally, use four consecutive single quotes (''''), or just two if the quote is already inside an outer pair of quotes.
To have a date other than today pre-selected, include in Options the word Choose followed immediately by a date in YYYYMMDD format. For example, Choose20050531
would pre-select May 31, 2005 (as with other options, it can also be a variable such as "Choose" Var
). To have no date/time selected, specify ChooseNone. ChooseNone also creates a checkbox inside the control that is unchecked whenever the control has no date. Whenever the control has no date, Gui.Submit or GuiControl.Value will retrieve a blank value (empty string).
The time of day may optionally be present. However, it must always be preceded by a date when going into or coming out of the control. The format of the time portion is HH24MISS (hours, minutes, seconds), where HH24 is expressed in 24-hour format; for example, 09 is 9am and 21 is 9pm. Thus, a complete date-time string would have the format YYYYMMDDHH24MISS.
223 |When specifying dates in the YYYYMMDDHH24MISS format, only the leading part needs to be present. Any remaining element that has been omitted will be supplied with the following default values: MM with month 01, DD with day 01, HH24 with hour 00, MI with minute 00 and SS with second 00.
224 |Within the drop-down calendar, the today-string at the bottom can be clicked to select today's date. In addition, the year and month name are clickable and allow easy navigation to a new month or year.
225 | 226 |When Gui.Submit or GuiControl.Value is used, the return value is the selected date and time in YYYYMMDDHH24MISS format. Both the date and the time are present regardless of whether they were actually visible in the control.
227 |Whenever the user changes the date or time, the Change event is raised. The Focus and LoseFocus events are also supported.
228 | 229 |Choose: See above.
231 |Range: Restricts how far back or forward in time the selected date can be. After the word Range, specify the minimum and maximum dates in YYYYMMDD format (with a dash between them). For example, Range20050101-20050615
would restrict the date to the first 5.5 months of 2005. Either the minimum or maximum may be omitted to leave the control unrestricted in that direction. For example, Range20010101
would prevent a date prior to 2001 from being selected and Range-20091231
(leading dash) would prevent a date later than 2009 from being selected. Without the Range option, any date between the years 1601 and 9999 can be selected. The time of day cannot be restricted.
Right: Causes the drop-down calendar to drop down on the right side of the control instead of the left.
233 |1: Specify the number 1 in Options to provide an up-down control to the right of the control to modify date-time values, which replaces the button of the drop-down month calendar that would otherwise be available. This does not work in conjunction with the format option LongDate described above.
234 |2: Specify the number 2 in Options to provide a checkbox inside the control that the user may uncheck to indicate that no date/time is selected. Once the control is created, this option cannot be changed.
235 |Colors inside the drop-down calendar: The colors of the day numbers inside the drop-down calendar obey that set by Gui.SetFont or the c (Color) option. To change the colors of other parts of the calendar, follow this example:
236 |SendMessage 0x1006, 4, 0xFFAA99, "SysDateTimePick321" ; 0x1006 is DTM_SETMCCOLOR. 4 is MCSC_MONTHBK (background color). The color must be specified in BGR vs. RGB format (red and blue components swapped).237 | 238 |
A list of choices that is displayed in response to pressing a small button. In this case, the last parameter of Gui.Add is an Array like ["Choice1", "Choice2", "Choice3"]
.
For example:
241 |MyGui.Add("DropDownList", "vColorChoice", ["Black", "White", "Red", "Green", "Blue"])242 |
Or:
243 |MyGui.AddDropDownList("vColorChoice", ["Black", "White", "Red", "Green", "Blue"])244 |
Appearance:
245 | 246 |To have one of the items pre-selected when the window first appears, include in Options the word Choose followed immediately by the number of an item to be pre-selected. For example, Choose5
would pre-select the fifth item (as with other options, it can also be a variable such as "Choose" Var
). After the control is created, use GuiControl.Value, GuiControl.Text or GuiControl.Choose to change the selection, and GuiControl.Add or GuiControl.Delete to add or remove entries from the list.
Specify either the word Uppercase or Lowercase in Options to automatically convert all items in the list to uppercase or lowercase. Specify the word Sort to automatically sort the contents of the list alphabetically (this also affects any items added later via GuiControl.Add). The Sort option also enables incremental searching whenever the list is dropped down; this allows an item to be selected by typing the first few characters of its name.
248 |GuiControl.Value returns the position number of the currently selected item (the first item is 1, the second is 2, etc.) or 0 if there is no item selected, while GuiControl.Text returns the text of the currently selected item. Gui.Submit stores the text, unless the word AltSubmit is in the control's Options, in which case it stores the position number of the item.
249 |Whenever the user selects a new item, the Change event is raised. The Focus and LoseFocus events are also supported.
250 |Use the R or H option to control the height of the popup list. For example, specifying R5
would make the list 5 rows tall, while H400
would set the total height of the selection field and list to 400 pixels. If both R and H are omitted, the list will automatically expand to take advantage of the available height of the user's desktop.
To set the height of the selection field or list items, use the CB_SETITEMHEIGHT message as in the example below:
252 |MyGui := Gui() 253 | DDL := MyGui.Add("DDL", "vcbx w200 Choose1", ["One", "Two"]) 254 | ; CB_SETITEMHEIGHT = 0x0153 255 | PostMessage(0x0153, -1, 50, DDL) ; Set height of selection field. 256 | PostMessage(0x0153, 0, 50, DDL) ; Set height of list items. 257 | MyGui.Show("h70")258 | 259 |
An area where free-form text can be typed by the user.
261 |For example:
262 |MyGui.Add("Edit", "r9 vMyEdit w135", "Text to appear inside the edit control (omit this parameter to start off empty).")263 |
Or:
264 |MyGui.AddEdit("r9 vMyEdit w135", "Text to appear inside the edit control (omit this parameter to start off empty).")265 |
Appearance:
266 | 267 |The control will be multi-line if it has more than one row of text. For example, specifying r3
in Options will create a 3-line edit control with the following default properties: a vertical scroll bar, word-wrapping enabled, and Enter captured as part of the input rather than triggering the window's default button.
To start a new line in a multi-line edit control, the last parameter (contents) may contain either a solitary linefeed (`n) or a carriage return and linefeed (`r`n). Both methods produce literal `r`n pairs inside the Edit control. However, when the control's content is retrieved via Gui.Submit or GuiControl.Value, each `r`n in the text is always translated to a plain linefeed (`n). To bypass this End-of-Line translation, use GuiControl.Text. To write the text to a file, follow this example: FileAppend(MyEdit.Text, "C:\Saved File.txt")
.
If the control has word-wrapping enabled (which is the default for multi-line edit controls), any wrapping that occurs as the user types will not produce linefeed characters (only Enter can do that).
270 |Whenever the user changes the control's content, the Change event is raised.
271 |TIP: To load a text file into an Edit control, use FileRead and GuiControl.Value. For example:
272 |MyEdit := MyGui.Add("Edit", "R20") 273 | MyEdit.Value := FileRead("C:\My File.txt")274 | 275 |
To remove an option rather than adding it, precede it with a minus sign:
277 |Limit: Restricts the user's input to the visible width of the edit field. Alternatively, to limit input to a specific number of characters, include a number immediately afterward. For example, Limit10
would allow no more than 10 characters to be entered.
Lowercase: The characters typed by the user are automatically converted to lowercase.
279 |Multi: Makes it possible to have more than one line of text. However, it is usually not necessary to specify this because it will be auto-detected based on height (H), rows (R), or contents (Text).
280 |Number: Prevents the user from typing anything other than digits into the field (however, it is still possible to paste non-digits into it). An alternate way of forcing a numeric entry is to attach an UpDown control to the Edit.
281 |Password: Hides the user's input (such as for password entry) by substituting masking characters for what the user types. If a non-default masking character is desired, include it immediately after the word Password. For example, Password*
would make the masking character an asterisk rather than the black circle (bullet). Note: This option has no effect for multi-line edit controls.
ReadOnly: Prevents the user from changing the control's contents. However, the text can still be scrolled, selected and copied to the clipboard.
283 |Tn: The letter T may be used to set tab stops inside a multi-line edit control (since tab stops determine the column positions to which literal TAB characters will jump, they can be used to format the text into columns). If the letter T is not used, tab stops are set at every 32 dialog units (the width of each "dialog unit" is determined by the operating system). If the letter T is used only once, tab stops are set at every n units across the entire width of the control. For example, MyGui.Add("Edit", "vMyEdit r16 t64")
would double the default distance between tab stops. To have custom tab stops, specify the letter T multiple times as in the following example: MyGui.Add("Edit", "vMyEdit r16 t8 t16 t32 t64 t128")
. One tab stop is set for each of the absolute column positions in the list, up to a maximum of 50 tab stops. Note: Tab stops require a multiline edit control.
Uppercase: The characters typed by the user are automatically converted to uppercase.
285 |WantCtrlA: Specify -WantCtrlA
(minus WantCtrlA) to prevent the user's press of Ctrl+A from selecting all text in the edit control.
WantReturn: Specify -WantReturn
(minus WantReturn) to prevent a multi-line edit control from capturing Enter. Pressing Enter will then be the same as pressing the window's default button (if any). In this case, the user may press Ctrl+Enter to start a new line.
WantTab: Causes Tab to produce a tab character rather than navigating to the next control. Without this option, the user may press Ctrl+Tab to produce a tab character inside a multi-line edit control. Note: WantTab also works in a single-line edit control.
288 |Wrap: Specify -Wrap
(minus Wrap) to turn off word-wrapping in a multi-line edit control. Since this style cannot be changed after the control has been created, use one of the following to change it: 1) Destroy then recreate the window and its control; or 2) Create two overlapping edit controls, one with wrapping enabled and the other without it. The one not currently in use can be kept empty and/or hidden.
See general options for other options like Right, Center, and Hidden. See also: positioning and sizing of controls.
290 |A more powerful edit control: HiEdit is a free, multitabbed, large-file edit control consuming very little memory. It can edit both text and binary files. For details and a demonstration, see HiEdit on GitHub.
291 | 292 |A rectangular border/frame, often used around other controls to indicate they are related. In this case, the last parameter is the title of the box, which if present is displayed at its upper-left edge.
294 |For example:
295 |MyGui.Add("GroupBox", "w200 h100", "Geographic Criteria")296 |
Or:
297 |MyGui.AddGroupBox("w200 h100", "Geographic Criteria")298 |
Appearance:
299 | 300 |By default, a GroupBox's title may have only one line of text. This can be overridden by specifying Wrap
in Options.
To specify the number of rows inside the control (or its height and width), see positioning and sizing of controls.
302 | 303 |A box that looks like a single-line edit control but instead accepts a keyboard combination pressed by the user. For example, if the user presses Ctrl+Alt+C on an English keyboard layout, the box would display "Ctrl + Alt + C".
305 |For example:
306 |MyGui.Add("Hotkey", "vChosenHotkey")307 |
Or:
308 |MyGui.AddHotkey("vChosenHotkey")309 |
Appearance:
310 | 311 |GuiControl.Value returns the control's hotkey modifiers and name, which are compatible with the Hotkey function. Examples: ^!C
, +!Home
, +^Down
, ^Numpad1
, !NumpadEnd
. If there is no hotkey in the control, the value is blank.
Note: Some keys are displayed the same even though they are retrieved as different names. For example, both ^Numpad7
and ^NumpadHome
might be displayed as Ctrl + Num 7.
By default, the control starts off with no hotkey specified. To instead have a default, specify its modifiers and name as the last parameter as in this example: MyGui.Add("Hotkey", "vChosenHotkey", "^!p")
. The only modifiers supported are ^ (Ctrl), ! (Alt), and + (Shift). See the key list for available key names.
Whenever the user changes the control's content (by pressing a key), the Change event is raised.
315 |Note: The event is raised even when an incomplete hotkey is present. For example, if the user holds down Ctrl, the event is raised once and GuiControl.Value returns only a circumflex (^). When the user completes the hotkey, the event is raised again and GuiControl.Value returns the complete hotkey.
316 |To restrict the types of hotkeys the user may enter, include the word Limit followed by the sum of one or more of the following numbers:
317 |For example, Limit1
would prevent unmodified hotkeys such as letters and numbers from being entered, and Limit15
would require at least two modifier keys. If the user types a forbidden modifier combination, the Ctrl+Alt combination is automatically and visibly substituted.
The Hotkey control has limited capabilities. For example, it does not support mouse/controller hotkeys or Win (LWin and RWin). One way to work around this is to provide one or more checkboxes as a means for the user to enable extra modifiers such as Win.
329 | 330 |A text control that can contain links similar to those found in a web browser. Within the control's text, enclose the link text within <A>
and </A>
to create a clickable link. Although this looks like HTML, Link controls only support the opening <A>
tag (optionally with an ID and/or HREF attribute) and closing </A>
tag.
For example:
333 |MyGui.Add("Link",, 'This is a <a href="https://www.autohotkey.com">link</a>') 334 | MyGui.Add("Link",, 'Links may be used anywhere in the text like <a id="A">this</a> or <a id="B">that</a>')335 |
Or:
336 |MyGui.AddLink(, 'This is a <a href="https://www.autohotkey.com">link</a>') 337 | MyGui.AddLink(, 'Links may be used anywhere in the text like <a id="A">this</a> or <a id="B">that</a>')338 |
Appearance:
339 | 340 | 341 |Whenever the user clicks on a link, the Click event is raised. If the control has no Click callback (registered by calling OnEvent), the link's HREF is automatically executed as though passed to the Run function.
342 |MyGui := Gui() 343 | LinkText := 'Click to run <a href="notepad" id="notepad">Notepad</a> or open <a id="help" href="https://www.autohotkey.com/docs/">online help</a>.' 344 | Link := MyGui.Add("Link", "w200", LinkText) 345 | Link.OnEvent("Click", Link_Click) 346 | Link_Click(Ctrl, ID, HREF) 347 | { 348 | MsgText := Format(" 349 | ( 350 | ID: {1} 351 | HREF: {2} 352 | 353 | Execute this link? 354 | )", ID, HREF) 355 | if MsgBox(MsgText,, "y/n") = "yes" 356 | Run(HREF) 357 | } 358 | MyGui.Show()359 | 360 |
A relatively tall box containing a list of choices that can be selected. In this case, the last parameter of Gui.Add is an Array like ["Choice1", "Choice2", "Choice3"]
.
For example:
363 |MyGui.Add("ListBox", "r5 vColorChoice", ["Red", "Green", "Blue", "Black", "White"])364 |
Or:
365 |MyGui.AddListBox("r5 vColorChoice", ["Red", "Green", "Blue", "Black", "White"])366 |
Appearance:
367 | 368 |To have one of the items pre-selected when the window first appears, include in Options the word Choose followed immediately by the number of an item to be pre-selected. For example, Choose5
would pre-select the fifth item. To have multiple items pre-selected, use GuiControl.Choose multiple times (requires the Multi option). After the control is created, use GuiControl.Value, GuiControl.Text or GuiControl.Choose to change the selection, and GuiControl.Add or GuiControl.Delete to add or remove entries from the list.
If the Multi option is absent, GuiControl.Value returns the position number of the currently selected item (the first item is 1, the second is 2, etc.) or 0 if there is no item selected, while GuiControl.Text returns the text of the currently selected item. If the Multi option is used, GuiControl.Value and GuiControl.Text return an array of items instead of a single item.
370 |Gui.Submit stores GuiControl.Text, unless the word AltSubmit is in the control's Options, in which case it stores GuiControl.Value.
371 |Whenever the user selects or deselects one or more items, the Change event is raised. The DoubleClick, Focus and LoseFocus events are also supported.
372 |When adding a large number of items to a ListBox, performance may be improved by using MyListBox.Opt("-Redraw")
prior to the operation, and MyListBox.Opt("+Redraw")
afterward. See Redraw for more details.
Choose: See above.
376 |Multi: Allows more than one item to be selected simultaneously via shift-click and control-click (to avoid the need for shift/control-click, specify the number 8 instead of the word Multi). In this case, Gui.Submit or GuiControl.Value returns an array of selected position numbers. For example, [1, 2, 3]
would indicate that the first three items are selected. To get an array of selected texts instead, use GuiControl.Text. To extract the individual items from the array, use MyListBox.Text[1]
(1 would be the first item) or a For-loop such as this example:
For Index, Field in MyListBox.Text 378 | { 379 | MsgBox "Selection number " Index " is " Field 380 | }381 |
ReadOnly: Prevents items from being visibly highlighted when they are selected (but Gui.Submit, GuiControl.Value or GuiControl.Text will still return the selected item).
382 |Sort: Automatically sorts the contents of the list alphabetically (this also affects any items added later via GuiControl.Add). The Sort option also enables incremental searching, which allows an item to be selected by typing the first few characters of its name.
383 |Tn: The letter T may be used to set tab stops, which can be used to format the text into columns. If the letter T is not used, tab stops are set at every 32 dialog units (the width of each "dialog unit" is determined by the operating system). If the letter T is used only once, tab stops are set at every n units across the entire width of the control. For example, MyGui.Add("ListBox", "vMyListBox t64")
would double the default distance between tab stops. To have custom tab stops, specify the letter T multiple times as in the following example: MyGui.Add("ListBox", "vMyListBox t8 t16 t32 t64 t128")
. One tab stop is set for each of the absolute column positions in the list, up to a maximum of 50 tab stops.
0x100: Include 0x100 in Options to turn on the LBS_NOINTEGRALHEIGHT style. This forces the ListBox to be exactly the height specified rather than a height that prevents a partial row from appearing at the bottom. This option also prevents the ListBox from shrinking when its font is changed.
385 |To specify the number of rows of text (or the height and width), see positioning and sizing of controls.
386 | 387 |A ListView is one of the most elaborate controls provided by the operating system. In its most recognizable form, it displays a tabular view of rows and columns, the most common example of which is Explorer's list of files and folders (detail view).
389 |For example:
390 |MyGui.Add("ListView", "r20 w700", ["Name", "In Folder", "Size (KB)", "Type"])391 |
Or:
392 |MyGui.AddListView("r20 w700", ["Name", "In Folder", "Size (KB)", "Type"])393 |
Appearance:
394 | 395 |See the separate ListView page for more information.
396 | 397 |A tall and wide control that displays all the days of the month in calendar format. The user may select a single date or a range of dates.
399 |For example:
400 |MyGui.Add("MonthCal", "vMyCalendar")401 |
Or:
402 |MyGui.AddMonthCal("vMyCalendar")403 |
Appearance:
404 | 405 |To have a date other than today pre-selected, specify it as the third parameter in YYYYMMDD format (e.g. 20050531
). A range of dates may also be pre-selected by including a dash between two dates (e.g. "20050525-20050531"
).
It is usually best to omit width (W) and height (H) for a MonthCal because it automatically sizes itself to fit exactly one month. To display more than one month vertically, specify R2
or higher in Options. To display more than one month horizontally, specify W-2
(W negative two) or higher. These options may both be present to expand in both directions.
The today-string at the bottom of the control can be clicked to select today's date. In addition, the year and month name are clickable and allow easy selection of a new year or month.
408 |Keyboard navigation: Keyboard navigation is fully supported in MonthCal, but only if it has the keyboard focus. For supported keyboard shortcuts, see DateTime's keyboard navigation (within the drop-down calendar).
409 |When Gui.Submit or GuiControl.Value is used, the return value is the selected date in YYYYMMDD format (without any time portion). However, when the multi-select option is in effect, the minimum and maximum dates are retrieved with a dash between them (e.g. 20050101-20050108
). If only a single date was selected in a multi-select calendar, the minimum and maximum are both present but identical. StrSplit can be used to separate the dates. For example, the following would put the minimum in Date[1] and the maximum in Date[2]: Date := StrSplit(MyMonthCal.Value, "-")
.
Whenever the user changes the selection, the Change event is raised.
411 |When specifying dates in the YYYYMMDD format, the MM and/or DD portions may be omitted, in which case they are assumed to be 1. For example, 200205
is seen as 20020501, and 2005
is seen as 20050101.
Multi: Multi-select. Allows the user to shift-click or click-drag to select a range of adjacent dates (the user may still select a single date too). This option may be specified explicitly or put into effect automatically by means of specifying a selection range when the control is created. For example: MyGui.Add("MonthCal", "vMyCal", "20050101-20050108")
. Once the control is created, this option cannot be changed.
Range: Restricts how far back or forward in time the calendar can go. After the word Range, specify the minimum and maximum dates in YYYYMMDD format (with a dash between them). For example, Range20050101-20050615
would restrict the selection to the first 5.5 months of 2005. Either the minimum or maximum may be omitted to leave the calendar unrestricted in that direction. For example, Range20010101
would prevent a date prior to 2001 from being selected and Range-20091231
(leading dash) would prevent a date later than 2009 from being selected. Without the Range option, any date between the years 1601 and 9999 can be selected.
4: Specify the number 4 in Options to display week numbers (1-53) to the left of each row of days. Week numbering is determined by the operating system's user local settings. The three possible modes are described in the documentation for LOCALE_IFIRSTWEEKOFYEAR.
417 |8: Specify the number 8 in Options to prevent the circling of today's date within the control.
418 |16: Specify the number 16 in Options to prevent the display of today's date at the bottom of the control.
419 |Colors: The colors of the day numbers inside the calendar obey that set by Gui.SetFont or the c (Color) option. To change the colors of other parts of the calendar, follow this example:
420 |SendMessage 0x100A, 5, 0xFFAA99, "SysMonthCal321" ; 0x100A is MCM_SETCOLOR. 5 is MCSC_TITLETEXT (color of title text). The color must be specified in BGR vs. RGB format (red and blue components swapped).421 | 422 |
An area containing an image (see last two paragraphs for supported file types). The last parameter is the filename of the image, which is assumed to be in A_WorkingDir if an absolute path isn't specified.
424 |For example:
425 |MyGui.Add("Picture", "w300 h-1", "C:\My Pictures\Company Logo.gif")426 |
Or:
427 |MyGui.AddPicture("w300 h-1", "C:\My Pictures\Company Logo.gif")428 |
To retain the image's actual width and/or height, omit the W and/or H options. Otherwise, the image is scaled to the specified width and/or height (this width and height also determines which icon to load from a multi-icon .ICO file). To shrink or enlarge the image while preserving its aspect ratio, specify -1 for one of the dimensions and a positive number for the other. For example, specifying "w200 h-1"
would make the image 200 pixels wide and cause its height to be set automatically. If the picture cannot be loaded or displayed (e.g. file not found), an error is thrown and the control is not added.
Picture controls support the Click and DoubleClick events, with the same caveat as Text controls.
430 |To use a picture as a background for other controls, the picture should normally be added prior to those controls. However, if those controls are input-capable and the picture has the SS_NOTIFY style (which may be added automatically by OnEvent), create the picture after the other controls and include 0x4000000 (which is WS_CLIPSIBLINGS) in the picture's Options. This trick also allows a picture to be the background behind a Tab control or ListView.
431 |Icons, cursors, and animated cursors: Icons and cursors may be loaded from the following types of files: ICO, CUR, ANI, EXE, DLL, CPL, SCR, and other types that contain icon resources. To use an icon group other than the first one in the file, include in Options the word Icon followed by the number of the group. In the following example, the default icon from the second icon group would be used: MyGui.Add("Picture", "Icon2", "C:\My Application.exe")
.
Specifying the word AltSubmit in Options tells the program to use Microsoft's GDIPlus.dll to load the image, which might result in a different appearance for GIF, BMP, and icon images. For example, it would load a GIF that has a transparent background as a transparent bitmap, which allows the BackgroundTrans option to take effect (but icons support transparency without AltSubmit).
433 |Formats supported without the use of GDIPlus include GIF, JPG, BMP, ICO, CUR, and ANI images. GDIPlus is used by default for other image formats, such as PNG, TIF, Exif, WMF and EMF.
434 |Animated GIFs: Although animated GIF files can be displayed in a picture control, they will not actually be animated. To solve this, use the AniGIF DLL (which is free for non-commercial use) as demonstrated at the AutoHotkey Forums. Alternatively, the ActiveX control type can be used. For example:
435 |; Specify below the path to the GIF file to animate (local files are allowed too): 436 | pic := "http://www.animatedgif.net/cartoons/A_5odie_e0.gif" 437 | MyGui := Gui() 438 | MyGui.Add("ActiveX", "w100 h150", "mshtml:<img src='" pic "' />") 439 | MyGui.Show()440 |
A bitmap or icon handle can be used instead of a filename. For example, "HBITMAP:" handle
.
A dual-color bar typically used to indicate how much progress has been made toward the completion of an operation.
444 |For example:
445 |MyGui.Add("Progress", "w200 h20 cBlue vMyProgress", 75)446 |
Or:
447 |MyGui.AddProgress("w200 h20 cBlue vMyProgress", 75)448 |
Appearance:
449 | 450 |Specify the starting position of the bar as the third parameter (if omitted, the bar starts off at 0 or the number in the allowable range that is closest to 0). To later change the position of the bar, follow these examples, all of which operate upon a progress bar whose Name is MyProgress:
451 |MyGui["MyProgress"].Value += 20 ; Increase the current position by 20. 452 | MyGui["MyProgress"].Value := 50 ; Set the current position to 50.453 |
For horizontal Progress Bars, the thickness of the bar is equal to the control's height. For vertical Progress Bars it is equal to the control's width.
454 | 455 |Cn: Changes the bar's color. Specify for n one of the 16 primary HTML color names or a 6-digit RGB color value. Examples: cRed
, cFFFF33
, cDefault
. If the C option is never used (or cDefault
is specified), the system's default bar color will be used.
BackgroundN: Changes the bar's background color. Specify for N one of the 16 primary HTML color names or a 6-digit RGB color value. Examples: BackgroundGreen
, BackgroundFFFF33
, BackgroundDefault
. If the Background option is never used (or BackgroundDefault
is specified), the background color will be that of the window or tab control behind it.
Range: Sets the range to be something other than 0 to 100. After the word Range, specify the minimum, a dash, and maximum. For example, Range0-1000
would allow numbers between 0 and 1000; Range-50-50
would allow numbers between -50 and 50; and Range-10--5
would allow numbers between -10 and -5.
Smooth: Displays a simple continuous bar. If this option is not used and the bar does not have any custom colors, the bar's appearance is defined by the current system theme. Otherwise, the bar appears as a length of segments.
460 |Vertical: Makes the bar rise or fall vertically rather than move along horizontally.
461 |The above options can be changed via GuiControl.Opt after the control is created.
462 | 463 |A radio button is a small empty circle that can be checked (on) or unchecked (off).
465 |For example:
466 |MyGui.Add("Radio", "vMyRadioGroup", "Wait for all items to be in stock before shipping.")467 |
Or:
468 |MyGui.AddRadio("vMyRadioGroup", "Wait for all items to be in stock before shipping.")469 |
Appearance:
470 | 471 |These controls usually appear in radio groups, each of which contains two or more radio buttons. When the user clicks a radio button to turn it on, any others in its radio group are turned off automatically (the user may also navigate inside a group with the arrow keys). A radio group is created automatically around all consecutively added radio buttons. To start a new group, specify the word Group in the Options of the first button of the new group -- or simply add a non-radio control in between, since that automatically starts a new group.
472 |For the last parameter, specify the label to display to the right of the radio button. This label is typically used as a prompt or description, and it may include linefeeds (`n) to start new lines. If a width (W) is specified in Options but no rows (R) or height (H), the control's text will be word-wrapped as needed, and the control's height will be set automatically.
473 |Specify the word Checked in Options to have the button start off in the "on" state. The word Checked may optionally be followed immediately by a 0 or 1 to indicate the starting state: 0 for unchecked and 1 for checked. In other words, "Checked"
and "Checked" VarContainingOne
are the same.
GuiControl.Value returns the number 1 for "on" and 0 for "off". To instead retrieve the position number of the selected radio option within a radio group, name only one of the radio buttons and use Gui.Submit.
475 |Whenever the user turns on the button, the Click event is raised. Unlike the single-variable mode in the previous paragraph, the event callback must be registered for each button in a radio group for which it should be called. This allows the flexibility to ignore the clicks of certain buttons.
476 |The DoubleClick, Focus and LoseFocus events are also supported. As these events are only raised if the control has the BS_NOTIFY (0x4000) style, it is added automatically by OnEvent.
477 |Known limitation: Certain desktop themes might not display a radio button's text properly. If this occurs, try including -Wrap
(minus Wrap) in the control's options. However, this also prevents having more than one line of text.
A sliding bar that the user can move along a vertical or horizontal track. The standard volume control in the taskbar's tray is an example of a slider.
481 |For example:
482 |MyGui.Add("Slider", "vMySlider", 50)483 |
Or:
484 |MyGui.AddSlider("vMySlider", 50)485 |
Appearance:
486 | 487 |Specify the starting position of the slider as the last parameter. If the last parameter is omitted, the slider starts off at 0 or the number in the allowable range that is closest to 0.
488 |The user may slide the control by the following means: 1) dragging the bar with the mouse; 2) clicking inside the bar's track area with the mouse; 3) turning the mouse wheel while the control has focus; or 4) pressing the following keys while the control has focus: ↑, →, ↓, ←, PgUp, PgDn, Home, and End.
489 |GuiControl.Value and Gui.Submit return or store the current numeric position of the slider.
490 | 491 |By default, the slider's Change event is raised when the user has stopped moving the slider, such as by releasing the mouse button after having dragging it. If the control has the AltSubmit option, the Change event is also raised (very frequently) after each visible movement of the bar while the user is dragging it with the mouse.
493 |Ctrl_Change(GuiCtrlObj, Info)
494 | Type: Integer
498 |A numeric value from the tables below indicating how the slider was moved. These values and the corresponding names are defined in the Windows SDK.
499 |Value | Name | Meaning |
---|---|---|
0 | TB_LINEUP | The user pressed ← or ↑. |
1 | TB_LINEDOWN | The user pressed → or ↓. |
2 | TB_PAGEUP | The user pressed PgUp. |
3 | TB_PAGEDOWN | The user pressed PgDn. |
4 | TB_THUMBPOSITION | The user moved the slider via the mouse wheel, or finished a drag-and-drop to a new position. |
6 | TB_TOP | The user pressed Home to send the slider to the left or top side. |
7 | TB_BOTTOM | The user pressed End to send the slider to the right or bottom side. |
Only if the AltSubmit option is used:
512 |Value | Name | Meaning |
---|---|---|
5 | TB_THUMBTRACK | The user is currently dragging the slider via the mouse; that is, the mouse button is currently down. |
8 | TB_ENDTRACK | The user has finished moving the slider, either via the mouse or the keyboard. Note: With the exception of mouse wheel movement (#4), the Change event is raised again for #8 even though it was already raised with one of the digits above. |
Buddy1 and Buddy2: Specifies up to two existing controls to automatically reposition at the ends of the slider. Buddy1 is displayed at the left or top side (depending on whether the Vertical option is present). Buddy2 is displayed at the right or bottom side. After the word Buddy1 or Buddy2, specify the Name or HWND of an existing control. For example, Buddy1MyTopText
would assign the control whose name is MyTopText. The text or ClassNN of a control can also be used, but only up to the first space or tab.
Center: The thumb (the bar moved by the user) will be blunt on both ends rather than pointed at one end.
521 |Invert: Reverses the control so that the lower value is considered to be on the right/bottom rather than the left/top. This is typically used to make a vertical slider move in the direction of a traditional volume control. Note: The ToolTip option described below will not obey the inversion and therefore should not be used in this case.
522 |Left: The thumb (the bar moved by the user) will point to the top rather than the bottom. But if the Vertical option is in effect, the thumb will point to the left rather than the right.
523 |Line: Specifies the number of positions to move when the user presses one of the arrow keys. After the word Line, specify number of positions to move. For example: Line2
.
NoTicks: Omits tickmarks alongside the track.
525 |Page: Specifies the number of positions to move when the user presses PgUp or PgDn. After the word Page, specify number of positions to move. For example: Page10
.
Range: Sets the range to be something other than 0 to 100. After the word Range, specify the minimum, a dash, and maximum. For example, Range1-1000
would allow a number between 1 and 1000 to be selected; Range-50-50
would allow a number between -50 and 50; and Range-10--5
would allow a number between -10 and -5.
Thick: Specifies the length of the thumb (the bar moved by the user). After the word Thick, specify the thickness in pixels (e.g. Thick30
). To go beyond a certain thickness, it is probably necessary to either specify the Center option or remove the theme from the control (which can be done by specifying -Theme
in the control's options).
TickInterval: Provides tickmarks alongside the track at the specified interval. After the word TickInterval, specify the interval at which to display additional tickmarks (if the interval is never set, it defaults to 1). For example, TickInterval10
would display a tickmark once every 10 positions.
ToolTip: Creates a tooltip that reports the numeric position of the slider as the user is dragging it. To have the tooltip appear in a non-default position, specify one of the following instead: ToolTipLeft
or ToolTipRight
(for vertical sliders); ToolTipTop
or ToolTipBottom
(for horizontal sliders).
Vertical: Makes the control slide up and down rather than left and right.
531 |The above options can be changed via GuiControl.Opt after the control is created.
532 | 533 |A row of text and/or icons attached to the bottom of a window, which is typically used to report changing conditions.
535 |For example:
536 |SB := MyGui.Add("StatusBar",, "Bar's starting text (omit to start off empty).") 537 | SB.SetText("There are " . RowCount . " rows selected.")538 |
Or:
539 |SB := MyGui.AddStatusBar(, "Bar's starting text (omit to start off empty).") 540 | SB.SetText("There are " . RowCount . " rows selected.")541 |
Appearance:
542 | 543 |The simplest use of a status bar is to call the SetText method whenever something changes that should be reported to the user. To report more than one piece of information, divide the bar into sections via the SetParts method. To display icon(s) in the bar, call the SetIcon method.
544 | 545 |Displays NewText in the specified part of the status bar.
550 |GuiCtrl.SetText(NewText , PartNumber, Style)551 |
Type: String
554 |Up to two tab characters (`t) may be present anywhere in NewText: anything to the right of the first tab is centered within the part, and anything to the right of the second tab is right-justified.
Type: Integer
556 |If omitted, it defaults to 1. Otherwise, specify an integer between 1 and 256.
Type: Integer
558 |If omitted, it defaults to 0, which uses a traditional border that makes that part of the bar look sunken. Otherwise, specify 1 to have no border or 2 to have border that makes that part of the bar look raised.
Divides the bar into multiple sections according to the specified widths (in pixels).
564 |GuiCtrl.SetParts(Width1, Width2, ... Width255)565 |
Type: Integer
568 |If all parameters are omitted, the bar is restored to having only a single, long part. Otherwise, specify the width of each part except the last (the last will fill the remaining width of the bar). For example, SB.SetParts(50, 50)
would create three parts: the first two of width 50 and the last one of all the remaining width.
Type: Integer
571 |This method returns the status bar's window handle (HWND). A control's HWND is often used with PostMessage, SendMessage, and DllCall. It can also be used directly in a Control parameter.
572 |Any parts "deleted" by this method will start off with no text the next time they are shown (furthermore, their icons are automatically destroyed).
Displays a small icon to the left of the text in the specified part.
578 |GuiCtrl.SetIcon(FileName , IconNumber, PartNumber)579 |
Type: String
582 |The path to an icon or image file, or a bitmap or icon handle such as "HICON:" handle
. For a list of supported formats, see the Picture control.
Type: Integer
585 |If omitted, it defaults to 1 (the first icon group). Otherwise, specify the number of the icon group to be used in the file. For example, SB.SetIcon("Shell32.dll", 2)
would use the default icon from the second icon group. If negative, its absolute value is assumed to be the resource ID of an icon within an executable file.
Type: Integer
587 |If omitted, it defaults to 1. Otherwise, specify an integer between 1 and 256.
Type: Integer
590 |This method returns the icon's handle (HICON). The HICON is a system resource that can be safely ignored by most scripts because it is destroyed automatically when the status bar's window is destroyed. Similarly, any old icon is destroyed when this method replaces it with a new one. This can be avoided via:
591 |SendMessage(0x040F, PartNumber - 1, HICON, SB) ; 0x040F is SB_SETICON.
Reacting to mouse clicks: Whenever the user clicks on the bar, the Click, DoubleClick or ContextMenu event is raised, and the Info or Item parameter contains the part number. However, the part number might be a very large integer if the user clicks near the sizing grip at the right side of the bar.
595 |Font and color: Although the font size, face, and style can be set via Gui.SetFont (just like normal controls), the text color cannot be changed. The status bar's background color may be changed by specifying in Options the word Background followed immediately by a color name (see color chart) or RGB value (the 0x prefix is optional). Examples: BackgroundSilver
, BackgroundFFDD99
, BackgroundDefault
. Note that the control must have Classic Theme appearance. Thus, the -Theme
option must be specified along with the Background option, e.g. -Theme BackgroundSilver
.
Hiding the StatusBar: Upon creation, the bar can be hidden via SB := MyGui.Add("StatusBar", "Hidden")
. To hide it sometime after creation, use SB.Visible := false
. To show it, use SB.Visible := true
. Note: Hiding the bar does not reduce the height of the window. If that is desired, one easy way is MyGui.Show("AutoSize")
.
Styles (rarely used): See the StatusBar styles table.
598 |Known limitations: 1) Any control that overlaps the status bar might sometimes get drawn on top of it. One way to avoid this is to dynamically shrink such controls via Size event. 2) Positioning and sizing options are ignored. 3) There is a limit of one status bar per window.
599 |Example: Example #1 at the bottom of the TreeView page demonstrates a multipart status bar.
600 | 601 |A large control containing multiple pages, each of which contains other controls. From this point forward, these pages are referred to as "tabs".
603 |There are three types of Tab control:
604 |For example:
610 |MyGui.Add("Tab3",, ["General", "View", "Settings"])611 |
Or:
612 |MyGui.AddTab3(, ["General", "View", "Settings"])613 |
Appearance:
614 | 615 |The last parameter above is an Array of tab names. After creating a Tab control, subsequently added controls automatically belong to its first tab. To change this, use the UseTab method below. For details and an example, see Tab Usage.
616 | 617 |Specifies the tab to which subsequently created controls will be added.
621 |GuiCtrl.UseTab(Value, ExactMatch)622 |
If blank or omitted, it defaults to 0, which causes subsequently created controls to be added outside the Tab control. Otherwise, specify 1 for the first tab, 2 for the second, etc.
627 |If Value is a string (even a numeric string), the tab whose leading name part matches Value will be used. The search is not case-sensitive. For example, if the control contains the tab "UNIX Text", specifying the word unix (lowercase) would be enough to use it. Use ExactMatch to change this matching behavior.
628 |Type: Boolean
631 |If omitted, it defaults to false.
632 |If false, the tab whose leading name part matches Value will be used, as described above.
633 |If true, Value has to be an exact match (but still not case-sensitive).
634 |To have one of the tabs pre-selected when the window first appears, include in Options the word Choose followed immediately by the number of a tab to be pre-selected. For example, Choose5
would pre-select the fifth tab (as with other options, it can also be a variable such as "Choose" Var
). After the control is created, use GuiControl.Value, GuiControl.Text or GuiControl.Choose to change the selected tab, and GuiControl.Add or GuiControl.Delete to add or remove tabs.
After creating a Tab control, subsequently added controls automatically belong to its first tab. This can be changed at any time by using the UseTab method as follows (in this case, Tab is the GuiControl object of the first tab control and Tab2 of the second one):
641 |Tab.UseTab() ; Future controls are not part of any tab control. 642 | Tab.UseTab(3) ; Future controls are owned by the third tab of the current tab control. 643 | Tab2.UseTab(3) ; Future controls are owned by the third tab of the second tab control. 644 | Tab.UseTab("Name") ; Future controls are owned by the tab whose name starts with Name (not case-sensitive). 645 | Tab.UseTab("Name", true) ; Same as above but requires exact match (not case-sensitive).646 |
It is also possible to use any of the examples above to assign controls to a tab or tab-control that does not yet exist (except in the case of the Name method). But in that case, the relative positioning options described below are not supported.
647 |Positioning: When each tab of a Tab control receives its first sub-control, that sub-control will have a special default position under the following conditions: 1) The X and Y coordinates are both omitted, in which case the first sub-control is positioned at the upper-left corner of the tab control's interior (with a standard margin), and sub-controls beyond the first are positioned beneath the previous control; 2) The X+n and/or Y+n positioning options are specified, in which case the sub-control is positioned relative to the upper-left corner of the tab control's interior. For example, specifying x+10 y+10
would position the control 10 pixels right and 10 pixels down from the upper left corner.
Current tab: GuiControl.Value returns the position number of the currently selected tab (the first tab is 1, the second is 2, etc.), while GuiControl.Text returns the text of the currently selected tab. Gui.Submit stores the text, unless the word AltSubmit is in the control's Options, in which case it stores the position number of the tab.
649 |Detecting tab selection: Whenever the user switches tabs, the Change event is raised.
650 |Keyboard navigation: The user may press Ctrl+PgDn/PgUp to navigate from page to page in a tab control; if the keyboard focus is on a control that does not belong to a Tab control, the window's first Tab control will be navigated. Ctrl+Tab and Ctrl+Shift+Tab may also be used except that they will not work if the currently focused control is a multi-line Edit control.
651 |Limits: Each window may have no more than 255 tab controls. Each tab control may have no more than 256 tabs (pages). In addition, a tab control may not contain other tab controls.
652 | 653 |Parent window: The parent window of a control affects the positioning and visibility of the control and tab-key navigation order. If a sub-control is added to an existing Tab3 control, its parent window is the "tab dialog", which fills the tab control's display area. Most other controls, including sub-controls of Tab or Tab2 controls, have no parent other than the GUI window itself.
655 |Positioning: For Tab and Tab2, sub-controls do not necessarily need to exist within their tab control's boundaries: they will still be hidden and shown whenever their tab is selected or de-selected. This behavior is especially appropriate for the "buttons" style described below.
656 |For Tab3, sub-controls assigned to a tab before the tab control is created behave as though added to a Tab or Tab2 control. All other sub-controls are visible only within the display area of the tab control.
657 |If a Tab3 control is moved, its sub-controls are moved with it. Tab and Tab2 controls do not have this behavior.
658 |In the rare case that WinMove (or an equivalent DllCall) is used to move a control, the coordinates must be relative to the parent window of the control, which might not be the GUI (see above). By contrast, GuiControl.Move takes GUI coordinates and ControlMove takes window coordinates, regardless of the control's parent window.
659 |Autosizing: If not specified by the script, the width and/or height of the Tab3 control are automatically calculated at one of the following times (whichever comes first after the control is created):
660 |The calculated size accounts for sub-controls which exist when autosizing occurs, plus the default margins. The size is calculated only once, and will not be recalculated even if controls are added later. If the Tab3 control is empty, it receives the same default size as a Tab or Tab2 control.
665 |Tab and Tab2 controls are not autosized; they receive an arbitrary default size.
666 |Tab-key navigation order: The navigation order via Tab usually depends on the order in which the controls are created. When tab controls are used, the order also depends on the type of tab control:
667 |Notification messages (Tab3): Common and Custom controls typically send notification messages to their parent window. Any WM_COMMAND, WM_NOTIFY, WM_VSCROLL, WM_HSCROLL or WM_CTLCOLOR' messages received by a Tab3 control's tab dialog are forwarded to the GUI window and can be detected by using OnMessage. If the tab control is themed and the sub-control lacks the +BackgroundTrans option, WM_CTLCOLORSTATIC is fully handled by the tab dialog and not forwarded. Other notification messages (such as custom messages) are not supported.
673 |Known issues with Tab2:
674 |Known issues with Tab:
680 |Choose: See above.
688 |Background: Specify -Background
(minus Background) to override the window's custom background color and use the system's default Tab control color. Specify +Theme -Background
to make the Tab control conform to the current desktop theme. However, most control types will look strange inside such a Tab control because their backgrounds will not match that of the tab control. This can be fixed for some control types (such as Text) by adding BackgroundTrans to their options.
Buttons: Creates a series of buttons at the top of the control rather than a series of tabs (in this case, there will be no border by default because the display area does not typically contain controls).
690 |Left/Right/Bottom: Specify one of these words to have the tabs on the left, right, or bottom side instead of the top. See TCS_VERTICAL for limitations on Left and Right.
691 |Wrap: Specify -Wrap
(minus Wrap) to prevent the tabs from taking up more than a single row (in which case if there are too many tabs to fit, arrow buttons are displayed to allow the user to slide more tabs into view).
To specify the number of rows of text inside the control (or its height and width), see positioning and sizing of controls.
693 |Icons in Tabs: An icon may be displayed next to each tab's name/text via SendMessage. This is demonstrated in the archived forum topic Icons in tabs.
694 | 695 |A region containing borderless text that the user cannot edit. Often used to label other controls.
697 |For example:
698 |MyGui.Add("Text",, "Please enter your name:")699 |
Or:
700 |MyGui.AddText(, "Please enter your name:")701 |
Appearance:
702 | 703 |In this case, the last parameter is the string to display. It may contain linefeeds (`n) to start new lines. In addition, a single long line can be broken up into several shorter ones by means of a continuation section.
704 |If a width (W) is specified in Options but no rows (R) or height (H), the control's text will be word-wrapped as needed, and the control's height will be set automatically.
705 | 706 |To detect when the user clicks the text, use the Click event. For example:
707 |MyGui := Gui() 708 | FakeLink := MyGui.Add("Text", "", "Click here to launch Google.") 709 | FakeLink.SetFont("underline cBlue") 710 | FakeLink.OnEvent("Click", LaunchGoogle) 711 | 712 | ; Alternatively, a Link control can be used: 713 | MyGui.Add("Link",, 'Click <a href="www.google.com">here</a> to launch Google.') 714 | MyGui.Show() 715 | 716 | LaunchGoogle(*) { 717 | Run("www.google.com") 718 | }719 |
Text controls also support the DoubleClick event.
720 |Only Text controls with the SS_NOTIFY (0x100) style send click and double-click notifications, so OnEvent automatically adds this style when a Click or DoubleClick callback is registered. The SS_NOTIFY style causes the OS to automatically copy the control's text to the clipboard when it is double-clicked.
721 |An ampersand (&) may be used in the text to underline one of its letters. For example:
722 |MyGui.Add("Text",, "&First Name:") 723 | MyGui.Add("Edit")724 |
In the example above, the letter F will be underlined, which allows the user to press the shortcut key Alt+F to set keyboard focus to the first input-capable control that was added after the text control. To instead display a literal ampersand, specify two consecutive ampersands (&&). To disable all special treatment of ampersands, include 0x80 in the control's options.
725 |See general options for other options like Right, Center, and Hidden. See also: positioning and sizing of controls.
726 | 727 |A TreeView displays a hierarchy of items by indenting child items beneath their parents. The most common example is Explorer's tree of drives and folders.
729 |For example:
730 |MyGui.Add("TreeView", "r10")731 |
Or:
732 |MyGui.AddTreeView("r10")733 |
Appearance:
734 | 735 |See the separate TreeView page for more information.
736 | 737 |A pair of arrow buttons that the user can click to increase or decrease a value. By default, an UpDown control automatically snaps onto the previously added control. This previous control is known as the UpDown's buddy control. The most common example is a "spinner", which is an UpDown attached to an Edit control.
739 |For example:
740 |MyGui.Add("Edit") 741 | MyGui.Add("UpDown", "vMyUpDown Range1-10", 5)742 |
Or:
743 |MyGui.AddEdit() 744 | MyGui.AddUpDown("vMyUpDown Range1-10", 5)745 |
Appearance:
746 | 747 |In the example above, the Edit control is the UpDown's buddy control. Whenever the user presses one of the arrow buttons, the number in the Edit control is automatically increased or decreased.
748 |An UpDown's buddy control can also be a Text control or ListBox. However, due to OS limitations, controls other than these (such as ComboBox and DropDownList) might not work properly with the Change event and other features.
749 |Specify the UpDown's starting position as the last parameter (if omitted, it starts off at 0 or the number in the allowable range that is closest to 0).
750 |When Gui.Submit or GuiControl.Value is used, the return value is the current numeric position of the UpDown. If the UpDown is attached to an Edit control and you do not wish to validate the user's input, it is best to use the UpDown's value rather than the Edit's. This is because the UpDown will always yield an in-range number, even when the user has typed something non-numeric or out-of-range in the Edit control. On a related note, numbers with more than three digits get a thousands separator (such as comma) by default. These separators are returned by the Edit control but not by the UpDown control.
751 |Whenever the user clicks one of the arrow buttons or presses an arrow key on the keyboard, the Change event is raised.
752 | 753 |Horz: Makes the control's buttons point left/right rather than up/down. By default, Horz also makes the control isolated (no buddy). This can be overridden by specifying Horz 16
in the control's options.
Left: Puts the UpDown on the left side of its buddy rather than the right.
756 |Range: Sets the range to be something other than 0 to 100. After the word Range, specify the minimum, a dash, and maximum. For example, Range1-1000
would allow a number between 1 and 1000 to be selected; Range-50-50
would allow a number between -50 and 50; and Range-10--5
would allow a number between -10 and -5. The minimum and maximum may be swapped to cause the arrows to move in the opposite of their normal direction. The broadest allowable range is -2147483648-2147483647. Finally, if the buddy control is a ListBox, the range defaults to 32767-0 for verticals and the inverse for horizontals (Horz).
Wrap: Causes the control to wrap around to the other end of its range when the user attempts to go beyond the minimum or maximum. Without Wrap, the control stops when the minimum or maximum is reached.
758 |16: Specify -16 (minus 16) to cause a vertical UpDown to be isolated; that is, it will have no buddy. This also causes the control to obey any specified width, height, and position rather than conforming to the size of its buddy control. In addition, an isolated UpDown tracks its own position internally. This position can be retrieved normally by means such as Gui.Submit or GuiControl.Value.
759 |0x80: Include 0x80 in Options to omit the thousands separator that is normally present between every three decimal digits in the buddy control. However, this style is normally not used because the separators are omitted from the number whenever the script retrieves it from the UpDown control itself (rather than its buddy control).
760 |Increments other than 1: This script demonstrates how to change an UpDown's increment to a value other than 1 (such as 5 or 0.1).
761 |Hexadecimal number format: The number format displayed inside the buddy control may be changed from decimal to hexadecimal by following this example:
762 |SendMessage 0x046D, 16, 0, "msctls_updown321" ; 0x046D is UDM_SETBASE763 |
However, this affects only the buddy control, not the UpDown's reported position.
764 |See also: positioning and sizing of controls.
765 | 766 |ListView, TreeView, Gui(), Gui object, GuiControl object, Menu object
768 | 769 | 770 | 771 | -------------------------------------------------------------------------------- /docs/lib/GuiCtrlFromHwnd.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Retrieves the GuiControl object of a GUI control associated with the specified window handle.
17 |GuiControlObj := GuiCtrlFromHwnd(Hwnd)
18 |
19 | Type: Integer
24 |The window handle (HWND) of a GUI control, or a child window of such a control (e.g. the Edit control of a ComboBox). The control must have been created by the current script via Gui.Add.
25 |Type: Object or String (empty)
30 |This function returns the GuiControl object associated with the specified HWND, or an empty string if there isn't one or the HWND is invalid.
31 | 32 |For example, a HWND of a GUI control can be retrieved via GuiControl.Hwnd, MouseGetPos or OnMessage.
34 | 35 |Gui(), Gui object, GuiControl object, GuiFromHwnd, Control Types, ListView, TreeView, Menu object, Control functions, MsgBox, FileSelect, DirSelect
37 | 38 |See the ToolTip example on the Gui object page.
40 | 41 | 42 | -------------------------------------------------------------------------------- /docs/lib/GuiFromHwnd.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Retrieves the Gui object of a GUI window associated with the specified window handle.
17 |GuiObj := GuiFromHwnd(Hwnd , RecurseParent)18 | 19 |
Type: Integer
24 |The window handle (HWND) of a GUI window previously created by the script, or if RecurseParent is true, any child window of a GUI window created by the script.
25 |Type: Boolean
29 |If this parameter is true and Hwnd identifies a child window which is not a GUI, the function searches for and retrieves its closest parent window which is a GUI. Otherwise, the function returns an empty string if Hwnd does not directly identify a GUI window.
30 |Type: Object or String (empty)
35 |This function returns the Gui object associated with the specified HWND, or an empty string if there isn't one or the HWND is invalid.
36 | 37 |For example, the HWND of a GUI window may be passed to an OnMessage function, or can be retrieved via Gui.Hwnd, WinExist or some other method.
39 | 40 |Gui(), Gui object, GuiControl object, GuiCtrlFromHwnd, Control Types, ListView, TreeView, Menu object, Control functions, MsgBox, FileSelect, DirSelect
42 | 43 |Retrieves the Gui object by using the HWND of the GUI window just created and reports its title.
46 |MyGui := Gui(, "Title of Window") 47 | MyGui.Add("Text",, "Some text to display.") 48 | MyGui.Show() 49 | 50 | MsgBox(GuiFromHwnd(MyGui.Hwnd).Title)51 |
Registers a function or method to be called when a control notification is received via the WM_COMMAND message.
16 |GuiCtrl.OnCommand(NotifyCode, Callback , AddRemove)17 | 18 |
Type: Integer
23 |The control-defined notification code to monitor.
24 |Type: String or Function Object
29 |The function, method or object to call when the event is raised.
30 |If the GUI has an event sink (that is, if Gui()'s EventObj parameter was specified), this parameter may be the name of a method belonging to the event sink. Otherwise, this parameter must be a function object.
31 |The callback accepts one parameter and can be defined as follows:
32 |MyCallback(GuiCtrl) { ...33 |
Although the name you give the parameter does not matter, it is assigned the GuiControl object of the current GUI control.
34 |You can omit the callback's parameter if the corresponding information is not needed, but in this case an asterisk must be specified, e.g. MyCallback(*)
.
The notes for OnEvent regarding this
and bound functions also apply to OnCommand.
If multiple callbacks have been registered for an event, a callback may return a non-empty value to prevent any remaining callbacks from being called.
37 |The callback's return value is ignored by the GUI control.
38 |Type: Integer
43 |If omitted, it defaults to 1. Otherwise, specify one of the following numbers:
44 |Certain types of controls send a WM_COMMAND message whenever an interesting event occurs. These are usually standard Windows controls which have been around a long time, as newer controls use the WM_NOTIFY message (see OnNotify). Commonly used notification codes are translated to events, which the script can monitor with OnEvent.
54 |The message's parameters contain the control ID, HWND and notification code, which AutoHotkey uses to dispatch the notification to the appropriate callback. There are no additional parameters.
55 |To determine which notifications are available (if any), refer to the control's documentation. Control Library (Microsoft Docs) contains links to each of the Windows common controls (however, only a few of these use WM_COMMAND). The notification codes (numbers) can be found in the Windows SDK, or by searching the Internet.
56 | 57 |These notes for OnEvent also apply to OnCommand: Threads, Destroying the GUI.
59 |OnNotify can be used for notifications which are sent as a WM_NOTIFY message.
60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /docs/lib/GuiOnEvent.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Registers a function or method to be called when the given event is raised by a GUI window or control.
16 |Gui.OnEvent(EventName, Callback , AddRemove) 17 | GuiCtrl.OnEvent(EventName, Callback , AddRemove)18 | 19 |
Type: String
24 |The name of the event. See Events further below.
25 |Type: String or Function Object
30 |The function, method or object to call when the event is raised.
31 |If the GUI has an event sink (that is, if Gui()'s EventObj parameter was specified), this parameter may be the name of a method belonging to the event sink. Otherwise, this parameter must be a function object.
32 |For details about the parameters, return value, naming, and more, see the following sections.
33 |Type: Integer
38 |If omitted, it defaults to 1. Otherwise, specify one of the following numbers:
39 |If the callback is a method registered by name, its hidden this parameter seamlessly receives the event sink object (that is, the object to which the method belongs). This parameter is not shown in the parameter lists in this documentation.
49 |Since Callback can be an object, it can be a BoundFunc object which inserts additional parameters at the beginning of the parameter list and then calls another function. This is a general technique not specific to OnEvent, so is generally ignored by the rest of this documentation.
50 |The callback's first explicit parameter is the Gui or GuiControl object which raised the event. The only exception is that this parameter is omitted when a Gui handles its own events, since this
already contains a reference to the Gui.
Many events pass additional parameters about the event, as described for each event.
52 |As with all methods or functions called dynamically, the callback is not required to declare parameters which the callback itself does not need, but in this case an asterisk must be specified as the final parameter, e.g. MyCallback(Param1, *)
. If an event has more parameters than are declared by the callback, they will simply be ignored (unless the callback is variadic).
The callback can declare more parameters than the event provides if (and only if) the additional parameters are declared optional. However, the use of optional parameters is not recommended as future versions of the program may extend an event with additional parameters, in which case the optional parameters would stop receiving their default values.
54 | 55 |If multiple callbacks have been registered for an event, a callback may return a non-empty value to prevent any remaining callbacks from being called.
57 |The return value may have additional meaning for specific events. For example, a Close callback may return a non-zero number (such as true
) to prevent the GUI window from closing.
By convention, the syntax of each event below is shown with a function name of the form ObjectType_EventName
, for clarity. Scripts are not required to follow this convention, and can use any valid function name.
Each event callback is called in a new thread, and therefore starts off fresh with the default values for settings such as SendMode. These defaults can be changed during script startup.
64 |Whenever a GUI thread is launched, that thread's last found window starts off as the GUI window itself. This allows functions for windows and controls -- such as WinGetStyle, WinSetTransparent, and ControlGetFocus -- to omit WinTitle and WinText when operating upon the GUI window itself (even if it is hidden).
65 |Except where noted, each event is limited to one thread at a time, per object. If an event is raised before a previous thread started by that event finishes, it is usually discarded. To prevent this, use Critical as the callback's first line (however, this will also buffer/defer other threads such as the press of a hotkey).
66 | 67 |When a GUI is destroyed, all event callbacks are released. Therefore, if the GUI is destroyed while an event is being dispatched, subsequent event callbacks are not called. For clarity, callbacks should return a non-empty value after destroying the GUI.
69 | 70 |The following events are supported by Gui objects:
72 |Event | Raised when... |
---|---|
Close | The window is closed. |
ContextMenu | The user right-clicks within the window or presses Menu or Shift+F10. |
DropFiles | Files/folders are dragged and dropped onto the window. |
Escape | The user presses Esc while the GUI window is active. |
Size | The window is resized, minimized, maximized or restored. |
The following events are supported by GuiControl objects, depending on the control type:
81 |Event | Raised when... |
---|---|
Change | The control's value changes. |
Click | The control is clicked. |
DoubleClick | The control is double-clicked. |
ColClick | One of the ListView's column headers is clicked. |
ContextMenu | The user right-clicks the control or presses Menu or Shift+F10 while the control has the keyboard focus. |
Focus | The control gains the keyboard focus. |
LoseFocus | The control loses the keyboard focus. |
ItemCheck | A ListView or TreeView item is checked or unchecked. |
ItemEdit | A ListView or TreeView item's label is edited by the user. |
ItemExpand | A TreeView item is expanded or collapsed. |
ItemFocus | The focused item changes in a ListView. |
ItemSelect | A ListView or TreeView item is selected, or a ListView item is deselected. |
Launched when the user or another program attempts to close the window, such as by pressing the X button in its title bar, selecting "Close" from its system menu, or calling WinClose.
101 |Gui_Close(GuiObj)
102 | By default, the window is automatically hidden after the callback returns, or if no callbacks were registered. A callback can prevent this by returning 1 (or true
), which will also prevent any remaining callbacks from being called. The callback can hide the window immediately by calling GuiObj.Hide, or destroy the window by calling GuiObj.Destroy.
For example, this GUI shows a confirmation prompt before closing:
104 |MyGui := Gui() 105 | MyGui.AddText("", "Press Alt+F4 or the X button in the title bar.") 106 | MyGui.OnEvent("Close", MyGui_Close) 107 | MyGui_Close(thisGui) { ; Declaring this parameter is optional. 108 | if MsgBox("Are you sure you want to close the GUI?",, "y/n") = "No" 109 | return true ; true = 1 110 | } 111 | MyGui.Show()112 | 113 |
Launched whenever the user right-clicks anywhere in the window except the title bar and menu bar. It is also launched in response to pressing Menu or Shift+F10.
115 |Gui_ContextMenu(GuiObj, GuiCtrlObj, Item, IsRightClick, X, Y)
116 | Type: Object or String (empty)
118 |The GuiControl object of the control that received the event (blank if none).
Type: Integer
121 |When a ListBox, ListView, or TreeView is the target of the context menu (as determined by GuiCtrlObj), Item specifies which of the control's items is the target.
122 |ListBox: The position number of the currently focused item. Note that a standard ListBox does not focus an item when it is right-clicked, so this might not be the clicked item.
123 |ListView and TreeView: For right-clicks, Item contains the clicked item's row number or ID (or 0 if the user clicked somewhere other than an item). For Menu and Shift+F10, Item contains the selected item's row number or ID.
Type: Integer (boolean)
126 |One of the following values:
127 |Type: Integer
133 |The X and Y coordinates of where the script should display the menu (e.g. MyContextMenu.Show X, Y
). Coordinates are relative to the upper-left corner of the window's client area.
Unlike most other GUI events, the ContextMenu event can have more than one concurrent thread.
136 |Each control can have its own ContextMenu event callback which is called before any callback registered for the Gui object. Control-specific callbacks omit the GuiObj parameter, but all other parameters are the same.
137 |Note: Since Edit and MonthCal controls have their own context menu, a right-click in one of them will not launch the ContextMenu event.
138 | 139 |Launched whenever files/folders are dropped onto the window as part of a drag-and-drop operation (but if this callback is already running, drop events are ignored).
141 |Gui_DropFiles(GuiObj, GuiCtrlObj, FileArray, X, Y)
142 | Type: Object or String (empty)
146 |The GuiControl object of the control upon which the files were dropped (blank if none).
Type: Array
151 |An array of filenames, where FileArray[1]
is the first file and FileArray.Length
returns the number of files. A for-loop can be used to iterate through the files:
Gui_DropFiles(GuiObj, GuiCtrlObj, FileArray, X, Y) { 153 | for i, DroppedFile in FileArray 154 | MsgBox "File " i " is:`n" DroppedFile 155 | }
Type: Integer
160 |The X and Y coordinates of where the files were dropped, relative to the upper-left corner of the window's client area.
161 |Launched when the user presses Esc while the GUI window is active.
166 |Gui_Escape(GuiObj)
167 | By default, pressing Esc has no effect. Known limitation: If the first control in the window is disabled (possibly depending on control type), the Escape event will not be launched. There may be other circumstances that produce this effect.
168 | 169 |Launched when the window is resized, minimized, maximized, or restored.
171 |Gui_Size(GuiObj, MinMax, Width, Height)
172 | Type: Integer
175 |One of the following values:
176 |Note that a maximized window can be resized without restoring/un-maximizing it, so a value of 1 does not necessarily mean that this event was raised in response to the user maximizing the window.
Type: Integer
184 |The new width and height of the window's client area, which is the area excluding title bar, menu bar, and borders.
A script may use the Size event to reposition and resize controls in response to the user's resizing of the window.
187 |When the window is resized (even by the script), the Size event might not be raised immediately. As with other window events, if the current thread is uninterruptible, the Size event won't be raised until the thread becomes interruptible. If the script has just resized the window, follow this example to ensure the Size event is raised immediately:
188 |Critical "Off" ; Even if Critical "On" was never used. 189 | Sleep -1190 |
Gui.Show automatically does a Sleep -1
, so it is generally not necessary to call Sleep in that case.
Raised when the control's value changes.
196 |Ctrl_Change(GuiCtrlObj, Info)
197 | Type: Integer
201 |Slider: A numeric value indicating how the slider moved. For details, see Detecting Changes.
202 |For all other controls, Info currently has no meaning.
203 |To retrieve the control's new value, use GuiCtrlObj.Value.
206 |Applies to: DDL, ComboBox, ListBox, Edit, DateTime, MonthCal, Hotkey, UpDown, Slider, Tab.
207 | 208 |Raised when the control is clicked.
210 |Ctrl_Click(GuiCtrlObj, Info) 211 | Link_Click(GuiCtrlObj, Info, Href)212 |
Type: Integer
216 |ListView: The row number of the clicked item, or 0 if the mouse was not over an item.
217 |TreeView: The ID of the clicked item, or 0 if the mouse was not over an item.
218 |Link: The link's ID attribute (a string) if it has one, otherwise the link's index (an integer).
219 |StatusBar: The part number of the clicked section (however, the part number might be a very large integer if the user clicks near the sizing grip at the right side of the bar).
220 |For all other controls, Info currently has no meaning.
221 |Type: String
225 |Link: The link's HREF attribute. Note that if a Click event callback is registered, the HREF attribute is not automatically executed.
226 |Applies to: Text, Pic, Button, CheckBox, Radio, ListView, TreeView, Link, StatusBar.
229 | 230 |Raised when the control is double-clicked.
232 |Ctrl_DoubleClick(GuiCtrlObj, Info)
233 | Type: Integer
237 |ListView, TreeView and StatusBar: Same as for the Click event.
238 |ListBox: The position number of the currently focused item. Double-clicking empty space below the last item usually focuses the last item and leaves the selection as it was.
239 |Applies to: Text, Pic, Button, CheckBox, Radio, ComboBox, ListBox, ListView, TreeView, StatusBar.
242 | 243 |Raised when one of the ListView's column headers is clicked.
245 |Ctrl_ColClick(GuiCtrlObj, Info)
246 | Type: Integer
250 |The one-based column number that was clicked. This is the original number assigned when the column was created; that is, it does not reflect any dragging and dropping of columns done by the user.
251 |Applies to: ListView.
254 | 255 |Raised when the user right-clicks the control or presses Menu or Shift+F10 while the control has the keyboard focus.
257 |Ctrl_ContextMenu(GuiCtrlObj, Item, IsRightClick, X, Y)
258 | For details, see ContextMenu.
259 |Applies to: All controls except Edit and MonthCal (and the Edit control within a ComboBox), which have their own standard context menu.
260 | 261 |Raised when the control gains or loses the keyboard focus.
263 |Ctrl_Focus(GuiCtrlObj, Info) 264 | Ctrl_LoseFocus(GuiCtrlObj, Info)265 |
Reserved.
Applies to: Button, CheckBox, Radio, DDL, ComboBox, ListBox, ListView, TreeView, Edit, DateTime.
270 |Not supported: Hotkey, Slider, Tab and Link. Note that Text, Pic, MonthCal, UpDown and StatusBar controls do not accept the keyboard focus.
271 | 272 |Raised when a ListView or TreeView item is checked or unchecked.
274 |Ctrl_ItemCheck(GuiCtrlObj, Item, Checked)
275 | Applies to: ListView, TreeView.
276 | 277 |Raised when a ListView or TreeView item's label is edited by the user.
279 |Ctrl_ItemEdit(GuiCtrlObj, Item)
280 | An item's label can only be edited if -ReadOnly
has been used in the control's options.
Applies to: ListView, TreeView.
282 | 283 |Raised when a TreeView item is expanded or collapsed.
285 |Ctrl_ItemExpand(GuiCtrlObj, Item, Expanded)
286 | Applies to: TreeView.
287 | 288 |Raised when the focused item changes in a ListView.
290 |Ctrl_ItemFocus(GuiCtrlObj, Item)
291 | Applies to: ListView.
292 | 293 |Raised when a ListView or TreeView item is selected, or a ListView item is deselected.
295 |ListView_ItemSelect(GuiCtrlObj, Item, Selected) 296 | TreeView_ItemSelect(GuiCtrlObj, Item)297 |
Applies to: ListView, TreeView.
298 |ListView: This event is raised once for each item being deselected or selected, so can be raised multiple times in response to a single action by the user.
299 | 300 | 301 |Other types of GUI events can be detected and acted upon via OnNotify, OnCommand or OnMessage. For example, a script can display context-sensitive help via ToolTip whenever the user moves the mouse over particular controls in the window. This is demonstrated in the GUI ToolTip example.
303 | 304 | 305 | 306 | 307 | -------------------------------------------------------------------------------- /docs/lib/GuiOnNotify.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Registers a function or method to be called when a control notification is received via the WM_NOTIFY message.
16 |GuiCtrl.OnNotify(NotifyCode, Callback , AddRemove)17 | 18 |
Type: Integer
23 |The control-defined notification code to monitor.
24 |Type: String or Function Object
29 |The function, method or object to call when the event is raised.
30 |If the GUI has an event sink (that is, if Gui()'s EventObj parameter was specified), this parameter may be the name of a method belonging to the event sink. Otherwise, this parameter must be a function object.
31 |The callback accepts two parameters and can be defined as follows:
32 |MyCallback(GuiCtrl, lParam) { ...33 |
Although the names you give the parameters do not matter, the following values are sequentially assigned to them:
34 |You can omit one or more parameters from the end of the callback's parameter list if the corresponding information is not needed, but in this case an asterisk must be specified as the final parameter, e.g. MyCallback(Param1, *)
.
The notes for OnEvent regarding this
and bound functions also apply to OnNotify.
If multiple callbacks have been registered for an event, a callback may return a non-empty value to prevent any remaining callbacks from being called.
41 |The callback's return value may have additional meaning, depending on the notification. For example, the ListView notification LVN_BEGINLABELEDIT (-175 or -105) prevents the user from editing the label if the callback returns TRUE (1).
42 |Type: Integer
47 |If omitted, it defaults to 1. Otherwise, specify one of the following numbers:
48 |Certain types of controls send a WM_NOTIFY message whenever an interesting event occurs or the control requires information from the program. The lParam parameter of this message contains a pointer to a structure containing information about the notification. The type of structure depends on the notification code and the type of control which raised the notification, but is always based on NMHDR.
58 |To determine which notifications are available (if any), what type of structure they provide and how they interpret the return value, refer to the control's documentation. Control Library (Microsoft Docs) contains links to each of the Windows common controls. The notification codes (numbers) can be found in the Windows SDK, or by searching the Internet.
59 |AutoHotkey uses the idFrom and hwndFrom fields to identify which control sent the notification, in order to dispatch it to the appropriate object. The code field contains the notification code. Since these must match up to GuiCtrl and NotifyCode used to register the callback, they are rarely useful to the script.
60 | 61 |These notes for OnEvent also apply to OnNotify: Threads, Destroying the GUI.
63 |OnCommand can be used for notifications which are sent as a WM_COMMAND message.
64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /docs/lib/HasBase.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns a non-zero number if the specified value is derived from the specified base object.
17 | 18 |HasBase := HasBase(Value, BaseObj)
19 | Any value, of any type.
24 |Type: Object
28 |The potential base object to test.
29 |Type: Integer (boolean)
34 |This function returns 1 (true) if BaseObj is in Value's chain of base objects, otherwise 0 (false).
35 | 36 |The following code is roughly equivalent to this function:
38 |MyHasBase(Value, BaseObj) { 39 | b := Value 40 | while b := ObjGetBase(b) 41 | if b = BaseObj 42 | return true 43 | return false 44 | }45 |
For example, HasBase(Obj, Array.Prototype)
is true if Obj is an instance of Array or any derived class. This the same check performed by Obj is Array
; however, instances can be based on other instances, whereas is
requires a Class.
HasBase accepts both objects and primitive values. For example, HasBase(1, 0.base)
returns true.
Objects, Obj.Base, ObjGetBase, HasMethod, HasProp
50 | 51 |Illustrates the use of this function.
54 |55 | thebase := {key: "value"} 56 | derived := {base: thebase} 57 | MsgBox HasBase(thebase, derived) ; 0 58 | MsgBox HasBase(derived, thebase) ; 1 59 |60 |
Returns a non-zero number if the specified value has a method by the specified name.
17 | 18 |HasMethod := HasMethod(Value , Name, ParamCount)19 |
Type: Any
24 |Any value, of any type except ComObject.
25 |Type: String
29 |If omitted, Value itself is checked whether it is callable. Otherwise, specify the method name to check for.
30 |If omitted (or if the parameter count was not verified), a basic check is performed for a Call method to verify that the object is most likely callable.
35 |Otherwise, specify the number of parameters that would be passed to the method or function. If specified, the method's MinParams, MaxParams and IsVariadic properties may be queried to verify that it can accept this number of parameters. If those properties are not present, the parameter count is not verified.
36 |This count should not include the implicit this
parameter.
Type: Integer (boolean)
42 |This function returns 1 (true) if a method was found and passed validation (if performed), otherwise 0 (false).
43 | 44 |HasMethod has the same limitations as GetMethod.
46 |This function can be used to estimate whether a value supports a specific action. For example, values without a Call method cannot be called or passed to SetTimer, while values without either an __Enum method or a Call method cannot be passed to For. However, the existence of a method does not guarantee that it can be called, since there are requirements that must be met, such as parameter count.
47 |When ParamCount is specified, the validation this function performs is equivalent to the validation performed by built-in functions such as SetTimer.
48 |A return value of 0 (false) does not necessarily indicate that the method cannot be called, as the value may have a __Call meta-function. However, __Call is not triggered in certain contexts, such as when __Enum is being called by For. If __Call is present, there is no way to detect which methods it may support.
49 |This function supports primitive values.
50 | 51 |Objects, HasBase, HasProp, GetMethod
53 | 54 |Illustrates the use of this function.
57 |58 | MsgBox HasMethod(0, "HasMethod") ; 1 59 | MsgBox HasMethod(0, "Call") ; 0 60 |61 |
Returns a non-zero number if the specified value has a property by the specified name.
17 | 18 |HasProp := HasProp(Value, Name)
19 | Type: Any
24 |Any value, of any type except ComObject.
25 |Type: String
29 |The property name to check for.
30 |Type: Integer (boolean)
35 |This function returns 1 (true) if the value has a property by this name, otherwise 0 (false).
36 | 37 |This function does not test for the presence of a __Get or __Set meta-function. If present, there is no way to detect the exact set of properties that it may implement.
39 |This function supports primitive values.
40 | 41 |Illustrates the use of this function.
47 |48 | MsgBox HasProp({}, "x") ; 0 49 | MsgBox HasProp({x:1}, "x") ; 1 50 | MsgBox HasProp(0, "Base") ; 1 51 |52 |
Specifies the criteria for subsequently created or modified hotkey variants and hotstring variants.
17 | 18 |20 | HotIf "Expression" 21 | HotIf Callback 22 |23 | 24 |
Type: String
30 |If omitted, blank criteria will be set (turns off context-sensitivity). Otherwise, the criteria will be set to an existing #HotIf expression. The expression is usually written as a quoted string, but can also be a variable or expression which returns text matching a #HotIf expression.
31 |Note: The HotIf function uses the string that you pass to it, not the original source code. Escape sequences are resolved when the script loads, so only the resulting characters are considered; for example, HotIf 'x = "`t"'
and HotIf 'x = "' A_Tab '"'
both correspond to #HotIf x = "`t"
.
For an example, see #HotIf example #5.
33 |Type: Function Object
38 |If omitted, blank criteria will be set (turns off context-sensitivity). Otherwise, the criteria will be set to a given function object. Subsequently-created hotkeys and hotstrings will only execute if the callback returns a non-zero number. This is like HotIf "Expression"
, except that each hotkey and hotstring can have many hotkey variants or hotstring variants (one per object).
The callback accepts one parameter and can be defined as follows:
40 |MyCallback(HotkeyName) { ...41 |
Although the name you give the parameter does not matter, it is assigned the hotkey name or hotstring name.
42 |You can omit the callback's parameter if the corresponding information is not needed, but in this case an asterisk must be specified, e.g. MyCallback(*)
.
Once passed to the HotIf function, the object will never be deleted (but memory will be reclaimed by the OS when the process exits).
44 |For an example, see example #2 below or Hotkey example #6.
45 |51 | HotIfWinActive WinTitle, WinText 52 | HotIfWinExist WinTitle, WinText 53 | HotIfWinNotActive WinTitle, WinText 54 | HotIfWinNotExist WinTitle, WinText 55 |56 | 57 |
Type: String
63 |If both are omitted, blank criteria will be set (turns off context-sensitivity). Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility). Depending on which function is called, affected hotkeys and hotstrings are in effect only while the target window is active, exists, is not active, or does not exist.
64 |Since the parameters are evaluated before the function is called, any variable reference becomes permanent at that moment. In other words, subsequent changes to the contents of the variable are not seen by existing hotkeys and hotstrings.
65 |WinTitle and WinText have the same meaning as for WinActive or WinExist, but only strings can be used, and they are evaluated according to the default settings for SetTitleMatchMode and DetectHiddenWindows as set by the auto-execute thread.
66 |For an example, see example #1 below.
67 | 68 |An exception is thrown if HotIf's parameter is invalid, such as if it does not match an existing expression or is not a valid callback function.
74 | 75 |The HotIf and HotIfWin functions allow context-sensitive hotkeys and hotstrings to be created and modified while the script is running (by contrast, the #HotIf directive is positional and takes effect before the script begins executing). For example:
77 |HotIfWinActive "ahk_class Notepad" 78 | Hotkey "^!e", MyFuncForNotepad ; Creates a hotkey that works only in Notepad.79 |
Using HotIf or one of the HotIfWin functions puts context sensitivity into effect for all subsequently created hotkeys and hotstrings in the current thread, and affects which hotkey or hotstring variants the Hotkey or Hotstring function modifies. Only the most recent call to the HotIf or HotIfWin function in the current thread will be in effect.
80 |To turn off context sensitivity (such as to make subsequently-created hotkeys and hotstrings work in all windows), call HotIf or one of the HotIfWin functions but omit the parameters. For example: HotIf
or HotIfWinActive
.
Before HotIf or one of the HotIfWin functions is used in a hotkey or hotstring thread, the Hotkey and Hotstring functions default to the same context as the hotkey or hotstring that launched the thread. In other words, Hotkey A_ThisHotkey, "Off"
turns off the current hotkey even if it is context-sensitive. All other threads default to creating or modifying global hotkeys and hotstrings, unless that default is overridden by using HotIf or one of the HotIfWin functions during script startup.
When a mouse or keyboard hotkey is disabled via HotIf, one of the HotIfWin functions, or the #HotIf directive, it performs its native function; that is, it passes through to the active window as though there is no such hotkey. However, controller hotkeys always pass through, whether they are disabled or not.
83 | 84 |Hotkeys, Hotstrings, Hotkey function, Hotstring function, #HotIf, Threads
86 | 87 |Similar to #HotIf example #1, this creates two hotkeys and one hotstring which only work when Notepad is active, and one hotkey which works for any window except Notepad. The main difference is that this example creates context-sensitive hotkeys and hotstrings at runtime, while the #HotIf example creates them at loadtime.
90 |HotIfWinActive "ahk_class Notepad" 91 | Hotkey "^!a", ShowMsgBox 92 | Hotkey "#c", ShowMsgBox 93 | Hotstring "::btw", "This replacement text will occur only in Notepad." 94 | HotIfWinActive 95 | Hotkey "#c", (*) => MsgBox("You pressed Win-C in a window other than Notepad.") 96 | 97 | ShowMsgBox(HotkeyName) 98 | { 99 | MsgBox "You pressed " HotkeyName " while Notepad is active." 100 | }101 |
Similar to the example above, but with a callback.
104 |HotIf MyCallback 105 | Hotkey "^!a", ShowMsgBox 106 | Hotkey "#c", ShowMsgBox 107 | Hotstring "::btw", "This replacement text will occur only in Notepad." 108 | HotIf 109 | Hotkey "#c", (*) => MsgBox("You pressed Win-C in a window other than Notepad.") 110 | 111 | MyCallback(*) 112 | { 113 | if WinActive("ahk_class Notepad") 114 | return true 115 | else 116 | return false 117 | } 118 | 119 | ShowMsgBox(HotkeyName) 120 | { 121 | MsgBox "You pressed " HotkeyName " while Notepad is active." 122 | }123 |
Creates, modifies, enables, or disables a hotkey while the script is running.
16 |17 | Hotkey KeyName , Action, Options 18 |19 | 20 |
Type: String
26 |Name of the hotkey's activation key, including any modifier symbols. For example, specify #c
for the Win+C hotkey.
If KeyName already exists as a hotkey -- either by the Hotkey function or a double-colon label in the script -- that hotkey will be updated with the values of the function's other parameters.
28 |When specifying an existing hotkey, KeyName is not case-sensitive. However, the names of keys must be spelled the same as in the existing hotkey (e.g. Esc is not the same as Escape for this purpose). Also, the order of modifier symbols such as ^!+#
does not matter. GetKeyName can be used to retrieve the standard spelling of a key name.
When a hotkey is first created -- either by the Hotkey function or the double-colon syntax in the script -- its key name and the ordering of its modifier symbols becomes the permanent name of that hotkey as reflected by ThisHotkey. This name is shared by all variants of the hotkey, and does not change even if the Hotkey function later accesses the hotkey with a different symbol ordering.
30 |If the hotkey variant already exists, its behavior is updated according to whether KeyName includes or excludes the tilde (~) prefix.
31 |The use hook ($) prefix can be added to existing hotkeys. This prefix affects all variants of the hotkey and cannot be removed.
32 |Type: Function Object or String
37 |If omitted and KeyName already exists as a hotkey, its action will not be changed. This is useful to change only the hotkey's Options. Otherwise, specify a callback, a hotkey name without trailing colons, or one of the special values listed below.
38 |Specify the function to call (as a new thread) when the hotkey is pressed.
40 |The callback accepts one parameter and can be defined as follows:
41 |MyCallback(HotkeyName) { ...42 |
Although the name you give the parameter does not matter, it is assigned the hotkey name.
43 |You can omit the callback's parameter if the corresponding information is not needed, but in this case an asterisk must be specified, e.g. MyCallback(*)
.
Hotkeys defined with the double-colon syntax automatically use the parameter name ThisHotkey
. Hotkeys can also be assigned a function name without the Hotkey function.
Note: If a callback is specified but the hotkey is disabled from a previous use of the Hotkey function, the hotkey will remain disabled. To prevent this, include the word ON in Options.
46 |Specify a hotkey name to use its original function; specifically, the original function of the hotkey variant corresponding to the current HotIf criteria. This is usually used to restore a hotkey's original function after having changed it, but can be used to assign the function of a different hotkey, provided that both hotkeys use the same HotIf criteria.
48 |Specify one of the following special values:
50 |On: The hotkey becomes enabled. No action is taken if the hotkey is already On.
51 |Off: The hotkey becomes disabled. No action is taken if the hotkey is already Off.
52 |Toggle: The hotkey is set to the opposite state (enabled or disabled).
53 |AltTab (and others): These are special Alt-Tab hotkey actions that are described here.
54 |Type: String
59 |A string of zero or more of the following options with optional spaces in between. For example: "On B0"
.
On: Enables the hotkey if it is currently disabled.
61 |Off: Disables the hotkey if it is currently enabled. This is typically used to create a hotkey in an initially-disabled state.
62 |B or B0: Specify the letter B to buffer the hotkey as described in #MaxThreadsBuffer. Specify B0
(B with the number 0) to disable this type of buffering.
Pn: Specify the letter P followed by the hotkey's thread priority. If the P option is omitted when creating a hotkey, 0 will be used.
64 |S or S0: Specify the letter S to make the hotkey exempt from Suspend, which allows the hotkey to be used to turn Suspend off. Specify S0 (S with the number 0) to remove the exemption, allowing the hotkey to be suspended.
65 |Tn: Specify the letter T followed by a the number of threads to allow for this hotkey as described in #MaxThreadsPerHotkey. For example: T5
.
In (InputLevel): Specify the letter I (or i) followed by the hotkey's input level. For example: I1
.
If any of the option letters are omitted and the hotkey already exists, those options will not be changed. But if the hotkey does not yet exist -- that is, it is about to be created by this function -- the options will default to those most recently in effect. For example, the instance of #MaxThreadsBuffer that occurs closest to the bottom of the script will be used. If #MaxThreadsBuffer does not appear in the script, its default setting (OFF in this case) will be used.
68 |An exception is thrown if a parameter is invalid or memory allocation fails.
74 |One of the following exceptions may be thrown if the hotkey is invalid or could not be created:
75 |Error Class | 78 |.Message | 79 |Description | 80 |
---|---|---|
ValueError | 83 |Invalid key name. | 84 |The KeyName parameter specifies one or more keys that are either not recognized or not supported by the current keyboard layout/language. Exception.Extra contains the key name; e.g. "Entre" from !Entre . |
85 |
Unsupported prefix key. | 88 |For example, using the mouse wheel as a prefix in a hotkey such as WheelDown & Enter is not supported. Exception.Extra contains the prefix key. |
89 | |
This AltTab hotkey must have exactly one modifier/prefix. | 92 |The KeyName parameter is not suitable for use with the AltTab or ShiftAltTab actions. A combination of (at most) two keys is required. For example: RControl & RShift::AltTab . Exception.Extra contains KeyName. |
93 | |
This AltTab hotkey must specify which key (L or R). | 96 |||
TargetError | 99 |Nonexistent hotkey. | 100 |The function attempted to modify a nonexistent hotkey. Exception.Extra contains KeyName. | 101 |
Nonexistent hotkey variant (IfWin). | 104 |The function attempted to modify a nonexistent variant of an existing hotkey. To solve this, use HotIf to set the criteria to match those of the hotkey to be modified. Exception.Extra contains KeyName. | 105 ||
Error | 108 |Max hotkeys. | 109 |Creating this hotkey would exceed the limit of 32762 hotkeys per script (however, each hotkey can have an unlimited number of variants, and there is no limit to the number of hotstrings). | 110 |
Tip: Try-Catch can be used to test for the existence of a hotkey variant. For example:
113 |114 | try 115 | Hotkey "^!p" 116 | catch TargetError 117 | MsgBox "The hotkey does not exist or it has no variant for the current HotIf criteria." 118 |119 | 120 |
The current HotIf setting determines the variant of a hotkey upon which the Hotkey function will operate.
122 |If the goal is to disable selected hotkeys or hotstrings automatically based on the type of window that is active, Hotkey "^!c", "Off"
is usually less convenient than using #HotIf with WinActive/WinExist (or their dynamic counterparts HotIfWinActive/Exist).
Creating hotkeys via the double-colon syntax performs better than using the Hotkey function because the hotkeys can all be enabled as a batch when the script starts (rather than one by one). Therefore, it is best to use this function to create only those hotkeys whose key names are not known until after the script has started running. One such case is when a script's hotkeys for various actions are configurable via an INI file.
124 |If the script is suspended, newly added/enabled hotkeys will also be suspended until the suspension is turned off (unless they are exempt as described in the Suspend section).
125 |The keyboard and/or mouse hooks will be installed or removed if justified by the changes made by this function.
126 |Although the Hotkey function cannot directly enable or disable hotkeys in scripts other than its own, in most cases it can override them by creating or enabling the same hotkeys. Whether this works depends on a combination of factors: 1) Whether the hotkey to be overridden is a hook hotkey in the other script (non-hook hotkeys can always be overridden); 2) The fact that the most recently started script's hotkeys generally take precedence over those in other scripts (therefore, if the script intending to override was started most recently, its override should always succeed); 3) Whether the enabling or creating of this hotkey will newly activate the keyboard or mouse hook (if so, the override will always succeed).
127 |Once a script has at least one hotkey, it becomes persistent, meaning that ExitApp rather than Exit should be used to terminate it.
128 | 129 |A particular hotkey can be created more than once if each definition has different HotIf criteria. These are known as hotkey variants. For example:
131 |HotIfWinActive "ahk_class Notepad" 132 | Hotkey "^!c", MyFuncForNotepad 133 | HotIfWinActive "ahk_class WordPadClass" 134 | Hotkey "^!c", MyFuncForWordPad 135 | HotIfWinActive 136 | Hotkey "^!c", MyFuncForAllOtherWindows137 |
If more than one variant of a hotkey is eligible to fire, only the one created earliest will fire. The exception to this is the global variant (the one with no HotIf criteria): It always has the lowest precedence, and thus will fire only if no other variant is eligible.
138 |When creating duplicate hotkeys, the order of modifier symbols such as ^!+#
does not matter. For example, "^!c"
is the same as "!^c"
. However, keys must be spelled consistently. For example, Esc is not the same as Escape for this purpose (though the case does not matter). Finally, any hotkey with a wildcard prefix (*) is entirely separate from a non-wildcard one; for example, "*F1"
and "F1"
would each have their own set of variants.
For more information, see HotIf and #HotIf's General Remarks.
140 | 141 |Hotkeys, HotIf, A_ThisHotkey, #MaxThreadsBuffer, #MaxThreadsPerHotkey, Suspend, Threads, Thread, Critical, Return, Menu object, SetTimer, Hotstring function
143 | 144 |Hotkey "^!z", MyFunc 148 | 149 | MyFunc(ThisHotkey) 150 | { 151 | MsgBox "You pressed " ThisHotkey 152 | }153 |
Creates Alt+W as a hotkey that works only in Notepad.
173 |HotIfWinActive "ahk_class Notepad" 174 | Hotkey "!w", ToggleWordWrap ; !w = Alt+W 175 | 176 | ToggleWordWrap(ThisHotkey) 177 | { 178 | MenuSelect "A",, "Format", "Word Wrap" 179 | } 180 |181 |
Creates a GUI that allows to register primitive three-key combination hotkeys.
185 |186 | HkGui := Gui() 187 | HkGui.Add("Text", "xm", "Prefix key:") 188 | HkGui.Add("Edit", "yp x100 w100 vPrefix", "Space") 189 | HkGui.Add("Text", "xm", "Suffix hotkey:") 190 | HkGui.Add("Edit", "yp x100 w100 vSuffix", "f & j") 191 | HkGui.Add("Button", "Default", "Register").OnEvent("Click", RegisterHotkey) 192 | HkGui.OnEvent("Close", (*) => ExitApp()) 193 | HkGui.OnEvent("Escape", (*) => ExitApp()) 194 | HkGui.Show() 195 | 196 | RegisterHotkey(*) 197 | { 198 | Saved := HkGui.Submit(false) 199 | HotIf (*) => GetKeyState(Saved.Prefix) 200 | Hotkey Saved.Suffix, (ThisHotkey) => MsgBox(ThisHotkey) 201 | }202 |
Creates, modifies, enables, or disables a hotstring while the script is running.
16 | 17 |Hotstring String , Replacement, OnOffToggle 18 | Hotstring NewOptions 19 | Hotstring SubFunction , Value120 | 21 |
Type: String
27 |The hotstring's trigger string, preceded by the usual colons and option characters. For example, "::btw"
or ":*:]d"
.
String may be matched to an existing hotstring by considering case-sensitivity (C), word-sensitivity (?), activation criteria (as set by #HotIf or HotIf) and the trigger string. For example, "::btw"
and "::BTW"
match unless the case-sensitive mode was enabled as a default, while ":C:btw"
and ":C:BTW"
never match. The C
and ?
options may be included in String or set as defaults by the #Hotstring directive or a previous use of NewOptions.
If the hotstring already exists, any options specified in String are put into effect, while all other options are left as is. However, since hotstrings with C
or ?
are considered distinct from other hotstrings, it is not possible to add or remove these options. Instead, turn off the existing hotstring and create a new one.
When a hotstring is first created -- either by the Hotstring function or the double-colon syntax in the script -- its trigger string and sequence of option characters becomes the permanent name of that hotstring as reflected by ThisHotkey. This name does not change even if the Hotstring function later accesses the hotstring with different option characters.
31 |Type: String or Function Object
36 |If omitted and String already exists as a hotstring, its replacement will not be changed. This is useful to change only the hotstring's options, or to turn it on or off. Otherwise, specify the replacement string or a callback.
37 |If Replacement is a function, it is called (as a new thread) when the hotstring triggers.
38 |The callback accepts one parameter and can be defined as follows:
39 |MyCallback(HotstringName) { ...40 |
Although the name you give the parameter does not matter, it is assigned the hotstring name.
41 |You can omit the callback's parameter if the corresponding information is not needed, but in this case an asterisk must be specified, e.g. MyCallback(*)
.
Hotstrings defined with the double-colon syntax automatically use the parameter name ThisHotkey
. Hotstrings can also be assigned a function name without the Hotstring function.
After reassigning the function of a hotstring, its original function can only be restored if it was given a name.
44 |Note: If this parameter is specified but the hotstring is disabled from a previous use of this function, the hotstring will remain disabled. To prevent this, specify "On"
for OnOffToggle.
One of the following values:
51 |On or 1 (true): Enables the hotstring.
52 |Off or 0 (false): Disables the hotstring.
53 |Toggle or -1: Sets the hotstring to the opposite state (enabled or disabled).
54 |Type: String
59 |To set new default options for subsequently created hotstrings, pass the options to the Hotstring function without any leading or trailing colon. For example: Hotstring "T"
.
Turning on case-sensitivity (C) or word-sensitivity (?) also affects which existing hotstrings will be found by any subsequent calls to the Hotstring function. For example, Hotstring ":T:btw"
will find ::BTW
by default, but not if Hotstring "C"
or #Hotstring C
is in effect. This can be undone or overridden by passing a mutually-exclusive option; for example, C0
and C1
override C
.
Type: String
66 |These parameters are dependent upon each other and their usage is described below.
67 |For SubFunction, specify one of the following:
73 |Retrieves or modifies the set of characters used as ending characters by the hotstring recognizer.
81 |OldValue := Hotstring("EndChars" , NewValue)82 |
For example:
83 |prev_chars := Hotstring("EndChars", "-()[]{}':;`"/\,.?!`n`s`t") 84 | MsgBox "The previous value was: " prev_chars85 |
#Hotstring EndChars also affects this setting.
86 |It is currently not possible to specify a different set of end characters for each hotstring.
87 | 88 |Retrieves or modifies the global setting which controls whether mouse clicks reset the hotstring recognizer, as described here.
90 |OldValue := Hotstring("MouseReset" , NewValue)91 |
NewValue should be 1 (true) to enable mouse click detection and resetting of the hotstring recognizer, or 0 (false) to disable it. The return value is the setting which was in effect before the function was called.
92 |The mouse hook may be installed or removed if justified by the changes made by this function.
93 |#Hotstring NoMouse also affects this setting, and is equivalent to specifying false
for NewValue.
Immediately resets the hotstring recognizer.
97 |Hotstring "Reset"
98 | In other words, the script will begin waiting for an entirely new hotstring, eliminating from consideration anything you previously typed.
99 | 100 |This function throws an exception if the parameters are invalid or a memory allocation fails.
102 |A TargetError is thrown if Replacement is omitted and String is valid but does not match an existing hotstring. This can be utilized to test for the existence of a hotstring. For example:
103 |try 104 | Hotstring "::btw" 105 | catch TargetError 106 | MsgBox "The hotstring does not exist or it has no variant for the current HotIf criteria."107 | 108 |
The current HotIf setting determines the variant of a hotstring upon which the Hotstring function will operate.
110 |If the script is suspended, newly added/enabled hotstrings will also be suspended until the suspension is turned off (unless they are exempt as described in the Suspend section).
111 |The keyboard and/or mouse hooks will be installed or removed if justified by the changes made by this function.
112 |This function cannot directly enable or disable hotstrings in scripts other than its own.
113 |Once a script has at least one hotstring, it becomes persistent, meaning that ExitApp rather than Exit should be used to terminate it.
114 | 115 |A particular hotstring can be created more than once if each definition has different HotIf criteria, case-sensitivity (C
vs. C0
/C1
), or word-sensitivity (?
). These are known as hotstring variants. For example:
HotIfWinActive "ahk_group CarForums" 118 | Hotstring "::btw", "behind the wheel" 119 | HotIfWinActive "Inter-Office Chat" 120 | Hotstring "::btw", "back to work" 121 | HotIfWinActive 122 | Hotstring "::btw", "by the way"123 |
If more than one variant of a hotstring is eligible to fire, only the one created earliest will fire.
124 |For more information, see HotIf.
125 | 126 |Hotstrings, HotIf, A_ThisHotkey, #MaxThreadsPerHotkey, Suspend, Threads, Thread, Critical, Hotkey function
128 | 129 |Hotstring Helper. The following script might be useful if you are a heavy user of hotstrings. It's based on the v1 script created by Andreas Borutta. By pressing Win+H (or another hotkey of your choice), the currently selected text can be turned into a hotstring. For example, if you have "by the way" selected in a word processor, pressing Win+H will prompt you for its abbreviation (e.g. btw), add the new hotstring to the script and activate it.
133 |#h:: ; Win+H hotkey 134 | { 135 | ; Get the text currently selected. The clipboard is used instead of 136 | ; EditGetSelectedText because it works in a greater variety of editors 137 | ; (namely word processors). Save the current clipboard contents to be 138 | ; restored later. Although this handles only plain text, it seems better 139 | ; than nothing: 140 | ClipboardOld := A_Clipboard 141 | A_Clipboard := "" ; Must start off blank for detection to work. 142 | Send "^c" 143 | if !ClipWait(1) ; ClipWait timed out. 144 | { 145 | A_Clipboard := ClipboardOld ; Restore previous contents of clipboard before returning. 146 | return 147 | } 148 | ; Replace CRLF and/or LF with `n for use in a "send-raw" hotstring: 149 | ; The same is done for any other characters that might otherwise 150 | ; be a problem in raw mode: 151 | ClipContent := StrReplace(A_Clipboard, "``", "````") ; Do this replacement first to avoid interfering with the others below. 152 | ClipContent := StrReplace(ClipContent, "`r`n", "``n") 153 | ClipContent := StrReplace(ClipContent, "`n", "``n") 154 | ClipContent := StrReplace(ClipContent, "`t", "``t") 155 | ClipContent := StrReplace(ClipContent, "`;", "```;") 156 | A_Clipboard := ClipboardOld ; Restore previous contents of clipboard. 157 | ShowInputBox(":T:::" ClipContent) 158 | } 159 | 160 | ShowInputBox(DefaultValue) 161 | { 162 | ; This will move the input box's caret to a more friendly position: 163 | SetTimer MoveCaret, 10 164 | ; Show the input box, providing the default hotstring: 165 | IB := InputBox(" 166 | ( 167 | Type your abbreviation at the indicated insertion point. You can also edit the replacement text if you wish. 168 | 169 | Example entry: :T:btw::by the way 170 | )", "New Hotstring",, DefaultValue) 171 | if IB.Result = "Cancel" ; The user pressed Cancel. 172 | return 173 | 174 | if RegExMatch(IB.Value, "(?P<Label>:.*?:(?P<Abbreviation>.*?))::(?P<Replacement>.*)", &Entered) 175 | { 176 | if !Entered.Abbreviation 177 | MsgText := "You didn't provide an abbreviation" 178 | else if !Entered.Replacement 179 | MsgText := "You didn't provide a replacement" 180 | else 181 | { 182 | Hotstring Entered.Label, Entered.Replacement ; Enable the hotstring now. 183 | FileAppend "`n" IB.Value, A_ScriptFullPath ; Save the hotstring for later use. 184 | } 185 | } 186 | else 187 | MsgText := "The hotstring appears to be improperly formatted" 188 | 189 | if IsSet(MsgText) 190 | { 191 | Result := MsgBox(MsgText ". Would you like to try again?",, 4) 192 | if Result = "Yes" 193 | ShowInputBox(DefaultValue) 194 | } 195 | 196 | MoveCaret() 197 | { 198 | WinWait "New Hotstring" 199 | ; Otherwise, move the input box's insertion point to where the user will type the abbreviation. 200 | Send "{Home}{Right 3}" 201 | SetTimer , 0 202 | } 203 | }204 |
Specifies one or more statements to execute if an expression evaluates to true.
16 |If Expression
17 | {
18 | Statements
19 | }
20 |
21 | If the If statement's expression evaluates to true (which is any result other than an empty string or the number 0), the line or block underneath it is executed. Otherwise, if there is a corresponding Else statement, execution jumps to the line or block underneath it.
23 |If an If owns more than one line, those lines must be enclosed in braces (to create a block). However, if only one line belongs to an If, the braces are optional. See the examples at the bottom of this page.
24 |The space after if
is optional if the expression starts with an open-parenthesis, as in if(expression)
.
The One True Brace (OTB) style may optionally be used. For example:
26 |if (x < y) { 27 | ; ... 28 | } 29 | if WinExist("Untitled - Notepad") { 30 | WinActivate 31 | } 32 | if IsDone { 33 | ; ... 34 | } else { 35 | ; ... 36 | }37 |
Unlike an If statement, an Else statement supports any type of statement immediately to its right.
38 | 39 |Expressions, Ternary operator (a?b:c), Blocks, Else, While-loop
41 | 42 | If the result of A_TickCount - StartTime
is greater than the result of 2*MaxTime + 100
, show "Too much time has passed." and terminate the script.
if (A_TickCount - StartTime > 2*MaxTime + 100) 52 | { 53 | MsgBox "Too much time has passed." 54 | ExitApp 55 | }56 |
This example is executed as follows:
60 |if (Color = "Blue" or Color = "White") 81 | { 82 | MsgBox "The color is one of the allowed values." 83 | ExitApp 84 | } 85 | else if (Color = "Silver") 86 | { 87 | MsgBox "Silver is not an allowed color." 88 | return 89 | } 90 | else 91 | { 92 | MsgBox "This color is not recognized." 93 | ExitApp 94 | }95 |
A single multi-statement line does not need to be enclosed in braces.
98 |MyVar := 3 99 | if (MyVar > 2) 100 | MyVar++, MyVar := MyVar - 4, MyVar .= " test" 101 | MsgBox MyVar ; Reports "0 test". 102 |103 |
Similar to AutoHotkey v1's If Var [not] between Lower and Upper, the following examples check whether a variable's contents are numerically or alphabetically between two values (inclusive).
107 |Checks whether var is in the range 1 to 5:
108 |if (var >= 1 and var <= 5) 109 | MsgBox var " is in the range 1 to 5, inclusive."110 |
Checks whether var is in the range 0.0 to 1.0:
111 |if not (var >= 0.0 and var <= 1.0) 112 | MsgBox var " is not in the range 0.0 to 1.0, inclusive."113 |
Checks whether var is between VarLow and VarHigh (inclusive):
114 |if (var >= VarLow and var <= VarHigh) 115 | MsgBox var " is between " VarLow " and " VarHigh "."116 |
Checks whether var is alphabetically between the words blue and red (inclusive):
117 |if (StrCompare(var, "blue") >= 0) and (StrCompare(var, "red") <= 0) 118 | MsgBox var " is alphabetically between the words blue and red."119 |
Allows the user to enter a number and checks whether it is in the range 1 to 10:
120 |LowerLimit := 1 121 | UpperLimit := 10 122 | IB := InputBox("Enter a number between " LowerLimit " and " UpperLimit) 123 | if not (IB.Value >= LowerLimit and IB.Value <= UpperLimit) 124 | MsgBox "Your input is not within the valid range."125 |
Similar to AutoHotkey v1's If Var [not] in/contains MatchList, the following examples check whether a variable's contents match one of the items in a list.
129 |Checks whether var is the file extension exe, bat or com:
130 |if (var ~= "i)\A(exe|bat|com)\z") 131 | MsgBox "The file extension is an executable type."132 |
Checks whether var is the prime number 1, 2, 3, 5, 7 or 11:
133 |if (var ~= "\A(1|2|3|5|7|11)\z") 134 | MsgBox var " is a small prime number."135 |
Checks whether var contains the digit 1 or 3:
136 |if (var ~= "1|3") 137 | MsgBox "Var contains the digit 1 or 3 (Var could be 1, 3, 10, 21, 23, etc.)"138 |
Checks whether var is one of the items in MyItemList:
139 |; Uncomment the following line if MyItemList contains RegEx chars except | 140 | ; MyItemList := RegExReplace(MyItemList, "[\Q\.*?+[{()^$\E]", "\$0") 141 | if (var ~= "i)\A(" MyItemList ")\z") 142 | MsgBox var " is in the list."143 |
Allows the user to enter a string and checks whether it is the word yes or no:
144 |IB := InputBox("Enter YES or NO") 145 | if not (IB.Value ~= "i)\A(yes|no)\z") 146 | MsgBox "Your input is not valid."147 |
Checks whether active_title contains "Address List.txt" or "Customer List.txt" and checks whether it contains "metapad" or "Notepad":
148 |active_title := WinGetTitle("A") 149 | if (active_title ~= "i)Address List\.txt|Customer List\.txt") 150 | MsgBox "One of the desired windows is active." 151 | if not (active_title ~= "i)metapad|Notepad") 152 | MsgBox "But the file is not open in either Metapad or Notepad."153 |
Searches a region of the screen for an image.
16 | 17 |ImageSearch &OutputVarX, &OutputVarY, X1, Y1, X2, Y2, ImageFile
18 | Type: VarRef
24 |References to the output variables in which to store the X and Y coordinates of the upper-left pixel of where the image was found on the screen (if no match is found, the variables are made blank). Coordinates are relative to the active window's client area unless CoordMode was used to change that.
25 |Type: Integer
30 |The X and Y coordinates of the upper left corner of the rectangle to search. Coordinates are relative to the active window's client area unless CoordMode was used to change that.
31 |Type: Integer
36 |The X and Y coordinates of the lower right corner of the rectangle to search. Coordinates are relative to the active window's client area unless CoordMode was used to change that.
37 |Type: String
42 |The file name of an image, which is assumed to be in A_WorkingDir if an absolute path isn't specified. Supported image formats include ANI, BMP, CUR, EMF, Exif, GIF, ICO, JPG, PNG, TIF, and WMF (BMP images must be 16-bit or higher). Other sources of icons include the following types of files: EXE, DLL, CPL, SCR, and other types that contain icon resources.
43 |Options: Zero or more of the following options may be also be present immediately before the name of the file. Separate each option from the next with a single space or tab. For example: "*2 *w100 *h-1 C:\Main Logo.bmp"
.
*IconN: To use an icon group other than the first one in the file, specify *Icon
followed immediately by the number of the group. For example, *Icon2
would load the default icon from the second icon group.
*n (variation): Specify for n a number between 0 and 255 (inclusive) to indicate the allowed number of shades of variation in either direction for the intensity of the red, green, and blue components of each pixel's color. For example, if *2
is specified and the color of a pixel is 0x444444, any color from 0x424242 to 0x464646 will be considered a match. This parameter is helpful if the coloring of the image varies slightly or if ImageFile uses a format such as GIF or JPG that does not accurately represent an image on the screen. If you specify 255 shades of variation, all colors will match. The default is 0 shades.
*TransN: This option makes it easier to find a match by specifying one color within the image that will match any color on the screen. It is most commonly used to find PNG, GIF, and TIF files that have some transparent areas (however, icons do not need this option because their transparency is automatically supported). For GIF files, *TransWhite
might be most likely to work. For PNG and TIF files, *TransBlack
might be best. Otherwise, specify for N some other color name or RGB value (see the color chart for guidance, or use PixelGetColor in its RGB mode). Examples: *TransBlack
, *TransFFFFAA
, *Trans0xFFFFAA
.
*wn and *hn: Width and height to which to scale the image (this width and height also determines which icon to load from a multi-icon .ICO file). If both these options are omitted, icons loaded from ICO, DLL, or EXE files are scaled to the system's default small-icon size, which is usually 16 by 16 (you can force the actual/internal size to be used by specifying *w0 *h0
). Images that are not icons are loaded at their actual size. To shrink or enlarge the image while preserving its aspect ratio, specify -1 for one of the dimensions and a positive number for the other. For example, specifying *w200 *h-1
would make the image 200 pixels wide and cause its height to be set automatically.
A bitmap or icon handle can be used instead of a filename. For example, "HBITMAP:*" handle
.
Type: Integer (boolean)
55 |This function returns 1 (true) if the image was found in the specified region, or 0 (false) if it was not found.
56 | 57 |A ValueError is thrown if an invalid parameter was detected or the image could not be loaded.
59 |An OSError is thrown if an internal function call fails.
60 | 61 |ImageSearch can be used to detect graphical objects on the screen that either lack text or whose text cannot be easily retrieved. For example, it can be used to discover the position of picture buttons, icons, web page links, or game objects. Once located, such objects can be clicked via Click.
63 |A strategy that is sometimes useful is to search for a small clipping from an image rather than the entire image. This can improve reliability in cases where the image as a whole varies, but certain parts within it are always the same. One way to extract a clipping is to:
64 |To be a match, an image on the screen must be the same size as the one loaded via the ImageFile parameter and its options.
73 |The region to be searched must be visible; in other words, it is not possible to search a region of a window hidden behind another window. By contrast, images that lie partially beneath the mouse cursor can usually be detected. The exception to this is game cursors, which in most cases will obstruct any images beneath them.
74 |Since the search starts at the top row of the region and moves downward, if there is more than one match, the one closest to the top will be found.
75 |Icons containing a transparent color automatically allow that color to match any color on the screen. Therefore, the color of what lies behind the icon does not matter.
76 |ImageSearch supports 8-bit color screens (256-color) or higher.
77 |The search behavior may vary depending on the display adapter's color depth (especially for GIF and JPG files). Therefore, if a script will run under multiple color depths, it is best to test it on each depth setting. You can use the shades-of-variation option (*n) to help make the behavior consistent across multiple color depths.
78 |If the image on the screen is translucent, ImageSearch will probably fail to find it. To work around this, try the shades-of-variation option (*n) or make the window temporarily opaque via WinSetTransparent("Off")
.
PixelSearch, PixelGetColor, CoordMode, MouseGetPos
81 |Searches a region of the active window for an image and stores in FoundX and FoundY the X and Y coordinates of the upper-left pixel of where the image was found.
84 |ImageSearch &FoundX, &FoundY, 40, 40, 300, 300, "C:\My Images\test.bmp"85 |
Searches a region of the screen for an image and stores in FoundX and FoundY the X and Y coordinates of the upper-left pixel of where the image was found, including advanced error handling.
88 |CoordMode "Pixel" ; Interprets the coordinates below as relative to the screen rather than the active window's client area. 89 | try 90 | { 91 | if ImageSearch(&FoundX, &FoundY, 0, 0, A_ScreenWidth, A_ScreenHeight, "*Icon3 " A_ProgramFiles "\SomeApp\SomeApp.exe") 92 | MsgBox "The icon was found at " FoundX "x" FoundY 93 | else 94 | MsgBox "Icon could not be found on the screen." 95 | } 96 | catch as exc 97 | MsgBox "Could not conduct the search due to the following error:`n" exc.Message 98 |99 |
Searches for a given occurrence of a string, from the left or the right.
16 | 17 |FoundPos := InStr(Haystack, Needle , CaseSense, StartingPos, Occurrence)18 |
Type: String
24 |The string whose content is searched.
25 |Type: String
30 |The string to search for.
31 |Type: String or Integer (boolean)
36 |If omitted, it defaults to Off. Otherwise, specify one of the following values:
37 |On or 1 (true): The search is case-sensitive.
38 |Off or 0 (false): The search is not case-sensitive, i.e. the letters A-Z are considered identical to their lowercase counterparts.
39 |Locale: The search is not case-sensitive according to the rules of the current user's locale. For example, most English and Western European locales treat not only the letters A-Z as identical to their lowercase counterparts, but also non-ASCII letters like Ä and Ü as identical to theirs. Locale is 1 to 8 times slower than Off depending on the nature of the strings being compared.
40 |Type: Integer
45 |If omitted, the entire string is searched. Otherwise, specify the position at which to start the search, where 1 is the first character, 2 is the second character, and so on. Negative values count from the end of Haystack, so -1 is the last character, -2 is the second-last, and so on.
46 |If Occurrence is omitted, a negative StartingPos causes the search to be conducted from right to left. However, StartingPos has no effect on the direction of the search if Occurrence is specified.
47 |For a right-to-left search, StartingPos specifies the position of the last character of the first potential occurence of Needle. For example, InStr("abc", "bc",, 2, +1)
will find a match but InStr("abc", "bc",, 2, -1)
will not.
If the absolute value of StartingPos is greater than the length of Haystack, 0 is returned.
49 |Type: Integer
54 |If omitted, it defaults to the first match in Haystack. The search is conducted from right to left if StartingPos is negative; otherwise it is conducted from left to right.
55 |If Occurrence is positive, the search is always conducted from left to right. Specify 2 for Occurrence to return the position of the second match, 3 for the third match, etc.
56 |If Occurrence is negative, the search is always conducted from right to left. For example, -2 searches for the second occurrence from the right.
57 |Type: Integer
63 |This function returns the position of an occurrence of the string Needle in the string Haystack. Position 1 is the first character; this is because 0 is synonymous with "false", making it an intuitive "not found" indicator.
64 |Regardless of the values of StartingPos or Occurrence, the return value is always relative to the first character of Haystack. For example, the position of "abc" in "123abc789" is always 4.
65 |Conventionally, an occurrence of an empty string (""
) can be found at any position. However, as a blank Needle would typically only be passed by mistake, it is treated as an error (an exception is thrown).
A ValueError is thrown in any of the following cases:
69 |RegExMatch can be used to search for a pattern (regular expression) within a string, making it much more flexible than InStr. However, InStr is generally faster than RegExMatch when searching for a simple substring.
77 |InStr searches only up to the first binary zero (null-terminator), whereas RegExMatch searches the entire length of the string even if it includes binary zero.
78 | 79 |Reports the 1-based position of the substring "abc" in the string "123abc789".
85 |MsgBox InStr("123abc789", "abc") ; Returns 486 |
Searches for Needle in Haystack.
90 |Haystack := "The Quick Brown Fox Jumps Over the Lazy Dog" 91 | Needle := "Fox" 92 | If InStr(Haystack, Needle) 93 | MsgBox "The string was found." 94 | Else 95 | MsgBox "The string was not found."96 |
Demonstrates the difference between a case-insensitive and case-sensitive search.
100 |Haystack := "The Quick Brown Fox Jumps Over the Lazy Dog" 101 | Needle := "the" 102 | MsgBox InStr(Haystack, Needle, false, 1, 2) ; case-insensitive search, return start position of second occurence 103 | MsgBox InStr(Haystack, Needle, true) ; case-sensitive search, return start position of first occurence, same result as above 104 |105 |
Deletes a value from a standard format .ini file.
16 | 17 |IniDelete Filename, Section , Key18 |
Type: String
24 |The name of the .ini file, which is assumed to be in A_WorkingDir if an absolute path isn't specified.
25 |Type: String
30 |The section name in the .ini file, which is the heading phrase that appears in square brackets (do not include the brackets in this parameter).
31 |Type: String
36 |If omitted, the entire section will be deleted. Otherwise, specify the key name in the .ini file.
37 |An OSError is thrown on failure.
42 |Regardless of whether an exception is thrown, A_LastError is set to the result of the operating system's GetLastError() function.
43 | 44 |A standard ini file looks like:
46 |[SectionName] 47 | Key=Value48 |
IniRead, IniWrite, RegDelete, RegDeleteKey
50 |Deletes a key and its value located in section2 from a standard format .ini file.
53 |IniDelete "C:\Temp\myfile.ini", "section2", "key"54 |
Reads a value, section or list of section names from a standard format .ini file.
16 | 17 |Value := IniRead(Filename, Section, Key , Default) 18 | Section := IniRead(Filename, Section) 19 | SectionNames := IniRead(Filename)20 |
Type: String
26 |The name of the .ini file, which is assumed to be in A_WorkingDir if an absolute path isn't specified.
27 |Type: String
32 |The section name in the .ini file, which is the heading phrase that appears in square brackets (do not include the brackets in this parameter).
33 |Type: String
38 |The key name in the .ini file.
39 |Type: String
44 |If omitted, an OSError is thrown on failure. Otherwise, specify the value to return on failure, such as if the requested key, section or file is not found.
45 |Type: String
51 |This function returns the actual value of the specified key. If the value cannot be retrieved, the default value indicated by the Default parameter is returned.
52 |If the Key parameter is omitted, this function returns an entire section. Comments and empty lines are omitted. Only the first 65,533 characters of the section are retrieved.
53 |If the Key and Section parameters are omitted, this function returns a linefeed (`n
) delimited list of section names.
An OSError is thrown on failure, but only if Default is omitted.
57 |Regardless of whether an exception is thrown, A_LastError is set to the result of the operating system's GetLastError() function.
58 | 59 |The operating system automatically omits leading and trailing spaces/tabs from the retrieved string. To prevent this, enclose the string in single or double quote marks. The outermost set of single or double quote marks is also omitted, but any spaces inside the quote marks are preserved.
61 |Values longer than 65,535 characters are likely to yield inconsistent results.
62 |A standard ini file looks like:
63 |[SectionName] 64 | Key=Value65 |
Unicode: IniRead and IniWrite rely on the external functions GetPrivateProfileString and WritePrivateProfileString to read and write values. These functions support Unicode only in UTF-16 files; all other files are assumed to use the system's default ANSI code page.
66 |IniDelete, IniWrite, RegRead, file-reading loop, FileRead
68 |Reads the value of a key located in section2 from a standard format .ini file and stores it in Value.
71 |Value := IniRead("C:\Temp\myfile.ini", "section2", "key") 72 | MsgBox "The value is " Value73 |
Writes a value or section to a standard format .ini file.
16 | 17 |IniWrite Value, Filename, Section, Key 18 | IniWrite Pairs, Filename, Section19 |
Type: String
25 |The string or number that will be written to the right of Key's equal sign (=).
26 |If the text is long, it can be broken up into several shorter lines by means of a continuation section, which might improve readability and maintainability.
27 |Type: String
32 |The complete content of a section to write to the .ini file, excluding the [SectionName] header. Key must be omitted. Pairs must not contain any blank lines. If the section already exists, everything up to the last key=value pair is overwritten. Pairs can contain lines without an equal sign (=), but this may produce inconsistent results. Comments can be written to the file but are stripped out when they are read back by IniRead.
33 |Type: String
38 |The name of the .ini file, which is assumed to be in A_WorkingDir if an absolute path isn't specified.
39 |Type: String
44 |The section name in the .ini file, which is the heading phrase that appears in square brackets (do not include the brackets in this parameter).
45 |Type: String
50 |The key name in the .ini file.
51 |An OSError is thrown on failure.
56 |Regardless of whether an exception is thrown, A_LastError is set to the result of the operating system's GetLastError() function.
57 | 58 |Values longer than 65,535 characters can be written to the file, but may produce inconsistent results as they usually cannot be read correctly by IniRead or other applications.
60 |A standard ini file looks like:
61 |[SectionName] 62 | Key=Value63 |
New files are created with a UTF-16 byte order mark to ensure that the full range of Unicode characters can be used. If this is undesired, ensure the file exists before calling IniWrite. For example:
64 |65 | ; Create a file with ANSI encoding. 66 | FileAppend "", "NonUnicode.ini", "CP0" 67 | 68 | ; Create a UTF-16 file without byte order mark. 69 | FileAppend "[SectionName]`n", "Unicode.ini", "UTF-16-RAW" 70 |71 |
Unicode: IniRead and IniWrite rely on the external functions GetPrivateProfileString and WritePrivateProfileString to read and write values. These functions support Unicode only in UTF-16 files; all other files are assumed to use the system's default ANSI code page.
72 | 73 |Writes a value to a key located in section2 of a standard format .ini file.
78 |IniWrite "this is a new value", "C:\Temp\myfile.ini", "section2", "key"79 |
Displays an input box to ask the user to enter a string.
16 | 17 |InputBoxObj := InputBox(Prompt, Title, Options, Default)18 |
Type: String
24 |If blank or omitted, it defaults to no text. Otherwise, specify the text, which is usually a message to the user indicating what kind of input is expected. If Prompt is long, it can be broken up into several shorter lines by means of a continuation section, which might improve readability and maintainability.
25 |Type: String
30 |If omitted, it defaults to the current value of A_ScriptName. Otherwise, specify the title of the input box.
31 |Type: String
36 |If blank or omitted, the input box will be centered horizontally and vertically on the screen, with a default size of about 380x200 pixels, depending on the OS version and theme. Otherwise, specify a string of one or more of the following options, each separated from the next with a space or tab:
37 |Xn and Yn: The X and Y coordinates of the dialog. For example, x0 y0
puts the window at the upper left corner of the desktop. If either coordinate is omitted, the dialog will be centered in that dimension. Either coordinate can be negative to position the dialog partially or entirely off the desktop (or on a secondary monitor in a multi-monitor setup).
Wn and Hn: The width and height of the dialog's client area, which excludes the title bar and borders. For example, w200 h100
.
Tn: Specifies the timeout in seconds. For example, T10.0
is ten seconds. If this value exceeds 2147483 (24.8 days), it will be set to 2147483. After the timeout has elapsed, the input box will be automatically closed and InputBoxObj.Result will be set to the word Timeout. InputBoxObj.Value will still contain what the user entered.
Password: Hides the user's input (such as for password entry) by substituting masking characters for what the user types. If a non-default masking character is desired, include it immediately after the word Password. For example, Password*
would make the masking character an asterisk rather than the black circle (bullet).
Type: String
46 |If blank or omitted, it defaults to no string. Otherwise, specify a string that will appear in the input box's edit field when the dialog first appears. The user can change it by backspacing or other means.
47 |Type: Object
53 |This function returns an object with the following properties:
54 |Value
(String): The text entered by the user.Result
(String): One of the following words indicating how the input box was closed: OK, Cancel, or Timeout.An input box usually looks like this:
61 | 62 |The dialog allows the user to enter text and then press OK or CANCEL. The user can resize the dialog window by dragging its borders.
63 |A GUI window may display a modal input box by means of OwnDialogs option. A modal input box prevents the user from interacting with the GUI window until the input box is dismissed.
64 |Gui object, MsgBox, FileSelect, DirSelect, ToolTip, InputHook
66 |Allows the user to enter a hidden password.
69 |password := InputBox("(your input will be hidden)", "Enter Password", "password").value70 |
Allows the user to enter a phone number.
74 |IB := InputBox("Please enter a phone number.", "Phone Number", "w640 h480") 75 | if IB.Result = "Cancel" 76 | MsgBox "You entered '" IB.Value "' but then cancelled." 77 | else 78 | MsgBox "You entered '" IB.Value "'."79 |
Creates an object which can be used to collect or intercept keyboard input.
16 | 17 |InputHookObj := InputHook(Options, EndKeys, MatchList)18 |
Type: String
24 |A string of zero or more of the following options (in any order, with optional spaces in between):
25 |B: Sets BackspaceIsUndo to 0 (false), which causes Backspace to be ignored.
26 |C: Sets CaseSensitive to 1 (true), making MatchList case-sensitive.
27 |I: Sets MinSendLevel to 1 or a given value, causing any input with send level below this value to be ignored. For example, I2
would ignore any input with a level of 0 (the default) or 1, but would capture input at level 2.
L: Length limit (e.g. L5
). The maximum allowed length of the input. When the text reaches this length, the Input is terminated and EndReason is set to the word Max (unless the text matches one of the MatchList phrases, in which case EndReason is set to the word Match). If unspecified, the length limit is 1023.
Specifying L0
disables collection of text and the length limit, but does not affect which keys are counted as producing text (see VisibleText). This can be useful in combination with OnChar, OnKeyDown, KeyOpt or the EndKeys parameter.
M: Allows a greater range of modified keypresses to produce text. Normally, a key is treated as non-text if it is modified by any combination other than Shift, Ctrl+Alt (i.e. AltGr) or Ctrl+Alt+Shift (i.e. AltGr+Shift). This option causes translation to be attempted for other combinations of modifiers. Consider this example, which typically recognizes Ctrl+C:
31 |CtrlC := Chr(3) ; Store the character for Ctrl-C in the CtrlC var. 32 | ih := InputHook("L1 M") 33 | ih.Start() 34 | ih.Wait() 35 | if (ih.Input = CtrlC) 36 | MsgBox "You pressed Control-C."37 |
By default, the system maps Ctrl+A through Ctrl+Z to ASCII control characters Chr(1) through Chr(26). Other translations may be defined by the system or the active window's keyboard layout. Translation may ignore any modifier key for which the keyboard layout does not define a modifier bitmask. For example, Win+E typically transcribes to "e" if the M option is used.
38 |The M option might cause some keyboard shortcuts such as Ctrl+← to misbehave while an Input is in progress.
39 |T: Sets Timeout (e.g. T3
or T2.5
).
V: Sets VisibleText and VisibleNonText to 1 (true). Normally, the user's input is blocked (hidden from the system). Use this option to have the user's keystrokes sent to the active window.
41 |*: Wildcard. Sets FindAnywhere to 1 (true), allowing matches to be found anywhere within what the user types.
42 |E: Handle single-character end keys by character code instead of by keycode. This provides more consistent results if the active window's keyboard layout is different to the script's keyboard layout. It also prevents key combinations which don't actually produce the given end characters from ending input; for example, if @ is an end key, on the US layout Shift+2 will trigger it but Ctrl+Shift+2 will not (if the E option is used). If the C option is also used, the end character is case-sensitive.
43 |Type: String
48 |A list of zero or more keys, any one of which terminates the Input when pressed (the end key itself is not written to the Input buffer). When an Input is terminated this way, EndReason is set to the word EndKey and EndKey is set to the name of the key.
49 |EndKeys uses a format similar to the Send function. For example, specifying {Enter}.{Esc}
would cause either Enter, ., or Esc to terminate the Input. To use the braces themselves as end keys, specify {{}
and/or {}}
.
To use Ctrl, Alt, or Shift as end keys, specify the left and/or right version of the key, not the neutral version. For example, specify {LControl}{RControl}
rather than {Control}
.
Although modified keys such as Alt+C (!c) are not supported, non-alphanumeric characters such as ?!:@&{}
by default require Shift or AltGr to be pressed or not pressed depending on how the character is normally typed. If the E option is present, single character key names are interpreted as characters instead, and in those cases the modifier keys must be in the correct state to produce that character. When both the E option and M option are used, Ctrl+A through Ctrl+Z are supported by including the corresponding ASCII control characters in EndKeys.
An explicit key code such as {vkFF}
or {sc001}
may also be specified. This is useful in the rare case where a key has no name and produces no visible character when pressed. Its key code can be determined by following the steps at the bottom of the key list page.
Type: String
58 |A comma-separated list of key phrases, any of which will cause the Input to be terminated (in which case EndReason will be set to the word Match). The entirety of what the user types must exactly match one of the phrases for a match to occur (unless the * option is present). In addition, any spaces or tabs around the delimiting commas are significant, meaning that they are part of the match string. For example, if MatchList is ABC , XYZ
, the user must type a space after ABC or before XYZ to cause a match.
Two consecutive commas results in a single literal comma. For example, the following would produce a single literal comma at the end of string1: string1,,,string2
. Similarly, the following list contains only a single item with a literal comma inside it: single,,item
.
Because the items in MatchList are not treated as individual parameters, the list can be contained entirely within a variable. For example, MatchList might consist of List1 "," List2 "," List3
-- where each of the variables contains a large sub-list of match phrases.
Any number of InputHook objects can be created and in progress at any time, but the order in which they are started affects how input is collected.
67 |When each Input is started (by the Start method), it is pushed onto the top of a stack, and is removed from this stack only when the Input is terminated. Keyboard events are passed to each Input in order of most recently started to least. If an Input suppresses a given keyboard event, it is passed no further down the stack.
68 |Sent keystrokes are ignored if the send level of the keystroke is below the InputHook's MinSendLevel. In such cases, the keystroke may still be processed by an Input lower on the stack.
69 |Multiple InputHooks can be used in combination with MinSendLevel to separately collect both sent keystrokes and real ones.
70 | 71 |The InputHook function returns an InputHook object, which has the following methods and properties.
73 | "InputHookObj" is used below as a placeholder for any InputHook object, as "InputHook" is the class itself. 74 |Sets options for a key or list of keys.
114 |InputHookObj.KeyOpt(Keys, KeyOptions)
115 | Type: String
120 |A list of keys. Braces are used to enclose key names, virtual key codes or scan codes, similar to the Send function. For example, {Enter}.{{}
would apply to Enter, . and {. Specifying a key by name, by {vkNN}
or by {scNNN}
may produce three different results; see below for details.
Specify the string {All}
(case-insensitive) on its own to apply KeyOptions to all VK and all SC, including {vkE7}
and {sc000}
as described below. KeyOpt may then be called a second time to remove options from specific keys.
Specify {sc000}
to apply KeyOptions to all events which lack a scan code.
Specify {vkE7}
to apply KeyOptions to Unicode events, such as those sent by SendEvent "{U+221e}"
or SendEvent "{Text}∞"
.
Type: String
128 |One or more of the following single-character options (spaces and tabs are ignored).
129 |- (minus): Removes any of the options following the -
, up to the next +
.
+ (plus): Cancels any previous -
, otherwise has no effect.
E: End key. If enabled, pressing the key terminates Input, sets EndReason to the word EndKey and EndKey to the key's normalized name. Unlike the EndKeys parameter, the state of Shift or AltGr is ignored. For example, @
and 2
are both equivalent to {vk32}
on the US keyboard layout.
I: Ignore text. Any text normally produced by this key is ignored, and the key is treated as a non-text key (see VisibleNonText). Has no effect if the key normally does not produce text.
133 |N: Notify. Causes the OnKeyDown and OnKeyUp callbacks to be called each time the key is pressed.
134 |S: Suppresses (blocks) the key after processing it. This overrides VisibleText or VisibleNonText until -S
is used. +S
implies -V
.
V: Visible. Prevents the key from being suppressed (blocked). This overrides VisibleText or VisibleNonText until -V
is used. +V
implies -S
.
Options can be set by both virtual key code (VK) and scan code (SC), and are accumulative.
140 |When a key is specified by name, options are added either by VK or by SC. Where two physical keys share the same VK but differ by SC (such as Up and NumpadUp), they are handled by SC. By contrast, if a VK number is used, it will apply to any physical key which produces that VK (and this may vary over time as it depends on the active keyboard layout).
141 |Removing an option by VK number does not affect any options that were set by SC, or vice versa. However, when an option is removed by key name and that name is handled by VK, the option is also removed for the corresponding SC (according to the script's keyboard layout). This allows keys to be excluded by name after applying an option to all keys.
142 |To prevent an option from affecting a key, the option must be removed from both the VK and the SC of that key, or sc000 if the key has no SC.
143 |Unicode events, such as those sent by SendEvent "{U+221e}"
or SendEvent "{Text}∞"
, are affected by options which have been set for either vkE7 or sc000. Any option applied to {All} is applied to both vkE7 and sc000, so to exclude Unicode events, remove the option from both. For example:
InputHookObj.KeyOpt("{All}", "+I") ; Ignore text produced by any event 145 | InputHookObj.KeyOpt("{vkE7}{sc000}", "-I") ; except Unicode events.146 |
Starts collecting input.
150 |InputHookObj.Start()
151 | Has no effect if the Input is already in progress.
152 |The newly started Input is placed on the top of the InputHook stack, which allows it to override any previously started Input.
153 |This method installs the keyboard hook (if it was not already).
154 |Terminates the Input and sets EndReason to the word Stopped.
158 |InputHookObj.Stop()
159 | Has no effect if the Input is not in progress.
160 |Waits until the Input is terminated (InProgress is false).
164 |EndReason := InputHookObj.Wait(MaxTime)165 |
Type: Float
170 |If omitted, the wait is indefinitely. Otherwise, specify the maximum number of seconds to wait. If Input is still in progress after MaxTime seconds, the method returns and does not terminate Input.
171 |Type: String
175 |This method returns EndReason.
176 |Returns the name of the end key which was pressed to terminate the Input.
181 |KeyName := InputHookObj.EndKey
182 | Note that EndKey returns the "normalized" name of the key regardless of how it was written in the EndKeys parameter. For example, {Esc}
and {vk1B}
both produce Escape
. GetKeyName can be used to retrieve the normalized name.
If the E option was used, EndKey returns the actual character which was typed (if applicable). Otherwise, the key name is determined according to the script's active keyboard layout.
184 |EndKey returns an empty string if EndReason is not "EndKey".
185 |Returns a string of the modifiers which were logically down when Input was terminated.
189 |Mods := InputHookObj.EndMods
190 | If all modifiers were logically down (pressed), the full string is:
191 |<^>^<!>!<+>+<#>#192 |
These modifiers have the same meaning as with hotkeys. Each modifier is always qualified with < (left) or > (right). The corresponding key names are: LCtrl, RCtrl, LAlt, RAlt, LShift, RShift, LWin, RWin.
193 |InStr can be used to check whether a given modifier (such as >!
or ^
) is present. The following line can be used to convert Mods to a string of neutral modifiers, such as ^!+#
:
Mods := RegExReplace(Mods, "[<>](.)(?:>\1)?", "$1")195 |
Due to split-second timing, this property may be more reliable than GetKeyState even if it is used immediately after Input terminates, or in the OnEnd callback.
196 |Returns an EndReason string indicating how Input was terminated.
200 |Reason := InputHookObj.EndReason
201 | If the Input is still in progress, an empty string is returned.
202 |Returns 1 (true) if the Input is in progress, otherwise 0 (false).
206 |Boolean := InputHookObj.InProgress
207 | Returns any text collected since the last time Input was started.
211 |String := InputHookObj.Input
212 | This property can be used while the Input is in progress, or after it has ended.
213 |Returns the MatchList item which caused the Input to terminate.
217 |String := InputHookObj.Match
218 | This property returns the matched item with its original case, which may differ from what the user typed if the C option was omitted, or an empty string if EndReason is not "Match".
219 |Retrieves or sets the function object which is called when Input is terminated.
223 |MyCallback := InputHookObj.OnEnd
224 | InputHookObj.OnEnd := MyCallback
225 | MyCallback is the function object to call. An empty string means no function object.
226 |The callback accepts one parameter and can be defined as follows:
227 |MyCallback(InputHookObj) { ...228 |
Although the name you give the parameter does not matter, it is assigned a reference to the InputHook object.
229 |You can omit the callback's parameter if the corresponding information is not needed, but in this case an asterisk must be specified, e.g. MyCallback(*)
.
The function is called as a new thread, so starts off fresh with the default values for settings such as SendMode and DetectHiddenWindows.
231 |Retrieves or sets the function object which is called after a character is added to the input buffer.
235 |MyCallback := InputHookObj.OnChar
236 | InputHookObj.OnChar := MyCallback
237 | MyCallback is the function object to call. An empty string means no function object.
238 |The callback accepts two parameters and can be defined as follows:
239 |MyCallback(InputHookObj, Char) { ...240 |
Although the names you give the parameters do not matter, the following values are sequentially assigned to them:
241 |You can omit one or more parameters from the end of the callback's parameter list if the corresponding information is not needed, but in this case an asterisk must be specified as the final parameter, e.g. MyCallback(Param1, *)
.
The presence of multiple characters indicates that a dead key was used prior to the last keypress, but the two keys could not be transliterated to a single character. For example, on some keyboard layouts `e produces è
while `z produces `z
.
The function is never called when an end key is pressed.
248 |Retrieves or sets the function object which is called when a notification-enabled key is pressed.
252 |MyCallback := InputHookObj.OnKeyDown
253 | InputHookObj.OnKeyDown := MyCallback
254 | Key-down notifications must first be enabled by KeyOpt or NotifyNonText.
255 |MyCallback is the function object to call. An empty string means no function object.
256 |The callback accepts three parameters and can be defined as follows:
257 |MyCallback(InputHookObj, VK, SC) { ...258 |
Although the names you give the parameters do not matter, the following values are sequentially assigned to them:
259 |You can omit one or more parameters from the end of the callback's parameter list if the corresponding information is not needed, but in this case an asterisk must be specified as the final parameter, e.g. MyCallback(Param1, *)
.
To retrieve the key name (if any), use GetKeyName(Format("vk{:x}sc{:x}", VK, SC))
.
The function is called as a new thread, so starts off fresh with the default values for settings such as SendMode and DetectHiddenWindows.
267 |The function is never called when an end key is pressed.
268 |Retrieves or sets the function object which is called when a notification-enabled key is released.
272 |MyCallback := InputHookObj.OnKeyUp
273 | InputHookObj.OnKeyUp := MyCallback
274 | Key-up notifications must first be enabled by KeyOpt or NotifyNonText. Whether a key is considered text or non-text is determined when the key is pressed. If an InputHook detects a key-up without having detected key-down, it is considered non-text.
275 |MyCallback is the function object to call. An empty string means no function object.
276 |The callback accepts three parameters and can be defined as follows:
277 |MyCallback(InputHookObj, VK, SC) { ...278 |
Although the names you give the parameters do not matter, the following values are sequentially assigned to them:
279 |You can omit one or more parameters from the end of the callback's parameter list if the corresponding information is not needed, but in this case an asterisk must be specified as the final parameter, e.g. MyCallback(Param1, *)
.
To retrieve the key name (if any), use GetKeyName(Format("vk{:x}sc{:x}", VK, SC))
.
The function is called as a new thread, so starts off fresh with the default values for settings such as SendMode and DetectHiddenWindows.
287 |Controls whether Backspace removes the most recently pressed character from the end of the Input buffer.
292 |CurrentSetting := InputHookObj.BackspaceIsUndo
293 | InputHookObj.BackspaceIsUndo := NewSetting
294 | CurrentSetting is NewSetting if assigned, otherwise 1 (true) by default unless overwritten by the B option.
295 |NewSetting is a boolean value that enables or disables this setting.
296 |When Backspace acts as undo, it is treated as a text entry key. Specifically, whether the key is suppressed depends on VisibleText rather than VisibleNonText.
297 |Backspace is always ignored if pressed in combination with a modifier key such as Ctrl (the logical modifier state is checked rather than the physical state).
298 |Note: If the input text is visible (such as in an editor) and the arrow keys or other means are used to navigate within it, Backspace will still remove the last character rather than the one behind the caret (insertion point).
299 |Controls whether MatchList is case-sensitive.
303 |CurrentSetting := InputHookObj.CaseSensitive
304 | InputHookObj.CaseSensitive := NewSetting
305 | CurrentSetting is NewSetting if assigned, otherwise 0 (false) by default unless overwritten by the C option.
306 |NewSetting is a boolean value that enables or disables this setting.
307 |Controls whether each match can be a substring of the input text.
311 |CurrentSetting := InputHookObj.FindAnywhere
312 | InputHookObj.FindAnywhere := NewSetting
313 | CurrentSetting is NewSetting if assigned, otherwise 0 (false) by default unless overwritten by the * option.
314 |NewSetting is a boolean value that enables or disables this setting. If true, a match can be found anywhere within what the user types (the match can be a substring of the input text). If false, the entirety of what the user types must match one of the MatchList phrases. In both cases, one of the MatchList phrases must be typed in full.
315 |Retrieves or sets the minimum send level of input to collect.
319 |CurrentLevel := InputHookObj.MinSendLevel
320 | InputHookObj.MinSendLevel := NewLevel
321 | CurrentLevel is NewLevel if assigned, otherwise 0 by default unless overwritten by the I option.
322 |NewLevel should be an integer between 0 and 101. Events which have 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).
323 |The SendInput and SendPlay methods are always ignored, regardless of this setting. Input generated by any source other than AutoHotkey is never ignored as a result of this setting.
324 |Controls whether the OnKeyDown and OnKeyUp callbacks are called whenever a non-text key is pressed.
328 |CurrentSetting := InputHookObj.NotifyNonText
329 | InputHookObj.NotifyNonText := NewSetting
330 | CurrentSetting is NewSetting if assigned, otherwise 0 (false) by default.
331 |NewSetting is a boolean value that enables or disables this setting. If true, notifications are enabled for all keypresses which do not produce text, such as when pressing ← or Alt+F. Setting this property does not affect a key's options, since the production of text depends on the active window's keyboard layout at the time the key is pressed.
332 |NotifyNonText is applied to key-up events by considering whether a previous key-down with a matching VK code was classified as text or non-text. For example, if NotifyNonText is true, pressing Ctrl+A will produce OnKeyDown and OnKeyUp calls for both Ctrl and A, while pressing A on its own will not call OnKeyDown or OnKeyUp unless KeyOpt has been used to enable notifications for that key.
333 |See VisibleText for details about which keys are counted as producing text.
334 |Retrieves or sets the timeout value in seconds.
338 |CurrentSeconds := InputHookObj.Timeout
339 | InputHookObj.Timeout := NewSeconds
340 | CurrentSeconds is NewSeconds if assigned, otherwise 0 by default unless overwritten by the T option.
341 |NewSeconds is a floating-point number representing the timeout. 0 means no timeout.
342 |The timeout period ordinarily starts when Start is called, but will restart if this property is assigned a value while Input is in progress. If Input is still in progress when the timeout period elapses, it is terminated and EndReason is set to the word Timeout.
343 |Controls whether keys or key combinations which do not produce text are visible (not blocked).
347 |CurrentSetting := InputHookObj.VisibleNonText
348 | InputHookObj.VisibleNonText := NewSetting
349 | CurrentSetting is NewSetting if assigned, otherwise 1 (true) by default. The V option sets this to 1 (true).
350 |NewSetting is a boolean value that enables or disables this setting. If true, keys and key combinations which do not produce text may trigger hotkeys or be passed on to the active window. If false, they are blocked.
351 |See VisibleText for details about which keys are counted as producing text.
352 |Controls whether keys or key combinations which produce text are visible (not blocked).
356 |CurrentSetting := InputHookObj.VisibleText
357 | InputHookObj.VisibleText := NewSetting
358 | CurrentSetting is NewSetting if assigned, otherwise 0 (false) by default unless overwritten by the V option.
359 |NewSetting is a boolean value that enables or disables this setting. If true, keys and key combinations which produce text may trigger hotkeys or be passed on to the active window. If false, they are blocked.
360 |Any keystrokes which cause text to be appended to the Input buffer are counted as producing text, even if they do not normally do so in other applications. For instance, Ctrl+A produces text if the M option is used, and Esc produces the control character Chr(27)
.
Dead keys are counted as producing text, although they do not typically produce an immediate effect. Pressing a dead key might also cause the following key to produce text (if only the dead key's character).
362 |Backspace is counted as producing text only when it acts as undo.
363 |The standard modifier keys and CapsLock, NumLock and ScrollLock are always visible (not blocked).
364 |The EndReason property returns one of the following strings:
368 |String | 371 |Description | 372 |
---|---|
Stopped | 375 |The Stop method was called or the Start method has not yet been called for the first time. | 376 |
Max | 379 |The Input reached the maximum allowed length and it does not match any of the items in MatchList. | 380 |
Timeout | 383 |The Input timed out. | 384 |
Match | 387 |The Input matches one of the items in MatchList. The Match property contains the matched item. | 388 |
EndKey | 391 |
392 | One of the EndKeys was pressed to terminate the Input. The EndKey property contains the terminating key name or character without braces. 393 | |
394 |
397 | | If the Input is in progress, EndReason is blank. | 398 |
The Start method must be called before input will be collected.
403 |InputHook is designed to allow different parts of the script to monitor input, with minimal conflicts. It can operate continuously, such as to watch for arbitrary words or other patterns. It can also operate temporarily, such as to collect user input or temporarily override specific (or non-specific) keys without interfering with hotkeys.
404 |Keyboard hotkeys are still in effect while an Input is in progress, but cannot activate if any of the required modifier keys are suppressed, or if the hotkey uses the reg method and its suffix key is suppressed. For example, the hotkey ^+a::
might be overridden by InputHook, whereas the hotkey $^+a::
would take priority unless the InputHook suppressed Ctrl or Shift.
Keys are either suppressed (blocked) or not depending on the following factors (in order):
406 |The keyboard hook is required while an Input is in progress, but will be uninstalled automatically if it is no longer needed when the Input is terminated.
413 |The script is automatically persistent while an Input is in progress, so it will continue monitoring input even if there are no running threads. The script may exit automatically when input ends (if there are no running threads and the script is not persistent for some other reason).
414 |AutoHotkey does not support Input Method Editors (IME). The keyboard hook intercepts keyboard events and translates them to text by using ToUnicodeEx or ToAsciiEx (except in the case of VK_PACKET events, which encapsulate a single character).
415 |If you use multiple languages or keyboard layouts, InputHook uses the keyboard layout of the active window rather than the script's (regardless of whether the Input is visible).
416 |Although not as flexible, hotstrings are generally easier to use.
417 | 418 |In AutoHotkey v1.1, InputHook is a replacement for the Input command, offering greater flexbility. The Input command was removed for v2.0, but the code below is mostly equivalent:
420 |421 | ; Input OutputVar, % Options, % EndKeys, % MatchList ; v1 422 | ih := InputHook(Options, EndKeys, MatchList) 423 | ih.Start() 424 | ErrorLevel := ih.Wait() 425 | if (ErrorLevel = "EndKey") 426 | ErrorLevel .= ":" ih.EndKey 427 | OutputVar := ih.Input 428 |429 |
The Input command terminates any previous Input which it started, whereas InputHook allows more than one Input at a time.
430 |Options is interpreted the same, but the default settings differ:
431 |The Input command blocks the thread while it is in progress, whereas InputHook allows the thread to continue, or even exit (which allows any thread that it interrupted to resume). Instead of waiting, the script can register an OnEnd function to be called when the Input is terminated.
436 |The Input command returns the user's input only after the Input is terminated, whereas InputHook's Input property allows it to be retrieved at any time. The script can register an OnChar function to be called whenever a character is added, instead of continuously checking the Input property.
437 |InputHook gives much more control over individual keys via the KeyOpt method. This includes adding or removing end keys, suppressing or not suppressing specific keys, or ignoring the text produced by specific keys.
438 |Unlike the Input command, InputHook can be used to detect keys which do not produce text, without terminating the Input. This is done by registering an OnKeyDown function and using KeyOpt or NotifyNonText to specify which keys are of interest.
439 |If a MatchList item caused the Input to terminate, the Match property can be consulted to determine exactly which match (this is more useful when the * option is present).
440 |Although the script can consult GetKeyState after the Input command returns, sometimes it does not accurately reflect which keys were pressed when the Input was terminated. InputHook's EndMods property reflects the logical state of the modifier keys at the time Input was terminated.
441 |There are some differences relating to backward-compatibility:
442 |If a key name used in EndKeys corresponds to a VK which is shared between two physical keys (such as NumpadUp and Up), the Input command handles the primary key by VK and the secondary key by SC, whereas InputHook handles both by SC. {vkNN}
notation can be used to handle the key by VK.
When the end key is handled by VK, both physical keys can terminate the Input. For example, {NumpadUp}
would cause the Input command to be terminated by pressing Up, but ErrorLevel would contain EndKey:NumpadUp
since only the VK is considered.
When an end key is handled by SC, the Input command always produces names for the known secondary SC of any given VK, and always produces scNNN
for any other key (even if it has a name). By contrast, InputHook produces a name if the key has one.
KeyWait, Hotstrings, InputBox, InstallKeybdHook, Threads
451 | 452 |Waits for the user to press any single key.
455 |456 | MsgBox KeyWaitAny() 457 | 458 | ; Same again, but don't block the key. 459 | MsgBox KeyWaitAny("V") 460 | 461 | KeyWaitAny(Options:="") 462 | { 463 | ih := InputHook(Options) 464 | if !InStr(Options, "V") 465 | ih.VisibleNonText := false 466 | ih.KeyOpt("{All}", "E") ; End 467 | ih.Start() 468 | ih.Wait() 469 | return ih.EndKey ; Return the key name 470 | } 471 |472 |
Waits for any key in combination with Ctrl/Alt/Shift/Win.
475 |476 | MsgBox KeyWaitCombo() 477 | 478 | KeyWaitCombo(Options:="") 479 | { 480 | ih := InputHook(Options) 481 | if !InStr(Options, "V") 482 | ih.VisibleNonText := false 483 | ih.KeyOpt("{All}", "E") ; End 484 | ; Exclude the modifiers 485 | ih.KeyOpt("{LCtrl}{RCtrl}{LAlt}{RAlt}{LShift}{RShift}{LWin}{RWin}", "-E") 486 | ih.Start() 487 | ih.Wait() 488 | return ih.EndMods . ih.EndKey ; Return a string like <^<+Esc 489 | } 490 |491 |
Simple auto-complete: any day of the week. Pun aside, this is a mostly functional example. Simply run the script and start typing today, press Tab to complete or press Esc to exit.
494 |WordList := "Monday`nTuesday`nWednesday`nThursday`nFriday`nSaturday`nSunday" 495 | 496 | Suffix := "" 497 | 498 | SacHook := InputHook("V", "{Esc}") 499 | SacHook.OnChar := SacChar 500 | SacHook.OnKeyDown := SacKeyDown 501 | SacHook.KeyOpt("{Backspace}", "N") 502 | SacHook.Start() 503 | 504 | SacChar(ih, char) ; Called when a character is added to SacHook.Input. 505 | { 506 | global Suffix := "" 507 | if RegExMatch(ih.Input, "`nm)\w+$", &prefix) 508 | && RegExMatch(WordList, "`nmi)^" prefix[0] "\K.*", &Suffix) 509 | Suffix := Suffix[0] 510 | 511 | if CaretGetPos(&cx, &cy) 512 | ToolTip Suffix, cx + 15, cy 513 | else 514 | ToolTip Suffix 515 | 516 | ; Intercept Tab only while we're showing a tooltip. 517 | ih.KeyOpt("{Tab}", Suffix = "" ? "-NS" : "+NS") 518 | } 519 | 520 | SacKeyDown(ih, vk, sc) 521 | { 522 | if (vk = 8) ; Backspace 523 | SacChar(ih, "") 524 | else if (vk = 9) ; Tab 525 | Send "{Text}" Suffix 526 | } 527 |528 |
Waits for the user to press any key. Keys that produce no visible character -- such as the modifier keys, function keys, and arrow keys -- are listed as end keys so that they will be detected too.
531 |ih := InputHook("L1", "{LControl}{RControl}{LAlt}{RAlt}{LShift}{RShift}{LWin}{RWin}{AppsKey}{F1}{F2}{F3}{F4}{F5}{F6}{F7}{F8}{F9}{F10}{F11}{F12}{Left}{Right}{Up}{Down}{Home}{End}{PgUp}{PgDn}{Del}{Ins}{BS}{CapsLock}{NumLock}{PrintScreen}{Pause}") 532 | ih.Start() 533 | ih.Wait()534 |
This is a working hotkey example. Since the hotkey has the tilde (~) prefix, its own keystroke will pass through to the active window. Thus, if you type [btw
(or one of the other match phrases) in any editor, the script will automatically perform an action of your choice (such as replacing the typed text). For an alternative version of this example, see Switch.
~[:: 538 | { 539 | msg := "" 540 | ih := InputHook("V T5 L4 C", "{enter}.{esc}{tab}", "btw,otoh,fl,ahk,ca") 541 | ih.Start() 542 | ih.Wait() 543 | if (ih.EndReason = "Max") 544 | msg := 'You entered "{1}", which is the maximum length of text.' 545 | else if (ih.EndReason = "Timeout") 546 | msg := 'You entered "{1}" at which time the input timed out.' 547 | else if (ih.EndReason = "EndKey") 548 | msg := 'You entered "{1}" and terminated the input with {2}.' 549 | 550 | if msg ; If an EndReason was found, skip the rest below. 551 | { 552 | MsgBox Format(msg, ih.Input, ih.EndKey) 553 | return 554 | } 555 | 556 | ; Otherwise, a match was found. 557 | if (ih.Input = "btw") 558 | Send("{backspace 4}by the way") 559 | else if (ih.Input = "otoh") 560 | Send("{backspace 5}on the other hand") 561 | else if (ih.Input = "fl") 562 | Send("{backspace 3}Florida") 563 | else if (ih.Input = "ca") 564 | Send("{backspace 3}California") 565 | else if (ih.Input = "ahk") 566 | Run("https://www.autohotkey.com") 567 | }568 |
Installs or uninstalls the keyboard hook.
17 |InstallKeybdHook Install, Force18 | 19 |
Type: Boolean
25 |If omitted, it defaults to true.
26 |If true, the hook is required to be installed.
27 |If false, any requirement previously set by this function is removed, potentially uninstalling the hook.
28 |Type: Boolean
33 |If omitted, it defaults to false.
34 |If false, an internal variable is updated to indicate whether the hook is required by the script, but there might be no immediate change if the hook is required for some other purpose.
35 |If true and Install is true, the hook is uninstalled and reinstalled. This has the effect of giving it precedence over any hooks previously installed by other processes. If the system has stopped calling the hook due to an unresponsive program, reinstalling the hook might get it working again.
36 |If true and Install is false, the hook is uninstalled even if needed for some other purpose. If a hotkey, hotstring or InputHook requires the hook, it will stop working until the hook is reinstalled. The hook may be reinstalled explicitly by calling this function, or automatically as a side-effect of enabling or disabling a hotkey or calling some other function which requires the hook.
37 |The keyboard hook monitors keystrokes for the purpose of activating hotstrings and any keyboard hotkeys not supported by RegisterHotkey (which is a function built into the operating system). It also supports a few other features such as the InputHook function.
43 |AutoHotkey does not install the keyboard and mouse hooks unconditionally because together they consume at least 500 KB of memory. Therefore, the keyboard hook is normally installed only when the script contains one of the following: 1) hotstrings; 2) one or more hotkeys that require the keyboard hook (most do not); 3) SetCaps/Scroll/NumLock AlwaysOn/AlwaysOff; 4) active Input hooks.
44 |By contrast, the InstallKeybdHook function can be used to unconditionally install the keyboard hook, which has benefits including:
45 |!LButton::
) can suppress the window menu more efficiently, by sending only one menu mask key when the Alt key is released, instead of sending one each time the button is clicked.Keyboard hotkeys which do not require the hook will use the reg method even if the InstallKeybdHook function is used. By contrast, applying the #UseHook directive or the $ prefix to a keyboard hotkey forces it to require the hook, which causes the hook to be installed if the hotkey is enabled.
53 |You can determine whether a script is using the hook via the KeyHistory function or menu item. You can determine which hotkeys are using the hook via the ListHotkeys function or menu item.
54 | 55 |InstallMouseHook, #UseHook, Hotkey, InputHook, KeyHistory, Hotstrings, GetKeyState, KeyWait
57 |Installs or uninstalls the mouse hook.
17 |InstallMouseHook Install, Force18 | 19 |
Type: Boolean
25 |If omitted, it defaults to true.
26 |If true, the hook is required to be installed.
27 |If false, any requirement previously set by this function is removed, potentially uninstalling the hook.
28 |Type: Boolean
33 |If omitted, it defaults to false.
34 |If false, an internal variable is updated to indicate whether the hook is required by the script, but there might be no immediate change if the hook is required for some other purpose.
35 |If true and Install is true, the hook is uninstalled and reinstalled. This has the effect of giving it precedence over any hooks previously installed by other processes. If the system has stopped calling the hook due to an unresponsive program, reinstalling the hook might get it working again.
36 |If true and Install is false, the hook is uninstalled even if needed for some other purpose. If a hotkey, hotstring or InputHook requires the hook, it will stop working until the hook is reinstalled. The hook may be reinstalled explicitly by calling this function, or automatically as a side-effect of enabling or disabling a hotkey or calling some other function which requires the hook.
37 |The mouse hook monitors mouse clicks for the purpose of activating mouse hotkeys and facilitating hotstrings.
43 |AutoHotkey does not install the keyboard and mouse hooks unconditionally because together they consume at least 500 KB of memory (but if the keyboard hook is installed, installing the mouse hook only requires about 50 KB of additional memory; and vice versa). Therefore, the mouse hook is normally installed only when the script contains one or more mouse hotkeys. It is also installed for hotstrings, but that can be disabled via #Hotstring NoMouse.
44 |By contrast, the InstallMouseHook function can be used to unconditionally install the mouse hook, which has benefits including:
45 |You can determine whether a script is using the hook via the KeyHistory function or menu item. You can determine which hotkeys are using the hook via the ListHotkeys function or menu item.
51 | 52 |InstallKeybdHook, #UseHook, Hotkey, KeyHistory, GetKeyState, KeyWait
54 |Converts a numeric string or floating-point value to an integer.
16 |IntValue := Integer(Value)
17 |
18 | Type: Integer
20 |This function returns the result of converting Value to a pure integer (having the type name "Integer"), or Value itself if it is already the correct type.
21 | 22 |Any fractional part of Value is dropped, equivalent to Value < 0 ? Ceil(Value) : Floor(Value)
.
If the value cannot be converted, a TypeError is thrown.
25 |To determine if a value can be converted to an integer, use the IsNumber function.
26 |Integer is actually a class, but can be called as a function. Value is Integer
can be used to check whether a value is a pure integer.
Type, Float, Number, String, Values, Expressions, Is functions
30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /docs/lib/Is.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Functions for checking the type and other conditions of a given value.
16 |Result := IsSomething(Value , Mode)
17 |
18 | There are three categories:
19 |Mode is valid only for IsAlpha, IsAlnum, IsUpper and IsLower. By default, only ASCII letters are considered. To instead perform the check according to the rules of the current user's locale, specify the string "Locale"
for the Mode parameter. The default mode can also be used by specifying 0 or 1.
Check the type of a value, or whether a string can be interpreted as a value of that type.
28 |Function | 31 |Description | 32 |
---|---|
IsInteger | 35 |True if Value is an integer or a purely numeric string (decimal or hexadecimal) without a decimal point. Leading and trailing spaces and tabs are allowed. The string may start with a plus or minus sign and must not be empty. | 36 |
IsFloat | 39 |True if Value is a floating point number or a purely numeric string containing a decimal point. Leading and trailing spaces and tabs are allowed. The string may start with a plus sign, minus sign, or decimal point and must not be empty. | 40 |
IsNumber | 43 |True if IsInteger(Value) or IsFloat(Value) is true. |
44 |
IsObject | 47 |True if Value is an object. This includes objects derived from Object, prototype objects such as 0.base , and COM objects, but not numbers or strings. |
48 |
Check miscellaneous conditions based on a given value or variable reference.
53 |Function | 56 |Description | 57 |
---|---|
IsLabel | 60 |True if Value is the name of a label defined within the current scope. | 61 |
IsSet | 64 |True if the variable Value has been assigned a value. | 65 |
IsSetRef | 68 |True if the VarRef contained by Value has been assigned a value. | 69 |
Check whether a string matches a specific pattern. Value must be a string, otherwise a TypeError is thrown.
74 |Function | 77 |Description | 78 |
---|---|
IsDigit | 81 |True if Value is a positive integer, an empty string, or a string which contains only the characters 0 through 9. Other characters such as the following are not allowed: spaces, tabs, plus signs, minus signs, decimal points, hexadecimal digits, and the 0x prefix. | 82 |
IsXDigit | 85 |Hexadecimal digit: Same as IsDigit except the characters A through F (uppercase or lowercase) are also allowed. A prefix of 0x is tolerated if present. | 86 |
IsAlpha | 89 |
90 | True if Value is a string and is empty or contains only alphabetic characters. False if there are any digits, spaces, tabs, punctuation, or other non-alphabetic characters anywhere in the string. For example, if Value contains a space followed by a letter, it is not considered to be alpha. 91 |By default, only ASCII letters are considered. To instead perform the check according to the rules of the current user's locale, use |
93 |
IsUpper | 96 |
97 | True if Value is a string and is empty or contains only uppercase characters. False if there are any digits, spaces, tabs, punctuation, or other non-uppercase characters anywhere in the string. 98 |By default, only ASCII letters are considered. To instead perform the check according to the rules of the current user's locale, use |
100 |
IsLower | 103 |
104 | True if Value is a string and is empty or contains only lowercase characters. False if there are any digits, spaces, tabs, punctuation, or other non-lowercase characters anywhere in the string. 105 |By default, only ASCII letters are considered. To instead perform the check according to the rules of the current user's locale, use |
107 |
IsAlnum | 110 |Same as IsAlpha except that integers and characters 0 through 9 are also allowed. | 111 |
IsSpace | 114 |True if Value is a string and is empty or contains only whitespace consisting of the following characters: space (A_Space or `s), tab (A_Tab or `t), linefeed (`n), return (`r), vertical tab (`v), and formfeed (`f). | 115 |
IsTime | 118 |True if Value is a valid date-time stamp, which can be all or just the leading part of the YYYYMMDDHH24MISS format. For example, a 4-digit string such as 2004 is considered valid. Use StrLen to determine whether additional time components are present. 119 |Value must have an even number of digits between 4 and 14 (inclusive) to be considered valid. 120 |Years less than 1601 are not considered valid because the operating system generally does not support them. The maximum year considered valid is 9999. 121 | |
122 |
Since literal numbers such as 128
, 0x7F
and 1.0
are converted to pure numbers before the script begins executing, the format of the literal number is lost. To avoid confusion, the string functions listed above throw an exception if they are given a pure number.
A_YYYY, FileGetTime, If, StrLen, InStr, StrUpper, DateAdd
130 | 131 |Checks whether var is a floating point number or an integer and checks whether it is a valid timestamp.
134 |135 | if isFloat(var) 136 | MsgBox var " is a floating point number." 137 | else if isInteger(var) 138 | MsgBox var " is an integer." 139 | if isTime(var) 140 | MsgBox var " is also a valid date-time." 141 |142 |
Returns a non-zero number if the specified label exists in the current scope.
16 | 17 |Boolean := IsLabel(LabelName)
18 | Type: String
24 |The name of a label. The trailing colon should not be included.
25 |Type: Integer (boolean)
31 |This function returns 1 (true) if the specified label exists within the current scope, otherwise 0 (false).
32 | 33 |This function is useful to avoid runtime errors when specifying a dynamic label for Goto.
35 |When called from inside a function, only that function's labels are searched. Global labels are not valid targets for a local goto.
36 | 37 |Reports "Target label exists" because the label does exist.
42 |if IsLabel("Label") 43 | MsgBox "Target label exists" 44 | else 45 | MsgBox "Target label doesn't exist" 46 | 47 | Label: 48 | return49 |
Returns a non-zero number if the specified value is an object.
16 | 17 |Boolean := IsObject(Value)
18 | Type: Any
24 |The value to check.
25 |Type: Integer (boolean)
31 |This function returns 1 (true) if Value is an object, otherwise 0 (false).
32 | 33 |Any value which is not a primitive value (number or string) is considered to be an object, including those which do not derive from Object, such as COM wrapper objects. This distinction is made because objects share several common traits in contrast to primitive values:
35 |Reports "This is an object." because the value is an object.
47 |obj := {key: "value"} 48 | 49 | if IsObject(obj) 50 | MsgBox "This is an object." 51 | else 52 | MsgBox "This is not an object."53 |
Returns a non-zero number if the specified variable has been assigned a value.
16 | 17 |Boolean := IsSet(Var) 18 | Boolean := IsSetRef(&Ref)19 |
Type: Variable
25 |A direct variable reference. For example: IsSet(MyVar)
.
Type: VarRef
31 |An indirect reference to the variable. This would usually not be passed directly, as in IsSetRef(&MyVar)
, but indirectly, such as to check a parameter containing a VarRef prior to dereferencing it.
Type: Integer (boolean)
38 |This function returns 1 (true) if Var or the variable represented by Ref has been assigned a value, otherwise 0 (false).
39 | 40 |Use IsSet to check a variable directly, as in IsSet(MyGlobalVar)
.
Use IsSetRef to check a VarRef, which would typically be contained by a variable, as in the example below.
43 |A variable which has not been assigned a value is also known as an uninitialized variable. Attempting to read an uninitialized variable causes an exception to be thrown. IsSet can be used to avoid this, such as for initializing a global or static variable on first use.
44 |Note: Static initializers such as static my_static_array := []
are evaluated only once, the first time they are reached during execution, so typically do not require the use of IsSet.
Although IsSet uses the same syntax as a function call, it may be considered more of an operator than a function. The keyword IsSet is reserved for the use shown here and cannot be redefined as a variable or function. IsSet cannot be called indirectly because any attempt to pass an uninitialized variable would cause an error to be thrown.
46 |IsSetRef can also be used to check a specific variable, by using it with the reference operator. When using it this way, be aware of the need to declare the variable first if it is global. For example, the &
in IsSetRef(&MyVar)
would cause MyVar to resolve to a local variable by default, if used within an assume-local function which lacks the declaration global MyVar
.
Shows different uses for IsSet and IsSetRef.
53 |54 | Loop 2 55 | if !IsSet(MyVar) ; Is this the first "use" of MyVar? 56 | MyVar := A_Index ; Initialize on first "use". 57 | MsgBox Function1(&MyVar) 58 | MsgBox Function2(&MyVar) 59 | 60 | Function1(&Param) ; ByRef parameter. 61 | { 62 | if IsSet(Param) ; Pass Param itself, which is an alias for MyVar. 63 | return Param ; ByRef parameters are automatically dereferenced. 64 | else 65 | return "unset" 66 | } 67 | 68 | Function2(Param) 69 | { 70 | if IsSetRef(Param) ; Pass the VarRef contained by Param. 71 | return %Param% ; Explicitly dereference Param. 72 | else 73 | return "unset" 74 | }75 |
Displays script info and a history of the most recent keystrokes and mouse clicks.
16 | 17 |KeyHistory MaxEvents18 |
Type: Integer
24 |If omitted, the script's main window will be shown, equivalent to selecting the "View->Key history" menu item. Otherwise, specify the maximum number of keyboard and mouse events that can be recorded for display in the window (limit 500). The key history is also reset, but the main window is not shown or refreshed. Specify 0 to disable key history entirely.
25 |If KeyHistory is not used, the default setting is 40.
31 |To disable key history, use the following:
32 |KeyHistory 033 |
This feature is intended to help debug scripts and hotkeys. It can also be used to detect the scan code of a non-standard keyboard key using the steps described at the bottom of the key list page (knowing the scan code allows such a key to be made into a hotkey).
34 |The virtual key codes (VK) of the wheel events (WheelDown, WheelUp, WheelLeft, and WheelRight) are placeholder values that do not have any meaning outside of AutoHotkey. Also, the scan code for wheel events is actually the number of notches by which the wheel was turned (typically 1).
35 |If the script does not have the keyboard hook installed, the KeyHistory window will display only the keyboard events generated by the script itself (i.e. not the user's). If the script does not have the mouse hook installed, mouse button events will not be shown. You can find out if your script uses either hook via "View->Key History" in the script's main window (accessible via "Open" in the tray icon). You can force the hooks to be installed by adding either or both of the following lines to the script:
36 |InstallKeybdHook 37 | InstallMouseHook38 |
Because each keystroke or mouse click consists of a down-event and an up-event, KeyHistory displays only half as many "complete events" as specified by MaxEvents. For example, if the script calls KeyHistory 50
, up to 25 keystrokes and mouse clicks will be displayed.
InstallKeybdHook, InstallMouseHook, ListHotkeys, ListLines, ListVars, GetKeyState, KeyWait, A_PriorKey
42 | 43 |Causes KeyHistory to display the last 100 instead 40 keyboard and mouse events.
52 |KeyHistory 10053 |
Waits for a key or mouse/controller button to be released or pressed down.
16 | 17 |KeyWait KeyName , Options18 |
Type: String
24 |This can be just about any single character from the keyboard or one of the key names from the key list, such as a mouse/controller button. Controller attributes other than buttons are not supported.
25 |An explicit virtual key code such as vkFF
may also be specified. This is useful in the rare case where a key has no name and produces no visible character when pressed. Its virtual key code can be determined by following the steps at the bottom of the key list page.
Type: String
30 |If blank or omitted, the function will wait indefinitely for the specified key or mouse/controller button to be physically released by the user. However, if the keyboard hook is not installed and KeyName is a keyboard key released artificially by means such as the Send function, the key will be seen as having been physically released. The same is true for mouse buttons when the mouse hook is not installed.
31 |Otherwise, specify a string of one or more of the following options (in any order, with optional spaces in between):
32 |D: Wait for the key to be pushed down.
33 |L: Check the logical state of the key, which is the state that the OS and the active window believe the key to be in (not necessarily the same as the physical state). This option is ignored for controller buttons.
34 |T: Timeout (e.g. T3
). The number of seconds to wait before timing out and returning 0. If the key or button achieves the specified state, the function will not wait for the timeout to expire. Instead, it will immediately return 1.
The timeout value can be a floating point number such as 2.5, but it should not be a hexadecimal value such as 0x03.
Type: Integer (boolean)
41 |This function returns 0 (false) if the function timed out or 1 (true) otherwise.
42 | 43 |The physical state of a key or mouse button will usually be the same as the logical state unless the keyboard and/or mouse hooks are installed, in which case it will accurately reflect whether or not the user is physically holding down the key. You can determine if your script is using the hooks via the KeyHistory function or menu item. You can force either or both of the hooks to be installed by adding the InstallKeybdHook and InstallMouseHook functions to the script.
45 |While the function is in a waiting state, new threads can be launched via hotkey, custom menu item, or timer.
46 |To wait for two or more keys to be released, use KeyWait consecutively. For example:
47 |KeyWait "Control" ; Wait for both Control and Alt to be released. 48 | KeyWait "Alt"49 |
To wait for any one key among a set of keys to be pressed down, see InputHook example #4.
50 |GetKeyState, Key List, InputHook, KeyHistory, InstallKeybdHook, InstallMouseHook, ClipWait, WinWait
52 |Waits up to 3 seconds for the first controller button to be pressed down.
65 |KeyWait "Joy1", "D T3"66 |
When pressing this hotkey, KeyWait waits for the user to physically release the CapsLock key. As a result, subsequent statements are performed on release instead of press. This behavior is similar to ~CapsLock up::
.
~CapsLock:: 76 | { 77 | KeyWait "CapsLock" ; Wait for user to physically release it. 78 | MsgBox "You pressed and released the CapsLock key." 79 | }80 |
Remaps a key or mouse button. (This example is only for illustration because it would be easier to use the built-in remapping feature.) In the following hotkey, the mouse button is kept held down while NumpadAdd is down, which effectively transforms NumpadAdd into a mouse button.
84 |*NumpadAdd:: 85 | { 86 | MouseClick "left",,, 1, 0, "D" ; Hold down the left mouse button. 87 | KeyWait "NumpadAdd" ; Wait for the key to be released. 88 | MouseClick "left",,, 1, 0, "U" ; Release the mouse button. 89 | }90 |
Detects when a key has been double-pressed (similar to double-click). KeyWait is used to stop the keyboard's auto-repeat feature from creating an unwanted double-press when you hold down the RControl key to modify another key. It does this by keeping the hotkey's thread running, which blocks the auto-repeats by relying upon #MaxThreadsPerHotkey being at its default setting of 1. For a more elaborate script that distinguishes between single, double and triple-presses, see SetTimer example #3.
94 |~RControl:: 95 | { 96 | if (A_PriorHotkey != "~RControl" or A_TimeSincePriorHotkey > 400) 97 | { 98 | ; Too much time between presses, so this isn't a double-press. 99 | KeyWait "RControl" 100 | return 101 | } 102 | MsgBox "You double-pressed the right control key." 103 | }104 |
Displays the hotkeys in use by the current script, whether their subroutines are currently running, and whether or not they use the keyboard or mouse hook.
16 | 17 |ListHotkeys
18 | This function is equivalent to selecting the View->Hotkeys menu item in the main window.
19 |If a hotkey has been disabled via the Hotkey function, it will be listed as OFF or PART ("PART" means that only some of the hotkey's variants are disabled).
20 |If any of a hotkey's variants have a non-zero #InputLevel, the level (or minimum and maximum levels) are displayed.
21 |If any of a hotkey's subroutines are currently running, the total number of threads is displayed for that hotkey.
22 |Finally, the type of hotkey is also displayed, which is one of the following:
23 |InstallKeybdHook, InstallMouseHook, #UseHook, KeyHistory, ListLines, ListVars, #MaxThreadsPerHotkey, A_MaxHotkeysPerInterval
34 | 35 |Enables or disables line logging or displays the script lines most recently executed.
16 | 17 |ListLines Mode18 |
Type: Integer (boolean)
24 |If omitted, the history of lines most recently executed is shown. Otherwise, specify one of the following numbers, which affects only the behavior of the current thread as follows:
25 |1 (true): Include subsequently-executed lines in the history.
26 |0 (false): Omit subsequently-executed lines from the history.
Type: Integer (boolean)
32 |This function returns the previous setting; either 0 (false) or 1 (true).
33 | 34 |If ListLines is not used to affect line logging, the default setting is 1 (true).
36 |ListLines
(with no parameter) is equivalent to selecting the "View->Lines most recently executed" menu item in the main window. It can help debug a script.
ListLines False
and ListLines True
can be used to selectively omit some lines from the history, which can help prevent the history from filling up too quickly (such as in a loop with many fast iterations). The line which called ListLines is also removed from the line history, to prevent clutter. Additionally, performance may be reduced by a few percent while line logging is enabled.
When the ListLines mode is changed, the current line (generally the one that called ListLines or assigned to A_ListLines) is omitted from the line history.
39 |Every newly launched thread (such as a hotkey, custom menu item, or timed subroutine) starts off fresh with the default setting for this function. That default may be changed by using this function during script startup.
40 |The built-in variable A_ListLines contains 1 if ListLines is enabled and 0 otherwise.
41 |On a related note, the built-in variables A_LineNumber and A_LineFile contain the currently executing line number and the file name to which it belongs.
42 | 43 |KeyHistory, ListHotkeys, ListVars
45 |Enables and disables line logging for specific lines and then displays the result.
48 |x := "This line is logged" 49 | ListLines False 50 | x := "This line is not logged" 51 | ListLines True 52 | ListLines 53 | MsgBox54 |
Displays the script's variables: their names and current contents.
16 | 17 |ListVars
18 | This function is equivalent to selecting the "View->Variables" menu item in the main window. It can help debug a script.
20 |For each variable in the list, the variable's name and contents are shown, along with other information depending on what the variable contains. Each item is terminated with a carriage return and newline (`r`n
), but may span multiple lines if the variable contains `r`n
.
List items may take the following forms (where words in italics are placeholders):
22 |23 | VarName[Length of Capacity]: String 24 | VarName: TypeName object {Info} 25 | VarName: Number 26 |27 |
Capacity is the variable's current capacity.
28 |String is the first 60 characters of the variable's string value.
29 |Info depends on the type of object, but is currently very limited.
30 |If ListVars is used inside a function, the following are listed:
31 |KeyHistory, ListHotkeys, ListLines
40 |The DebugVars script can be used to inspect and change the contents of variables and objects.
41 | 42 |Displays information about the script's variables.
45 |var1 := "foo" 46 | var2 := "bar" 47 | obj := [] 48 | ListVars 49 | Pause50 |
A ListView is one of the most elaborate controls provided by the operating system. In its most recognizable form, it displays a tabular view of rows and columns, the most common example of which is Explorer's list of files and folders (detail view).
28 |A ListView usually looks like this:
29 | 30 |Though it may be elaborate, a ListView's basic features are easy to use. The syntax for creating a ListView is:
31 |LV := GuiObj.Add("ListView", Options, ["ColumnTitle1", "ColumnTitle2", "..."])
32 | Or:
33 |LV := GuiObj.AddListView(Options, ["ColumnTitle1", "ColumnTitle2", "..."])
34 | Here is a working script that creates and displays a ListView containing a list of files in the user's "My Documents" folder:
35 |; Create the window: 36 | MyGui := Gui() 37 | 38 | ; Create the ListView with two columns, Name and Size: 39 | LV := MyGui.Add("ListView", "r20 w700", ["Name", "Size (KB)"]) 40 | 41 | ; Notify the script whenever the user double clicks a row: 42 | LV.OnEvent("DoubleClick", LV_DoubleClick) 43 | 44 | ; Gather a list of file names from a folder and put them into the ListView: 45 | Loop Files, A_MyDocuments "\*.*" 46 | LV.Add(, A_LoopFileName, A_LoopFileSizeKB) 47 | 48 | LV.ModifyCol() ; Auto-size each column to fit its contents. 49 | LV.ModifyCol(2, "Integer") ; For sorting purposes, indicate that column 2 is an integer. 50 | 51 | ; Display the window: 52 | MyGui.Show() 53 | 54 | LV_DoubleClick(LV, RowNumber) 55 | { 56 | RowText := LV.GetText(RowNumber) ; Get the text from the row's first field. 57 | ToolTip("You double-clicked row number " RowNumber ". Text: '" RowText "'") 58 | }59 |
Background: Specify the word Background followed immediately by a color name (see color chart) or RGB value (the 0x prefix is optional). Examples: BackgroundSilver
, BackgroundFFDD99
. If this option is not present, the ListView initially defaults to the system's default background color. Specifying BackgroundDefault
or -Background
applies the system's default background color (usually white). For example, a ListView can be restored to the default color via LV.Opt("+BackgroundDefault")
.
C: Text color. Specify the letter C followed immediately by a color name (see color chart) or RGB value (the 0x prefix is optional). Examples: cRed
, cFF2211
, c0xFF2211
, cDefault
.
Checked: Provides a checkbox at the left side of each row. When adding a row, specify the word Check in its options to have the box to start off checked instead of unchecked. The user may either click the checkbox or press the spacebar to check or uncheck a row.
63 |Count: Specify the word Count followed immediately by the total number of rows that the ListView will ultimately contain. This is not a limit: rows beyond the count can still be added. Instead, this option serves as a hint to the control that allows it to allocate memory only once rather than each time a row is added, which greatly improves row-adding performance (it may also improve sorting performance). To improve performance even more, use LV.Opt("-Redraw")
prior to adding a large number of rows and LV.Opt("+Redraw")
afterward. See Redraw for more details.
Grid: Provides horizontal and vertical lines to visually indicate the boundaries between rows and columns.
65 |Hdr: Specify -Hdr
(minus Hdr) to omit the header (the special top row that contains column titles). To make it visible later, use LV.Opt("+Hdr")
.
LV: Specify the string LV followed immediately by the number of an extended ListView style. These styles are entirely separate from generic extended styles. For example, specifying -E0x200
would remove the generic extended style WS_EX_CLIENTEDGE to eliminate the control's default border. By contrast, specifying -LV0x20
would remove LVS_EX_FULLROWSELECT.
LV0x10: Specify -LV0x10
to prevent the user from dragging column headers to the left or right to reorder them. However, it is usually not necessary to do this because the physical reordering of columns does not affect the column order seen by the script. For example, the first column will always be column 1 from the script's point of view, even if the user has physically moved it to the right of other columns.
LV0x20: Specify -LV0x20
to require that a row be clicked at its first field to select it (normally, a click on any field will select it). The advantage of this is that it makes it easier for the user to drag a rectangle around a group of rows to select them.
Multi: Specify -Multi
(minus Multi) to prevent the user from selecting more than one row at a time.
NoSortHdr: Prevents the header from being clickable. It will take on a flat appearance rather than its normal button-like appearance. Unlike most other ListView styles, this one cannot be changed after the ListView is created.
71 |NoSort: Turns off the automatic sorting that occurs when the user clicks a column header. However, the header will still behave visually like a button (unless the NoSortHdr option above has been specified). In addition, the ColClick event is still raised, so the script can respond with a custom sort or other action.
72 |ReadOnly: Specify -ReadOnly
(minus ReadOnly) to allow editing of the text in the first column of each row. To edit a row, select it then press F2 (see the WantF2 option below). Alternatively, you can click a row once to select it, wait at least half a second, then click the same row again to edit it.
R: Rows of height (upon creation). Specify the letter R followed immediately by the number of rows for which to make room inside the control. For example, R10
would make the control 10 rows tall. If the ListView is created with a view mode other than report view, the control is sized to fit rows of icons instead of rows of text. Note: adding icons to a ListView's rows will increase the height of each row, which will make this option inaccurate.
Sort: The control is kept alphabetically sorted according to the contents of the first column.
75 |SortDesc: Same as above except in descending order.
76 |WantF2: Specify -WantF2
(minus WantF2) to prevent F2 from editing the currently focused row. This setting is ignored unless -ReadOnly is also in effect.
(Unnamed numeric styles): Since styles other than the above are rarely used, they do not have names. See the ListView styles table for a list.
78 |A ListView has five viewing modes, of which the most common is report view (which is the default). To use one of the other views, specify its name in the options list. The view can also be changed after the control is created; for example: LV.Opt("+IconSmall")
.
Icon: Shows a large-icon view. In this view and all the others except Report, the text in columns other than the first is not visible. To display icons in this mode, the ListView must have a large-icon ImageList assigned to it.
81 |Tile: Shows a large-icon view but with ergonomic differences such as displaying each item's text to the right of the icon rather than underneath it. Checkboxes do not function in this view.
82 |IconSmall: Shows a small-icon view.
83 |List: Shows a small-icon view in list format, which displays the icons in columns. The number of columns depends on the width of the control and the width of the widest text item in it.
84 |Report: Switches back to report view, which is the initial default. For example: LV.Opt("+Report")
.
In addition to the default methods/properties of a GUI control, ListView controls have the following methods (defined in the Gui.ListView class).
87 |When the phrase "row number" is used on this page, it refers to a row's current position within the ListView. The top row is 1, the second row is 2, and so on. After a row is added, its row number tends to change due to sorting, deleting, and inserting of other rows. Therefore, to locate specific row(s) based on their contents, it is usually best to use the GetText method in a loop.
88 |Row methods:
89 |Column methods:
96 |Retrieval methods:
102 |Other methods:
108 |Adds a new row to the bottom of the list.
115 |RowNumber := LV.Add(Options, Col1, Col2, ...)116 |
Type: String
121 |If blank or omitted, it defaults to no options. Otherwise, specify one or more options from the list below (not case-sensitive). Separate each option from the next with a space or tab. To remove an option, precede it with a minus sign. To add an option, a plus sign is permitted but not required.
122 |Check: Shows a checkmark in the row (if the ListView has checkboxes). To later uncheck it, use LV.Modify(RowNumber, "-Check")
.
Col: Specify the word Col followed immediately by the column number at which to begin applying the parameters Col1 and beyond. This is most commonly used with the Modify method to alter individual fields in a row without affecting those that lie to their left.
124 |Focus: Sets keyboard focus to the row (often used in conjunction with the Select option below). To later de-focus it, use LV.Modify(RowNumber, "-Focus")
.
Icon: Specify the word Icon followed immediately by the number of this row's icon, which is displayed in the left side of the first column. If this option is absent, the first icon in the ImageList is used. To display a blank icon, specify -1 or a number that is larger than the number of icons in the ImageList. If the control lacks a small-icon ImageList, no icon is displayed nor is any space reserved for one in report view.
126 |The Icon option accepts a one-based icon number, but this is internally translated to a zero-based index; therefore, Icon0
corresponds to the constant I_IMAGECALLBACK, which is normally defined as -1, and Icon-1
corresponds to I_IMAGENONE. Other out of range values may also cause a blank space where the icon would be.
Select: Selects the row. To later deselect it, use LV.Modify(RowNumber, "-Select")
. When selecting rows, it is usually best to ensure that at least one row always has the focus property because that allows the Apps key to display its context menu (if any) near the focused row. The word Select may optionally be followed immediately by a 0 or 1 to indicate the starting state. In other words, both "Select"
and "Select" . VarContainingOne
are the same (the period used here is the concatenation operator). This technique also works with the Focus and Check options above.
Vis: Ensures that the specified row is completely visible by scrolling the ListView, if necessary. This has an effect only for LV.Modify; for example: LV.Modify(RowNumber, "Vis")
.
Type: String
133 |The columns of the new row, which can be text or numeric (including numeric expression results). To make any field blank, specify ""
or the equivalent. If there are too few fields to fill all the columns, the columns at the end are left blank. If there are too many fields, the fields at the end are completely ignored.
Type: Integer
138 |This method returns the new row number, which is not necessarily the last row if the ListView has the Sort or SortDesc style.
139 |Inserts a new row at the specified row number.
144 |RowNumber := LV.Insert(RowNumber , Options, Col1, Col2, ...)145 |
Type: Integer
150 |The row number of the newly inserted row. Any rows at or beneath RowNumber are shifted downward to make room for the new row. If RowNumber is greater than the number of rows in the list (even as high as 2147483647), the new row is added to the end of the list.
151 |Type: String
155 |If blank or omitted, it defaults to no options. Otherwise, specify one or more options from the list above.
156 |Type: String
160 |The columns of the new row, which can be text or numeric (including numeric expression results). To make any field blank, specify ""
or the equivalent. If there are too few fields to fill all the columns, the columns at the end are left blank. If there are too many fields, the fields at the end are completely ignored.
Type: Integer
165 |This method returns the specified row number.
166 |Modifies the attributes and/or text of a row.
171 |LV.Modify(RowNumber , Options, NewCol1, NewCol2, ...)172 |
Type: Integer
177 |The number of the row to modify. If 0, all rows in the control are modified.
178 |Type: String
182 |If blank or omitted, it defaults to no options. Otherwise, specify one or more options from the list above. The Col option may be used to update specific columns without affecting the others.
183 |Type: String
187 |The new columns of the specified row, which can be text or numeric (including numeric expression results). To make any field blank, specify ""
or the equivalent. If there are too few parameters to cover all the columns, the columns at the end are not changed. If there are too many fields, the fields at the end are completely ignored.
When only the first two parameters are present, only the row's attributes and not its text are changed.
192 |Deletes the specified row or all rows.
197 |LV.Delete(RowNumber)198 |
Type: Integer
203 |If omitted, all rows in the ListView are deleted. Otherwise, specify the number of the row to delete.
204 |Modifies the attributes and/or text of the specified column and its header.
211 |LV.ModifyCol(ColumnNumber, Options, ColumnTitle)212 |
Type: Integer
217 |If this and the other parameters are all omitted, the width of every column is adjusted to fit the contents of the rows. This has no effect when not in Report (Details) view.
218 |Otherwise, specify the number of the column to modify. The first column is 1 (not 0).
219 |Type: String
223 |If omitted, it defaults to Auto (adjusts the column's width to fit its contents). Otherwise, specify one or more options from the list below (not case-sensitive). Separate each option from the next with a space or tab. To remove an option, precede it with a minus sign. To add an option, a plus sign is permitted but not required.
224 |General options:
226 |N: Specify for N the new width of the column, in pixels. This number can be unquoted if is the only option. For example, the following are both valid: LV.ModifyCol(1, 50)
and LV.ModifyCol(1, "50 Integer")
.
Auto: Adjusts the column's width to fit its contents. This has no effect when not in Report (Details) view.
228 |AutoHdr: Adjusts the column's width to fit its contents and the column's header text, whichever is wider. If applied to the last column, it will be made at least as wide as all the remaining space in the ListView. It is usually best to apply this setting only after the rows have been added because that allows any newly-arrived vertical scroll bar to be taken into account when sizing the last column. This has no effect when not in Report (Details) view.
229 |Icon: Specify the word Icon followed immediately by the number of the ImageList's icon to display next to the column header's text. Specify -Icon
(minus icon) to remove any existing icon.
IconRight: Puts the icon on the right side of the column rather than the left.
231 |Data type options:
233 |Float: For sorting purposes, indicates that this column contains floating point numbers (hexadecimal format is not supported). Sorting performance for Float and Text columns is up to 25 times slower than it is for integers.
234 |Integer: For sorting purposes, indicates that this column contains integers. To be sorted properly, each integer must be 32-bit; that is, within the range -2147483648 to 2147483647. If any of the values are not integers, they will be considered zero when sorting (unless they start with a number, in which case that number is used). Numbers may appear in either decimal or hexadecimal format (e.g. 0xF9E0
).
Text: Changes the column back to text-mode sorting, which is the initial default for every column. Only the first 8190 characters of text are significant for sorting purposes (except for the Logical option, in which case the limit is 4094).
236 |Alignment options:
238 |Center: Centers the text in the column. To center an Integer or Float column, specify the word Center after the word Integer or Float.
239 |Left: Left-aligns the column's text, which is the initial default for every column. On older operating systems, the first column might have a forced left-alignment.
240 |Right: Right-aligns the column's text. This attribute need not be specified for Integer and Float columns because they are right-aligned by default. That default can be overridden by specifying something such as "Integer Left"
or "Float Center"
.
Sorting options:
243 |Case: The sorting of the column is case-sensitive (affects only text columns). If the options Case, CaseLocale, and Logical are all omitted, the uppercase letters A-Z are considered identical to their lowercase counterparts for the purpose of the sort.
244 |CaseLocale: The sorting of the column is case-insensitive based on the current user's locale (affects only text columns). For example, most English and Western European locales treat the letters A-Z and ANSI letters like Ä and Ü as identical to their lowercase counterparts. This method also uses a "word sort", which treats hyphens and apostrophes in such a way that words like "coop" and "co-op" stay together.
245 |Desc: Descending order. The column starts off in descending order the first time the user sorts it.
246 |Logical: Same as CaseLocale except that any sequences of digits in the text are treated as true numbers rather than mere characters. For example, the string "T33" would be considered greater than "T4". Logical and Case are currently mutually exclusive: only the one most recently specified will be in effect.
247 |NoSort: Prevents a user's click on this column from having any automatic sorting effect. However, the ColClick event is still raised, so the script can respond with a custom sort or other action. To disable sorting for all columns rather than only a subset, include NoSort in the ListView's options.
248 |Sort: Immediately sorts the column in ascending order (even if it has the Desc option).
249 |SortDesc: Immediately sorts the column in descending order.
250 |Uni: Unidirectional sort. This prevents a second click on the same column from reversing the sort direction.
251 |Type: String
255 |If omitted, the current header is left unchanged. Otherwise, specify the new header of the column.
256 |Inserts a new column at the specified column number.
263 |ColumnNumber := LV.InsertCol(ColumnNumber, Options, ColumnTitle)264 |
Type: Integer
269 |If omitted or larger than the number of columns currently in the control, the new column is added next to the last column on the right side.
270 |Otherwise, specify the column number of the newly inserted column. Any column at or on the right side of ColumnNumber are shifted to the right to make room for the new column. The first column is 1 (not 0).
271 |Type: String
275 |If omitted, the column always starts off at its defaults, such as whether or not it uses integer sorting. Otherwise, specify one or more options from the list above.
276 |Type: String
280 |If blank or omitted, it defaults to an empty header. Otherwise, specify the header of the column.
281 |Type: Integer
285 |This method returns the new column's position number.
286 |The newly inserted column starts off with empty contents beneath it unless it is the first column, in which case it inherits the old first column's contents and the old first column acquires blank contents.
288 |The maximum number of columns in a ListView is 200.
289 |Deletes the specified column and all of the contents beneath it.
294 |LV.DeleteCol(ColumnNumber)
295 | Type: Integer
300 |The number of the column to delete. Once a column is deleted, the column numbers of any that lie to its right are reduced by 1. Consequently, calling LV.DeleteCol(2)
twice would delete the second and third columns.
Returns the number of rows or columns in the control.
308 |Count := LV.GetCount(Mode)309 |
Type: String
314 |If blank or omitted, the method returns the total number of rows in the control. Otherwise, specify one of the following strings:
315 |S or Selected: The count includes only the selected/highlighted rows.
316 |Col or Column: The method returns the number of columns in the control.
317 |Type: Integer
321 |This method returns the number of rows or columns in the control. The value is always returned immediately because the control keeps track of these counts.
322 |This method is often used in the top line of a Loop, in which case the method would get called only once (prior to the first iteration). For example:
324 |Loop LV.GetCount() 325 | { 326 | RetrievedText := LV.GetText(A_Index) 327 | if InStr(RetrievedText, "some filter text") 328 | LV.Modify(A_Index, "Select") ; Select each row whose first field contains the filter-text. 329 | }330 |
To retrieve the widths of a ListView's columns -- for uses such as saving them to an INI file to be remembered between sessions -- follow this example:
331 |Loop LV.GetCount("Column") 332 | { 333 | ColWidth := SendMessage(0x101D, A_Index - 1, 0, LV) ; 0x101D is LVM_GETCOLUMNWIDTH. 334 | MsgBox("Column " A_Index "'s width is " ColWidth ".") 335 | }336 |
Returns the row number of the next selected, checked, or focused row.
341 |RowNumber := LV.GetNext(StartingRowNumber, RowType)342 |
Type: Integer
347 |If omitted or less than 1, the search begins at the top of the list. Otherwise, specify the number of the row after which to begin the search.
348 |Type: String
352 |If blank or omitted, the method searches for the next selected/highlighted row (see the example below). Otherwise, specify one of the following strings:
353 |C or Checked: Find the next checked row.
354 |F or Focused: Find the focused row. There is never more than one focused row in the entire list, and sometimes there is none at all.
355 |Type: Integer
359 |This method returns the row number of the next selected, checked, or focused row. If none is found, it returns 0.
360 |The following example reports all selected rows in the ListView:
362 |RowNumber := 0 ; This causes the first loop iteration to start the search at the top of the list. 363 | Loop 364 | { 365 | RowNumber := LV.GetNext(RowNumber) ; Resume the search at the row after that found by the previous iteration. 366 | if not RowNumber ; The above returned zero, so there are no more selected rows. 367 | break 368 | Text := LV.GetText(RowNumber) 369 | MsgBox('The next selected row is #' RowNumber ', whose first field is "' Text '".') 370 | }371 |
An alternate method to find out if a particular row number is checked is the following:
372 |ItemState := SendMessage(0x102C, RowNumber - 1, 0xF000, LV) ; 0x102C is LVM_GETITEMSTATE. 0xF000 is LVIS_STATEIMAGEMASK. 373 | IsChecked := (ItemState >> 12) - 1 ; This sets IsChecked to true if RowNumber is checked or false otherwise.374 | 375 |
Retrieves the text at the specified row and column number.
379 |Text := LV.GetText(RowNumber , ColumnNumber)380 |
Type: Integer
384 |The number of the row whose text to be retrieved. If 0, the column header text is retrieved.
385 |Type: Integer
389 |If omitted, it defaults to 1 (the text in the first column). Otherwise, specify the number of the column where RowNumber is located.
390 |Type: String
394 |The method returns the retrieved text. Only up to 8191 characters are retrieved.
395 |Column numbers seen by the script are not altered by any dragging and dropping of columns the user may have done. For example, the original first column is still number 1 even if the user drags it to the right of other columns.
397 | 398 |Sets or replaces an ImageList for displaying icons.
402 |PrevImageListID := LV.SetImageList(ImageListID , IconType)403 |
Type: Integer
408 |The ID number returned from a previous call to IL_Create.
409 |Type: Integer
413 |If omitted, the type of icons in the ImageList is detected automatically as large or small. Otherwise, specify 0 for large icons, 1 for small icons, or 2 for state icons (which are not yet directly supported, but could be used via SendMessage).
414 |Type: Integer
418 |This method returns the ImageList ID that was previously associated with the ListView. On failure, it returns 0. Any such detached ImageList should normally be destroyed via IL_Destroy.
419 |This method is normally called prior to adding any rows to the ListView. It sets the ImageList whose icons will be displayed by the ListView's rows (and optionally, its columns).
421 |A ListView may have up to two ImageLists: small-icon and/or large-icon. This is useful when the script allows the user to switch to and from the large-icon view. To add more than one ImageList to a ListView, call the SetImageList method a second time, specifying the ImageList ID of the second list. A ListView with both a large-icon and small-icon ImageList should ensure that both lists contain the icons in the same order. This is because the same ID number is used to reference both the large and small versions of a particular icon.
422 |Although it is traditional for all viewing modes except Icon and Tile to show small icons, this can be overridden by passing a large-icon list to the SetImageList method and specifying 1 (small-icon) for the second parameter. This also increases the height of each row in the ListView to fit the large icon.
423 |The following events can be detected by calling OnEvent to register a callback function or method:
427 |Event | Raised when... |
---|---|
Click | The control is clicked. |
DoubleClick | The control is double-clicked. |
ColClick | A column header is clicked. |
ContextMenu | The user right-clicks the control or presses Menu or Shift+F10 while the control has the keyboard focus. |
Focus | The control gains the keyboard focus. |
LoseFocus | The control loses the keyboard focus. |
ItemCheck | An item is checked or unchecked. |
ItemEdit | An item's label is edited by the user. |
ItemFocus | The focused item changes. |
ItemSelect | An item is selected or deselected. |
Additional (rarely-used) notifications can be detected by using OnNotify. These notifications are documented at Microsoft Docs. Microsoft Docs does not show the numeric value of each notification code; those can be found in the Windows SDK or by searching the Internet.
441 | 442 |An Image-List is a group of identically sized icons stored in memory. Upon creation, each ImageList is empty. The script calls IL_Add repeatedly to add icons to the list, and each icon is assigned a sequential number starting at 1. This is the number to which the script refers to display a particular icon in a row or column header. Here is a working example that demonstrates how to put icons into a ListView's rows:
444 |MyGui := Gui() ; Create a Gui window. 445 | LV := MyGui.Add("ListView", "h200 w180", ["Icon & Number", "Description"]) ; Create a ListView. 446 | ImageListID := IL_Create(10) ; Create an ImageList to hold 10 small icons. 447 | LV.SetImageList(ImageListID) ; Assign the above ImageList to the current ListView. 448 | Loop 10 ; Load the ImageList with a series of icons from the DLL. 449 | IL_Add(ImageListID, "shell32.dll", A_Index) 450 | Loop 10 ; Add rows to the ListView (for demonstration purposes, one for each icon). 451 | LV.Add("Icon" . A_Index, A_Index, "n/a") 452 | MyGui.Show()453 | 454 |
Creates a new ImageList that is initially empty.
456 |ImageListID := IL_Create(InitialCount, GrowCount, LargeIcons)457 |
Type: Integer
462 |If omitted, it defaults to 2. Otherwise, specify the number of icons you expect to put into the list immediately.
463 |Type: Integer
467 |If omitted, it defaults to 5. Otherwise, specify the number of icons by which the list will grow each time it exceeds the current list capacity.
468 |Type: Boolean
472 |If omitted, it defaults to false.
473 |If false, the ImageList will contain small icons.
474 |If true, the ImageList will contain large icons.
475 |Icons added to the list are scaled automatically to conform to the system's dimensions for small and large icons.
476 |Type: Integer
480 |On success, this function returns the unique ID of the newly created ImageList. On failure, it returns 0.
481 | 482 |Adds an icon or picture to the specified ImageList.
484 |IconIndex := IL_Add(ImageListID, IconFileName , IconNumber) 485 | IconIndex := IL_Add(ImageListID, PicFileName, MaskColor, Resize)486 |
Type: Integer
491 |The ID number returned from a previous call to IL_Create.
492 |Type: String
496 |The name of an icon (.ICO), cursor (.CUR), or animated cursor (.ANI) file (animated cursors will not actually be animated when displayed in a ListView), or an icon handle such as "HICON:" handle
. Other sources of icons include the following types of files: EXE, DLL, CPL, SCR, and other types that contain icon resources.
Type: Integer
501 |If omitted, it defaults to 1 (the first icon group). Otherwise, specify the number of the icon group to be used in the file. If the number is negative, its absolute value is assumed to be the resource ID of an icon within an executable file. In the following example, the default icon from the second icon group would be used: IL_Add(ImageListID, "C:\My Application.exe", 2)
.
Type: String
506 |The name of a non-icon image such as BMP, GIF, JPG, PNG, TIF, Exif, WMF, and EMF, or a bitmap handle such as "HBITMAP:" handle
.
Type: Integer
511 |The mask/transparency color number. 0xFFFFFF (the color white) might be best for most pictures.
512 |Type: Boolean
516 |If true, the picture is scaled to become a single icon.
517 |If false, the picture is divided up into however many icons can fit into its actual width.
518 |Type: Integer
522 |On success, this function returns the new icon's index (1 is the first icon, 2 is the second, and so on). On failure, it returns 0.
523 | 524 |Deletes the specified ImageList.
526 |IsDestroyed := IL_Destroy(ImageListID)
527 | Type: Integer
532 |The ID number returned from a previous call to IL_Create.
533 |Type: Integer (boolean)
537 |On success, this function returns 1 (true). On failure, it returns 0 (false).
538 |It is normally not necessary to destroy ImageLists because once attached to a ListView, they are destroyed automatically when the ListView or its parent window is destroyed. However, if the ListView shares ImageLists with other ListViews (by having 0x40 in its options), the script should explicitly destroy the ImageList after destroying all the ListViews that use it. Similarly, if the script replaces one of a ListView's old ImageLists with a new one, it should explicitly destroy the old one.
540 | 541 |Gui.Submit has no effect on a ListView control.
543 |After a column is sorted -- either by means of the user clicking its header or the script calling LV.ModifyCol(1, "Sort")
-- any subsequently added rows will appear at the bottom of the list rather than obeying the sort order. The exception to this is the Sort and SortDesc styles, which move newly added rows into the correct positions.
To detect when the user has pressed Enter while a ListView has focus, use a default button (which can be hidden if desired). For example:
545 |MyGui.Add("Button", "Hidden Default", "OK").OnEvent("Click", LV_Enter) 546 | ... 547 | LV_Enter(*) { 548 | global 549 | if MyGui.FocusedCtrl != LV 550 | return 551 | MsgBox("Enter was pressed. The focused row number is " LV.GetNext(0, "Focused")) 552 | }553 |
In addition to navigating from row to row with the keyboard, the user may also perform incremental search by typing the first few characters of an item in the first column. This causes the selection to jump to the nearest matching row.
554 |Although any length of text can be stored in each field of a ListView, only the first 260 characters are displayed.
555 |Although the maximum number of rows in a ListView is limited only by available system memory, row-adding performance can be greatly improved as described in the Count option.
556 |A picture may be used as a background around a ListView (that is, to frame the ListView). To do this, create the picture control after the ListView and include 0x4000000 (which is WS_CLIPSIBLINGS) in the picture's Options.
557 |A script may create more than one ListView per window.
558 |It is best not to insert or delete columns directly with SendMessage. This is because the program maintains a collection of sorting preferences for each column, which would then get out of sync. Instead, use the built-in column methods.
559 |To perform actions such as resizing, hiding, or changing the font of a ListView, see GuiControl object.
560 |To extract text from external ListViews (those not owned by the script), use ListViewGetContent.
561 |TreeView, Other Control Types, Gui(), ContextMenu event, Gui object, GuiControl object, ListView styles table
563 |Selects or de-selects all rows by specifying 0 as the row number.
567 |LV.Modify(0, "Select") ; Select all. 568 | LV.Modify(0, "-Select") ; De-select all. 569 | LV.Modify(0, "-Check") ; Uncheck all the checkboxes.570 |
Auto-sizes all columns to fit their contents.
574 |LV.ModifyCol ; There are no parameters in this mode.575 |
The following is a working script that is more elaborate than the one near the top of this page. It displays the files in a folder chosen by the user, with each file assigned the icon associated with its type. The user can double-click a file, or right-click one or more files to display a context menu.
579 |; Create a GUI window: 580 | MyGui := Gui("+Resize") ; Allow the user to maximize or drag-resize the window. 581 | 582 | ; Create some buttons: 583 | B1 := MyGui.Add("Button", "Default", "Load a folder") 584 | B2 := MyGui.Add("Button", "x+20", "Clear List") 585 | B3 := MyGui.Add("Button", "x+20", "Switch View") 586 | 587 | ; Create the ListView and its columns via Gui.Add: 588 | LV := MyGui.Add("ListView", "xm r20 w700", ["Name", "In Folder", "Size (KB)", "Type"]) 589 | LV.ModifyCol(3, "Integer") ; For sorting, indicate that the Size column is an integer. 590 | 591 | ; Create an ImageList so that the ListView can display some icons: 592 | ImageListID1 := IL_Create(10) 593 | ImageListID2 := IL_Create(10, 10, true) ; A list of large icons to go with the small ones. 594 | 595 | ; Attach the ImageLists to the ListView so that it can later display the icons: 596 | LV.SetImageList(ImageListID1) 597 | LV.SetImageList(ImageListID2) 598 | 599 | ; Apply control events: 600 | LV.OnEvent("DoubleClick", RunFile) 601 | LV.OnEvent("ContextMenu", ShowContextMenu) 602 | B1.OnEvent("Click", LoadFolder) 603 | B2.OnEvent("Click", (*) => LV.Delete()) 604 | B3.OnEvent("Click", SwitchView) 605 | 606 | ; Apply window events: 607 | MyGui.OnEvent("Size", Gui_Size) 608 | 609 | ; Create a popup menu to be used as the context menu: 610 | ContextMenu := Menu() 611 | ContextMenu.Add("Open", ContextOpenOrProperties) 612 | ContextMenu.Add("Properties", ContextOpenOrProperties) 613 | ContextMenu.Add("Clear from ListView", ContextClearRows) 614 | ContextMenu.Default := "Open" ; Make "Open" a bold font to indicate that double-click does the same thing. 615 | 616 | ; Display the window: 617 | MyGui.Show() 618 | 619 | LoadFolder(*) 620 | { 621 | static IconMap := Map() 622 | MyGui.Opt("+OwnDialogs") ; Forces user to dismiss the following dialog before using main window. 623 | Folder := DirSelect(, 3, "Select a folder to read:") 624 | if not Folder ; The user canceled the dialog. 625 | return 626 | 627 | ; Check if the last character of the folder name is a backslash, which happens for root 628 | ; directories such as C:\. If it is, remove it to prevent a double-backslash later on. 629 | if SubStr(Folder, -1, 1) = "\" 630 | Folder := SubStr(Folder, 1, -1) ; Remove the trailing backslash. 631 | 632 | ; Calculate buffer size required for SHFILEINFO structure. 633 | sfi_size := A_PtrSize + 688 634 | sfi := Buffer(sfi_size) 635 | 636 | ; Gather a list of file names from the selected folder and append them to the ListView: 637 | LV.Opt("-Redraw") ; Improve performance by disabling redrawing during load. 638 | Loop Files, Folder "\*.*" 639 | { 640 | FileName := A_LoopFilePath ; Must save it to a writable variable for use below. 641 | 642 | ; Build a unique extension ID to avoid characters that are illegal in variable names, 643 | ; such as dashes. This unique ID method also performs better because finding an item 644 | ; in the array does not require search-loop. 645 | SplitPath(FileName,,, &FileExt) ; Get the file's extension. 646 | if FileExt ~= "i)\A(EXE|ICO|ANI|CUR)\z" 647 | { 648 | ExtID := FileExt ; Special ID as a placeholder. 649 | IconNumber := 0 ; Flag it as not found so that these types can each have a unique icon. 650 | } 651 | else ; Some other extension/file-type, so calculate its unique ID. 652 | { 653 | ExtID := 0 ; Initialize to handle extensions that are shorter than others. 654 | Loop 7 ; Limit the extension to 7 characters so that it fits in a 64-bit value. 655 | { 656 | ExtChar := SubStr(FileExt, A_Index, 1) 657 | if not ExtChar ; No more characters. 658 | break 659 | ; Derive a Unique ID by assigning a different bit position to each character: 660 | ExtID := ExtID | (Ord(ExtChar) << (8 * (A_Index - 1))) 661 | } 662 | ; Check if this file extension already has an icon in the ImageLists. If it does, 663 | ; several calls can be avoided and loading performance is greatly improved, 664 | ; especially for a folder containing hundreds of files: 665 | IconNumber := IconMap.Has(ExtID) ? IconMap[ExtID] : 0 666 | } 667 | if not IconNumber ; There is not yet any icon for this extension, so load it. 668 | { 669 | ; Get the high-quality small-icon associated with this file extension: 670 | if not DllCall("Shell32\SHGetFileInfoW", "Str", FileName 671 | , "Uint", 0, "Ptr", sfi, "UInt", sfi_size, "UInt", 0x101) ; 0x101 is SHGFI_ICON+SHGFI_SMALLICON 672 | IconNumber := 9999999 ; Set it out of bounds to display a blank icon. 673 | else ; Icon successfully loaded. 674 | { 675 | ; Extract the hIcon member from the structure: 676 | hIcon := NumGet(sfi, 0, "Ptr") 677 | ; Add the HICON directly to the small-icon and large-icon lists. 678 | ; Below uses +1 to convert the returned index from zero-based to one-based: 679 | IconNumber := DllCall("ImageList_ReplaceIcon", "Ptr", ImageListID1, "Int", -1, "Ptr", hIcon) + 1 680 | DllCall("ImageList_ReplaceIcon", "Ptr", ImageListID2, "Int", -1, "Ptr", hIcon) 681 | ; Now that it's been copied into the ImageLists, the original should be destroyed: 682 | DllCall("DestroyIcon", "Ptr", hIcon) 683 | ; Cache the icon to save memory and improve loading performance: 684 | IconMap[ExtID] := IconNumber 685 | } 686 | } 687 | 688 | ; Create the new row in the ListView and assign it the icon number determined above: 689 | LV.Add("Icon" . IconNumber, A_LoopFileName, A_LoopFileDir, A_LoopFileSizeKB, FileExt) 690 | } 691 | LV.Opt("+Redraw") ; Re-enable redrawing (it was disabled above). 692 | LV.ModifyCol() ; Auto-size each column to fit its contents. 693 | LV.ModifyCol(3, 60) ; Make the Size column at little wider to reveal its header. 694 | } 695 | 696 | SwitchView(*) 697 | { 698 | static IconView := false 699 | if not IconView 700 | LV.Opt("+Icon") ; Switch to icon view. 701 | else 702 | LV.Opt("+Report") ; Switch back to details view. 703 | IconView := not IconView ; Invert in preparation for next time. 704 | } 705 | 706 | RunFile(LV, RowNumber) 707 | { 708 | FileName := LV.GetText(RowNumber, 1) ; Get the text of the first field. 709 | FileDir := LV.GetText(RowNumber, 2) ; Get the text of the second field. 710 | try 711 | Run(FileDir "\" FileName) 712 | catch 713 | MsgBox("Could not open " FileDir "\" FileName ".") 714 | } 715 | 716 | ShowContextMenu(LV, Item, IsRightClick, X, Y) ; In response to right-click or Apps key. 717 | { 718 | ; Show the menu at the provided coordinates, X and Y. These should be used 719 | ; because they provide correct coordinates even if the user pressed the Apps key: 720 | ContextMenu.Show(X, Y) 721 | } 722 | 723 | ContextOpenOrProperties(ItemName, *) ; The user selected "Open" or "Properties" in the context menu. 724 | { 725 | ; For simplicitly, operate upon only the focused row rather than all selected rows: 726 | FocusedRowNumber := LV.GetNext(0, "F") ; Find the focused row. 727 | if not FocusedRowNumber ; No row is focused. 728 | return 729 | FileName := LV.GetText(FocusedRowNumber, 1) ; Get the text of the first field. 730 | FileDir := LV.GetText(FocusedRowNumber, 2) ; Get the text of the second field. 731 | try 732 | { 733 | if (ItemName = "Open") ; User selected "Open" from the context menu. 734 | Run(FileDir "\" FileName) 735 | else 736 | Run("properties " FileDir "\" FileName) 737 | } 738 | catch 739 | MsgBox("Could not perform requested action on " FileDir "\" FileName ".") 740 | } 741 | 742 | ContextClearRows(*) ; The user selected "Clear" in the context menu. 743 | { 744 | RowNumber := 0 ; This causes the first iteration to start the search at the top. 745 | Loop 746 | { 747 | ; Since deleting a row reduces the RowNumber of all other rows beneath it, 748 | ; subtract 1 so that the search includes the same row number that was previously 749 | ; found (in case adjacent rows are selected): 750 | RowNumber := LV.GetNext(RowNumber - 1) 751 | if not RowNumber ; The above returned zero, so there are no more selected rows. 752 | break 753 | LV.Delete(RowNumber) ; Clear the row from the ListView. 754 | } 755 | } 756 | 757 | Gui_Size(thisGui, MinMax, Width, Height) ; Expand/Shrink ListView in response to the user's resizing. 758 | { 759 | if MinMax = -1 ; The window has been minimized. No action needed. 760 | return 761 | ; Otherwise, the window has been resized or maximized. Resize the ListView to match. 762 | LV.Move(,, Width - 20, Height - 40) 763 | }764 | 765 |
Returns a list of items/rows from a ListView.
17 | 18 |List := ListViewGetContent(Options, Control, WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String
25 |Specifices what to retrieve. If blank or omitted, all the text in the ListView is retrieved. Otherwise, specify zero or more of the following words, each separated from the next with a space or tab:
26 |Selected: Returns only the selected (highlighted) rows rather than all rows. If none, the return value is blank.
27 |Focused: Returns only the focused row. If none, the return value is blank.
28 |ColN: Returns only the Nth column (field) rather than all columns. Replace N with a number of your choice. For example, Col4 returns the fourth column.
29 |Count: Returns a single number that is the total number of rows in the ListView.
30 |Count Selected: Returns the number of selected (highlighted) rows.
31 |Count Focused: Returns the row number (position) of the focused row (0 if none).
32 |Count Col: Returns the number of columns in the control (or -1 if the count cannot be determined).
33 |Type: String, Integer or Object
37 |The control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
Type: String, Integer or Object
42 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
43 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
44 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
45 |Type: String
50 |This function returns a list of items/rows. Within each row, each field (column) except the last will end with a tab character (`t). To access the items/rows individually, use a parsing loop as in example #1.
51 | 52 |A TargetError is thrown if the window or control could not be found.
54 |An OSError is thrown if a message could not be sent to the control, or if the process owning the ListView could not be opened, perhaps due to a lack of user permissions or because it is locked.
55 |A ValueError is thrown if the ColN option specifies a nonexistent column.
56 | 57 |Some applications store their ListView text privately, which prevents their text from being retrieved. In these cases, an exception will usually not be thrown, but all the retrieved fields will be empty.
59 |The columns in a ListView can be resized via SendMessage as shown in this example:
60 |SendMessage(0x101E, 0, 80, "SysListView321", WinTitle) ; 0x101E is the message LVM_SETCOLUMNWIDTH.61 |
In the above, 0 indicates the first column (specify 1 for the second, 2 for the third, etc.) Also, 80 is the new width. Replace 80 with -1 to autosize the column. Replace it with -2 to do the same but also take into account the header text width.
62 | 63 |ControlGetItems, WinGetList, Control functions
65 | 66 |Extracts the individual rows and fields out of a ListView.
69 |List := ListViewGetContent("Selected", "SysListView321", WinTitle) 70 | Loop Parse, List, "`n" ; Rows are delimited by linefeeds (`n). 71 | { 72 | RowNumber := A_Index 73 | Loop Parse, A_LoopField, A_Tab ; Fields (columns) in each row are delimited by tabs (A_Tab). 74 | MsgBox "Row #" RowNumber " Col #" A_Index " is " A_LoopField 75 | }76 |
Loads a picture from file and returns a bitmap or icon handle.
16 |Handle := LoadPicture(Filename , Options, &OutImageType)17 | 18 |
Type: String
24 |The filename of the picture, which is usually assumed to be in A_WorkingDir if an absolute path isn't specified. If the name of a DLL or EXE file is given without a path, it may be loaded from the directory of the current executable (AutoHotkey.exe or a compiled script) or a system directory.
25 |Type: String
30 |If blank or omitted, it defaults to no options. Otherwise, specify a string of one or more of the following options, each separated from the next with a space or tab:
31 |Wn and Hn: The width and height to load the image at, where n is an integer. If one dimension is omitted or -1, it is calculated automatically based on the other dimension, preserving aspect ratio. If both are omitted, the image's original size is used. If either dimension is 0, the original size is used for that dimension. For example: "w80 h50"
, "w48 h-1"
or "w48"
(preserve aspect ratio), "h0 w100"
(use original height but override width).
Iconn: Indicates which icon to load from a file with multiple icons (generally an EXE or DLL file). For example, "Icon2"
loads the file's second icon. If negative, the absolute value is assumed to be the resource ID of an icon within an executable file. Any supported image format can be converted to an icon by specifying "Icon1"
. However, the icon is converted back to a bitmap if the OutImageType parameter is omitted.
GDI+: Use GDI+ to load the image, if available. For example, "GDI+ w100"
.
Type: VarRef
39 |If omitted, the corresponding value will not be stored, and the return value will always be a bitmap handle (icons/cursors are converted if necessary) because reliably using or deleting an icon/cursor/bitmap handle requires knowing which type it is. Otherwise, specify a reference to the output variable in which to store a number indicating the type of handle being returned: 0 (IMAGE_BITMAP), 1 (IMAGE_ICON) or 2 (IMAGE_CURSOR).
40 |Type: Integer
46 |This function returns a bitmap or icon handle depending on whether a picture or icon is specified and whether the &OutImageType parameter is present or not. If there are any errors, the function returns 0.
47 | 48 |LoadPicture also supports the handle syntax, such as for creating a resized image based on an icon or bitmap which has already been loaded into memory, or converting an icon to a bitmap by omitting &OutImageType.
50 |If the image needs to be freed from memory, call whichever function is appropriate for the type of handle.
51 |if (not OutImageType) ; IMAGE_BITMAP (0) or the OutImageType parameter was omitted. 52 | DllCall("DeleteObject", "ptr", Handle) 53 | else if (OutImageType = 1) ; IMAGE_ICON 54 | DllCall("DestroyIcon", "ptr", Handle) 55 | else if (OutImageType = 2) ; IMAGE_CURSOR 56 | DllCall("DestroyCursor", "ptr", Handle)57 | 58 |
Pre-loads and reuses some images.
64 |Pics := [] 65 | ; Find some pictures to display. 66 | Loop Files, A_WinDir "\Web\Wallpaper\*.jpg", "R" 67 | { 68 | ; Load each picture and add it to the array. 69 | Pics.Push(LoadPicture(A_LoopFileFullPath)) 70 | } 71 | if !Pics.Length 72 | { 73 | ; If this happens, edit the path on the Loop line above. 74 | MsgBox("No pictures found! Try a different directory.") 75 | ExitApp 76 | } 77 | ; Add the picture control, preserving the aspect ratio of the first picture. 78 | MyGui := Gui() 79 | Pic := MyGui.Add("Pic", "w600 h-1 +Border", "HBITMAP:*" Pics[1]) 80 | MyGui.OnEvent("Escape", (*) => ExitApp()) 81 | MyGui.OnEvent("Close", (*) => ExitApp()) 82 | MyGui.Show() 83 | Loop 84 | { 85 | ; Switch pictures! 86 | Pic.Value := "HBITMAP:*" Pics[Mod(A_Index, Pics.Length)+1] 87 | Sleep 3000 88 | }89 |
Performs one or more statements repeatedly: either the specified number of times or until Break is encountered.
16 | 17 |Loop Count18 |
Type: Integer
24 |If omitted, the loop continues indefinitely until a Break or Return is encountered. Otherwise, specify how many times (iterations) to perform the loop. However, an explicit blank value or number less than 1 causes the loop to be skipped entirely.
25 |Count is evaluated only once, right before the loop begins. For instance, if Count is an expression with side-effects such as function calls or assignments, the side-effects occur only once.
26 |If Count is enclosed in parentheses, a space or tab is not required. For example: Loop(2)
The loop statement is usually followed by a block, which is a collection of statements that form the body of the loop. However, a loop with only a single statement does not require a block (an "if" and its "else" count as a single statement for this purpose).
33 |A common use of this statement is an infinite loop that uses the Break statement somewhere in the loop's body to determine when to stop the loop.
34 |The use of Break and Continue inside a loop are encouraged as alternatives to Goto, since they generally make a script more understandable and maintainable. One can also create a "While" or "Do...While/Until" loop by making the first or last statement of the loop's body an IF statement that conditionally issues the Break statement, but the use of While or Loop...Until is usually preferred.
35 |The built-in variable A_Index contains the number of the current loop iteration. It contains 1 the first time the loop's body is executed. For the second time, it contains 2; and so on. If an inner loop is enclosed by an outer loop, the inner loop takes precedence. A_Index works inside all types of loops, including file loops and registry loops; but A_Index contains 0 outside of a loop.
36 |A_Index can be assigned any integer value by the script. If Count is specified, changing A_Index affects the number of iterations that will be performed. For example, A_Index := 3
would make the loop statement act as though it is on the third iteration (A_Index will be 4 on the next iteration), while A_Index--
would prevent the current iteration from being counted toward the total.
The loop may optionally be followed by an Else statement, which is executed if Count is zero.
38 |The One True Brace (OTB) style may optionally be used. For example:
39 |Loop { 40 | ... 41 | } 42 | Loop RepeatCount { 43 | ... 44 | }45 |
Specialized loops: Loops can be used to automatically retrieve files, folders, or registry items (one at a time). See file loop and registry loop for details. In addition, file-reading loops can operate on the entire contents of a file, one line at a time. Finally, parsing loops can operate on the individual fields contained inside a delimited string.
46 | 47 |Until, While-loop, For-loop, Files-and-folders loop, Registry loop, File-reading loop, Parsing loop, Break, Continue, Blocks, Else
49 | 50 |Creates a loop with 3 iterations.
53 |Loop 3 54 | { 55 | MsgBox "Iteration number is " A_Index ; A_Index will be 1, 2, then 3 56 | Sleep 100 57 | }58 |
Creates an infinite loop, but it will be terminated after the 25th iteration.
62 |Loop 63 | { 64 | if (A_Index > 25) 65 | break ; Terminate the loop 66 | if (A_Index < 20) 67 | continue ; Skip the below and start a new iteration 68 | MsgBox "A_Index = " A_Index ; This will display only the numbers 20 through 25 69 | }70 |
Retrieves the specified files or folders, one at a time.
16 | 17 |Loop Files FilePattern , Mode18 | 19 |
Type: String
25 |The name of a single file or folder, or a wildcard pattern such as "C:\Temp\*.tmp"
. FilePattern is assumed to be in A_WorkingDir if an absolute path isn't specified.
Both asterisks (*
) and question marks (?
) are supported as wildcards. *
matches zero or more characters and ?
matches any single character. Usage examples:
*.*
or *
matches all files.*.htm
matches files with the extension .htm, .html, etc.*.
matches files without an extension.log?.txt
matches e.g. log1.txt but not log10.txt.*report*
matches any filename containing the word "report".A match occurs when the pattern appears in either the file's long/normal name or its 8.3 short name.
35 |If this parameter is a single file or folder (i.e. no wildcards) and Mode includes R, more than one match will be found if the specified file name appears in more than one of the folders being searched.
36 |Patterns longer than 259 characters may fail to find any files due to system limitations (MAX_PATH). This limit can be bypassed by using the \\?\
long path prefix, with some stipulations.
Type: String
42 |If blank or omitted, only files are included and subdirectories are not recursed into. Otherwise, specify one or more of the following letters:
43 |The following variables exist within any file loop. If an inner file loop is enclosed by an outer file loop, the innermost loop's file will take precedence:
54 |Variable | 57 |Description | 58 |
---|---|
A_LoopFileName | 61 |The name of the file or folder currently retrieved (without the path). | 62 |
A_LoopFileExt | 65 |The file's extension (e.g. TXT, DOC, or EXE). The period (.) is not included. | 66 |
A_LoopFilePath | 69 |The path and name of the file/folder currently retrieved. If FilePattern contains a relative path rather than an absolute path, the path here will also be relative. In addition, any short (8.3) folder names in FilePattern will still be short (see next item to get the long version). | 70 |
A_LoopFileFullPath | 73 |This is different than A_LoopFilePath in the following ways: 1) It always contains the absolute/complete path of the file even if FilePattern contains a relative path; 2) Any short (8.3) folder names in FilePattern itself are converted to their long names; 3) Characters in FilePattern are converted to uppercase or lowercase to match the case stored in the file system. This is useful for converting file names -- such as those passed into a script as command line parameters -- to their exact path names as shown by Explorer. | 74 |
A_LoopFileShortPath | 77 |The 8.3 short path and name of the file/folder currently retrieved. For example: C:\MYDOCU~1\ADDRES~1.txt. If FilePattern contains a relative path rather than an absolute path, the path here will also be relative. 78 |To retrieve the complete 8.3 path and name for a single file or folder, follow this example: 79 |Loop Files, "C:\My Documents\Address List.txt" 80 | ShortPathName := A_LoopFileShortPath81 | Note: This variable will be blank if the file does not have a short name, which can happen on systems where NtfsDisable8dot3NameCreation has been set in the registry. It will also be blank if FilePattern contains a relative path and the body of the loop uses SetWorkingDir to switch away from the working directory in effect for the loop itself. |
82 |
A_LoopFileShortName | 85 |The 8.3 short name or alternate name of the file. If the file doesn't have one (due to the long name being shorter than 8.3 or perhaps because short-name generation is disabled on an NTFS file system), A_LoopFileName will be retrieved instead. | 86 |
A_LoopFileDir | 89 |The path of the directory in which A_LoopFileName resides. If FilePattern contains a relative path rather than an absolute path, the path here will also be relative. A root directory will not contain a trailing backslash. For example: C: | 90 |
A_LoopFileTimeModified | 93 |The time the file was last modified. Format YYYYMMDDHH24MISS. | 94 |
A_LoopFileTimeCreated | 97 |The time the file was created. Format YYYYMMDDHH24MISS. | 98 |
A_LoopFileTimeAccessed | 101 |The time the file was last accessed. Format YYYYMMDDHH24MISS. | 102 |
A_LoopFileAttrib | 105 |The attributes of the file currently retrieved. | 106 |
A_LoopFileSize | 109 |The size in bytes of the file currently retrieved. Files larger than 4 gigabytes are also supported. | 110 |
A_LoopFileSizeKB | 113 |The size in Kbytes of the file currently retrieved, rounded down to the nearest integer. | 114 |
A_LoopFileSizeMB | 117 |The size in Mbytes of the file currently retrieved, rounded down to the nearest integer. | 118 |
A file loop is useful when you want to operate on a collection of files and/or folders, one at a time.
123 |All matching files are retrieved, including hidden files. By contrast, OS features such as the DIR command omit hidden files by default. To avoid processing hidden, system, and/or read-only files, use something like the following inside the loop:
124 |if A_LoopFileAttrib ~= "[HRS]" ; Skip any file that is either H (Hidden), R (Read-only), or S (System). See ~= operator. 125 | continue ; Skip this file and move on to the next one.126 |
To retrieve files' relative paths instead of absolute paths during a recursive search, use SetWorkingDir to change to the base folder prior to the loop, and then omit the path from the loop (e.g. Loop Files, "*.*", "R"
). That will cause A_LoopFilePath to contain the file's path relative to the base folder.
A file loop can disrupt itself if it creates or renames files or folders within its own purview. For example, if it renames files via FileMove or other means, each such file might be found twice: once as its old name and again as its new name. To work around this, rename the files only after creating a list of them. For example:
128 |FileList := "" 129 | Loop Files, "*.jpg" 130 | FileList .= A_LoopFileName "`n" 131 | Loop Parse, FileList, "`n" 132 | FileMove A_LoopField, "renamed_" A_LoopField133 |
Files in an NTFS file system are probably always retrieved in alphabetical order. Files in other file systems are retrieved in no particular order. To ensure a particular ordering, use the Sort function as shown in the Examples section below.
134 |File patterns longer than 259 characters are supported only when at least one of the following is true:
135 |\\?\
long path prefix is used (caveats apply).In all other cases, file patterns longer than 259 characters will not find any files or folders. This limit applies both to FilePattern and any temporary pattern used during recursion into a subfolder.
140 |The One True Brace (OTB) style may optionally be used, which allows the open-brace to appear on the same line rather than underneath. For example: Loop Files "*.txt", "R" {
.
See Loop for information about Blocks, Break, Continue, and the A_Index variable (which exists in every type of loop).
142 |The loop may optionally be followed by an Else statement, which is executed if no matching files or directories were found (i.e. the loop had zero iterations).
143 |The functions FileGetAttrib, FileGetSize, FileGetTime, FileGetVersion, FileSetAttrib, and FileSetTime can be used in a file loop without their Filename/FilePattern parameter.
144 | 145 |Loop, Break, Continue, Blocks, SplitPath, FileSetAttrib, FileSetTime
147 | 148 |Reports the full path of each text file located in a directory and in its subdirectories.
151 |Loop Files, A_ProgramFiles "\*.txt", "R" ; Recurse into subfolders. 152 | { 153 | Result := MsgBox("Filename = " A_LoopFilePath "`n`nContinue?",, "y/n") 154 | if Result = "No" 155 | break 156 | }157 |
Calculates the size of a folder, including the files in all its subfolders.
161 |FolderSizeKB := 0 162 | WhichFolder := DirSelect() ; Ask the user to pick a folder. 163 | Loop Files, WhichFolder "\*.*", "R" 164 | FolderSizeKB += A_LoopFileSizeKB 165 | MsgBox "Size of " WhichFolder " is " FolderSizeKB " KB."166 |
Retrieves file names sorted by name (see next example to sort by date).
170 |FileList := "" ; Initialize to be blank. 171 | Loop Files, "C:\*.*" 172 | FileList .= A_LoopFileName "`n" 173 | FileList := Sort(FileList, "R") ; The R option sorts in reverse order. See Sort for other options. 174 | Loop Parse, FileList, "`n" 175 | { 176 | if A_LoopField = "" ; Ignore the blank item at the end of the list. 177 | continue 178 | Result := MsgBox("File number " A_Index " is " A_LoopField ". Continue?",, "y/n") 179 | if Result = "No" 180 | break 181 | }182 |
Retrieves file names sorted by modification date.
186 |FileList := "" 187 | Loop Files, A_MyDocuments "\Photos\*.*", "FD" ; Include Files and Directories 188 | FileList .= A_LoopFileTimeModified "`t" A_LoopFileName "`n" 189 | FileList := Sort(FileList) ; Sort by date. 190 | Loop Parse, FileList, "`n" 191 | { 192 | if A_LoopField = "" ; Omit the last linefeed (blank item) at the end of the list. 193 | continue 194 | FileItem := StrSplit(A_LoopField, A_Tab) ; Split into two parts at the tab char. 195 | Result := MsgBox("The next file (modified at " FileItem[1] ") is:`n" FileItem[2] "`n`nContinue?",, "y/n") 196 | if Result = "No" 197 | break 198 | }199 |
Copies only the source files that are newer than their counterparts in the destination. Call this function with a source pattern like "A:\Scripts\*.ahk" and an existing destination directory like "B:\Script Backup".
203 |CopyIfNewer(SourcePattern, Dest) 204 | { 205 | Loop Files, SourcePattern 206 | { 207 | copy_it := false 208 | if !FileExist(Dest "\" A_LoopFileName) ; Always copy if target file doesn't yet exist. 209 | copy_it := true 210 | else 211 | { 212 | time := FileGetTime(Dest "\" A_LoopFileName) 213 | time := DateDiff(time, A_LoopFileTimeModified, "Seconds") ; Subtract the source file's time from the destination's. 214 | if time < 0 ; Source file is newer than destination file. 215 | copy_it := true 216 | } 217 | if copy_it 218 | { 219 | try 220 | FileCopy A_LoopFilePath, Dest "\" A_LoopFileName, 1 ; Copy with overwrite=yes 221 | catch 222 | MsgBox 'Could not copy "' A_LoopFilePath '" to "' Dest '\' A_LoopFileName '".' 223 | } 224 | } 225 | }226 |
Converts filenames passed in via command-line parameters to long names, complete path, and correct uppercase/lowercase characters as stored in the file system.
230 |for GivenPath in A_Args ; For each parameter (or file dropped onto a script): 231 | { 232 | Loop Files, GivenPath, "FD" ; Include files and directories. 233 | LongPath := A_LoopFilePath 234 | MsgBox "The case-corrected long path name of file`n" GivenPath "`nis:`n" LongPath 235 | }236 |
Retrieves substrings (fields) from a string, one at a time.
16 | 17 |Loop Parse String , DelimiterChars, OmitChars18 |
Type: String
24 |The string to analyze.
25 |Type: String
30 |If blank or omitted, each character of the input string will be treated as a separate substring.
31 |If this parameter is "CSV"
, the string will be parsed in standard comma separated value format. Here is an example of a CSV line produced by MS Excel:
"first field",SecondField,"the word ""special"" is quoted literally",,"last field, has literal comma"33 |
Otherwise, specify one or more characters (case-sensitive), each of which is used to determine where the boundaries between substrings occur.
34 |Delimiter characters are not considered to be part of the substrings themselves. In addition, if there is nothing between a pair of delimiter characters within the input string, the corresponding substring will be empty.
35 |For example: ','
(a comma) would divide the string based on every occurrence of a comma. Similarly, A_Space A_Tab
would start a new substring every time a space or tab is encountered in the input string.
To use a string as a delimiter rather than a character, first use StrReplace to replace all occurrences of the string with a single character that is never used literally in the text, e.g. one of these special characters: ¢¤¥¦§©ª«®µ¶
. Consider this example, which uses the string <br> as a delimiter:
NewHTML := StrReplace(HTMLString, "<br>", "¢") 38 | Loop Parse, NewHTML, "¢" ; Parse the string based on the cent symbol. 39 | { 40 | ; ... 41 | }42 |
Type: String
47 |If blank or omitted, no characters will be excluded. Otherwise, specify a list of characters (case-sensitive) to exclude from the beginning and end of each substring. For example, if OmitChars is A_Space A_Tab
, spaces and tabs will be removed from the beginning and end (but not the middle) of every retrieved substring.
If DelimiterChars is blank, OmitChars indicates which characters should be excluded from consideration (the loop will not see them).
49 |A string parsing loop is useful when you want to operate on each field contained in a string, one at a time. Parsing loops use less memory than StrSplit (though either way the memory use is temporary) and in most cases they are easier to use.
55 |The built-in variable A_LoopField exists within any parsing loop. It contains the contents of the current substring (field). If an inner parsing loop is enclosed by an outer parsing loop, the innermost loop's field will take precedence.
56 |Although there is no built-in variable "A_LoopDelimiter", the example at the very bottom of this page demonstrates how to detect which delimiter character was encountered for each field.
57 |There is no restriction on the size of the input string or its fields.
58 |To arrange the fields in a different order prior to parsing, use the Sort function.
59 |See Loop for information about Blocks, Break, Continue, and the A_Index variable (which exists in every type of loop).
60 |The loop may optionally be followed by an Else statement, which is executed if the loop had zero iterations. Note that the loop always has at least one iteration unless String is empty or DelimiterChars is omitted and all characters in String are included in OmitChars.
61 | 62 |StrSplit, file-reading loop, Loop, Break, Continue, Blocks, Sort, FileSetAttrib, FileSetTime
64 | 65 |Parses a comma-separated string.
68 |Colors := "red,green,blue" 69 | Loop parse, Colors, "," 70 | { 71 | MsgBox "Color number " A_Index " is " A_LoopField 72 | }73 |
Reads the lines inside a variable, one by one (similar to a file-reading loop). A file can be loaded into a variable via FileRead.
77 |Loop parse, FileContents, "`n", "`r" ; Specifying `n prior to `r allows both Windows and Unix files to be parsed. 78 | { 79 | Result := MsgBox("Line number " A_Index " is " A_LoopField ".`n`nContinue?",, "y/n") 80 | } 81 | until Result = "No"82 |
This is the same as the example above except that it's for the clipboard. It's useful whenever the clipboard contains files, such as those copied from an open Explorer window (the program automatically converts such files to their file names).
86 |Loop parse, A_Clipboard, "`n", "`r" 87 | { 88 | Result := MsgBox("File number " A_Index " is " A_LoopField ".`n`nContinue?",, "y/n") 89 | } 90 | until Result = "No"91 |
Parses a comma separated value (CSV) file.
95 |Loop read, "C:\Database Export.csv" 96 | { 97 | LineNumber := A_Index 98 | Loop parse, A_LoopReadLine, "CSV" 99 | { 100 | Result := MsgBox("Field " LineNumber "-" A_Index " is:`n" A_LoopField "`n`nContinue?",, "y/n") 101 | if Result = "No" 102 | return 103 | } 104 | }105 |
Determines which delimiter character was encountered.
109 |; Initialize string to search. 110 | Colors := "red,green|blue;yellow|cyan,magenta" 111 | ; Initialize counter to keep track of our position in the string. 112 | Position := 0 113 | 114 | Loop Parse, Colors, ",|;" 115 | { 116 | ; Calculate the position of the delimiter character at the end of this field. 117 | Position += StrLen(A_LoopField) + 1 118 | ; Retrieve the delimiter character found by the parsing loop. 119 | DelimiterChar := SubStr(Colors, Position, 1) 120 | 121 | MsgBox "Field: " A_LoopField "`nDelimiter character: " DelimiterChar 122 | }123 |
Retrieves the lines in a text file, one at a time.
17 | 18 |Loop Read InputFile , OutputFile19 |
Type: String
25 |The name of the text file whose contents will be read by the loop, which is assumed to be in A_WorkingDir if an absolute path isn't specified. The file's lines may end in carriage return and linefeed (`r`n), just linefeed (`n), or just carriage return (`r).
26 |Type: String
31 |(Optional) The name of the file to be kept open for the duration of the loop, which is assumed to be in A_WorkingDir if an absolute path isn't specified.
32 |Within the loop's body, use the FileAppend function without the Filename parameter (i.e. omit it) to append to this special file. Appending to a file in this manner performs better than using FileAppend in its 2-parameter mode because the file does not need to be closed and re-opened for each operation. Remember to include a linefeed (`n) or carriage return and linefeed (`r`n) after the text, if desired.
33 |The file is not opened if nothing is ever written to it. This happens if the loop performs zero iterations or if it never calls FileAppend.
34 |Options: The end of line (EOL) translation mode and output file encoding depend on which options are passed in the opening call to FileAppend (i.e. the first call which omits Filename). Subsequent calls ignore the Options parameter. EOL translation is not performed by default; that is, linefeed (`n) characters are written as-is unless the "`n"
option is present.
Standard Output (stdout): Specifying an asterisk (*) for OutputFile sends any text written by FileAppend to standard output (stdout). Such text can be redirected to a file, piped to another EXE, or captured by fancy text editors. However, text sent to stdout will not appear at the command prompt it was launched from. This can be worked around by 1) compiling the script with the Ahk2Exe ConsoleApp directive, or 2) piping a script's output to another command or program. See FileAppend for more details.
36 |A file-reading loop is useful when you want to operate on each line contained in a text file, one at a time. The file is kept open for the entire operation to avoid having to re-scan each time to find the next line.
42 |The built-in variable A_LoopReadLine exists within any file-reading loop. It contains the contents of the current line excluding the carriage return and linefeed (`r`n) that marks the end of the line. If an inner file-reading loop is enclosed by an outer file-reading loop, the innermost loop's file-line will take precedence.
43 |Lines up to 65,534 characters long can be read. If the length of a line exceeds this, its remaining characters will be read during the next loop iteration.
44 |StrSplit or a parsing loop is often used inside a file-reading loop to parse the contents of each line retrieved from InputFile. For example, if InputFile's lines are each a series of tab-delimited fields, those fields can individually retrieved as in this example:
45 |Loop read, "C:\Database Export.txt" 46 | { 47 | Loop parse, A_LoopReadLine, A_Tab 48 | { 49 | MsgBox "Field number " A_Index " is " A_LoopField "." 50 | } 51 | }52 |
To load an entire file into a variable, use FileRead because it performs much better than a loop (especially for large files).
53 |To have multiple files open simultaneously, use FileOpen.
54 |The One True Brace (OTB) style may optionally be used, which allows the open-brace to appear on the same line rather than underneath. For example: Loop Read InputFile, OutputFile {
.
See Loop for information about Blocks, Break, Continue, and the A_Index variable (which exists in every type of loop).
56 |To control how the file is decoded when no byte order mark is present, use FileEncoding.
57 |The loop may optionally be followed by an Else statement, which is executed if the input file is empty or could not be found. If OutputFile was specified, the special mode of FileAppend described above may also be used within the Else statement's body. If there is no Else, an OSError is thrown if the file could not be found.
58 | 59 |FileEncoding, FileOpen/File Object, FileRead, FileAppend, Sort, Loop, Break, Continue, Blocks, FileSetAttrib, FileSetTime
61 | 62 |Only those lines of the 1st file that contain the word FAMILY will be written to the 2nd file. Uncomment the first line to overwrite rather than append to any existing file.
65 |;FileDelete "C:\Docs\Family Addresses.txt" 66 | 67 | Loop read, "C:\Docs\Address List.txt", "C:\Docs\Family Addresses.txt" 68 | { 69 | if InStr(A_LoopReadLine, "family") 70 | FileAppend(A_LoopReadLine "`n") 71 | } 72 | else 73 | MsgBox "Address List.txt was completely empty or not found."74 |
Retrieves the last line from a text file.
78 |Loop read, "C:\Log File.txt" 79 | last_line := A_LoopReadLine ; When loop finishes, this will hold the last line.80 |
Attempts to extract all FTP and HTTP URLs from a text or HTML file.
84 |85 | SourceFile := FileSelect(3,, "Pick a text or HTML file to analyze.") 86 | if SourceFile = "" 87 | return ; This will exit in this case. 88 | 89 | SplitPath SourceFile,, &SourceFilePath,, &SourceFileNoExt 90 | DestFile := SourceFilePath "\" SourceFileNoExt " Extracted Links.txt" 91 | 92 | if FileExist(DestFile) 93 | { 94 | Result := MsgBox("Overwrite the existing links file? Press No to append to it.`n`nFILE: " DestFile,, 4) 95 | if Result = "Yes" 96 | FileDelete DestFile 97 | } 98 | 99 | LinkCount := 0 100 | Loop read, SourceFile, DestFile 101 | { 102 | URLSearch(A_LoopReadLine) 103 | } 104 | MsgBox LinkCount ' links were found and written to "' DestFile '".' 105 | return 106 | 107 | 108 | URLSearch(URLSearchString) 109 | { 110 | ; It's done this particular way because some URLs have other URLs embedded inside them: 111 | ; Find the left-most starting position: 112 | URLStart := 0 ; Set starting default. 113 | for URLPrefix in ["https://", "http://", "ftp://", "www."] 114 | { 115 | ThisPos := InStr(URLSearchString, URLPrefix) 116 | if !ThisPos ; This prefix is disqualified. 117 | continue 118 | if !URLStart 119 | URLStart := ThisPos 120 | else ; URLStart has a valid position in it, so compare it with ThisPos. 121 | { 122 | if ThisPos && ThisPos < URLStart 123 | URLStart := ThisPos 124 | } 125 | } 126 | 127 | if !URLStart ; No URLs exist in URLSearchString. 128 | return 129 | 130 | ; Otherwise, extract this URL: 131 | URL := SubStr(URLSearchString, URLStart) ; Omit the beginning/irrelevant part. 132 | Loop parse, URL, " `t<>" ; Find the first space, tab, or angle bracket (if any). 133 | { 134 | URL := A_LoopField 135 | break ; i.e. perform only one loop iteration to fetch the first "field". 136 | } 137 | ; If the above loop had zero iterations because there were no ending characters found, 138 | ; leave the contents of the URL var untouched. 139 | 140 | ; If the URL ends in a double quote, remove it. For now, StrReplace is used, but 141 | ; note that it seems that double quotes can legitimately exist inside URLs, so this 142 | ; might damage them: 143 | URLCleansed := StrReplace(URL, '"') 144 | FileAppend URLCleansed "`n" 145 | global LinkCount += 1 146 | 147 | ; See if there are any other URLs in this line: 148 | CharactersToOmit := StrLen(URL) 149 | CharactersToOmit += URLStart 150 | URLSearchString := SubStr(URLSearchString, CharactersToOmit) 151 | 152 | ; Recursive call to self: 153 | URLSearch(URLSearchString) 154 | } 155 |156 |
Retrieves the contents of the specified registry subkey, one item at a time.
16 | 17 |Loop Reg KeyName , Mode18 |
Type: String
24 |The full name of the registry key, e.g. "HKLM\Software\SomeApplication"
.
This must start with HKEY_LOCAL_MACHINE (or HKLM), HKEY_USERS (or HKU), HKEY_CURRENT_USER (or HKCU), HKEY_CLASSES_ROOT (or HKCR), or HKEY_CURRENT_CONFIG (or HKCC).
26 |To access a remote registry, prepend the computer name and a backslash, e.g. "\\workstation01\HKLM"
.
Type: String
32 |If blank or omitted, only values are included and subkeys are not recursed into. Otherwise, specify one or more of the following letters:
33 |A registry loop is useful when you want to operate on a collection registry values or subkeys, one at a time. The values and subkeys are retrieved in reverse order (bottom to top) so that RegDelete and RegDeleteKey can be used inside the loop without disrupting the loop.
45 |The following variables exist within any registry loop. If an inner registry loop is enclosed by an outer registry loop, the innermost loop's registry item will take precedence:
46 |Variable | 49 |Description | 50 |
---|---|
A_LoopRegName | 53 |Name of the currently retrieved item, which can be either a value name or the name of a subkey. Value names displayed by Windows RegEdit as "(Default)" will be retrieved if a value has been assigned to them, but A_LoopRegName will be blank for them. | 54 |
A_LoopRegType | 57 |The type of the currently retrieved item, which is one of the following words: KEY (i.e. the currently retrieved item is a subkey not a value), REG_SZ, REG_EXPAND_SZ, REG_MULTI_SZ, REG_DWORD, REG_QWORD, REG_BINARY, REG_LINK, REG_RESOURCE_LIST, REG_FULL_RESOURCE_DESCRIPTOR, REG_RESOURCE_REQUIREMENTS_LIST, REG_DWORD_BIG_ENDIAN (probably rare on most Windows hardware). It will be empty if the currently retrieved item is of an unknown type. | 58 |
A_LoopRegKey | 61 |The full name of the key which contains the current loop item. For remote registry access, this value will not include the computer name. | 62 |
A_LoopRegTimeModified | 65 |The time the current subkey or any of its values was last modified. Format YYYYMMDDHH24MISS. This variable will be empty if the currently retrieved item is not a subkey (i.e. A_LoopRegType is not the word KEY). | 66 |
When used inside a registry loop, the following functions can be used in a simplified way to indicate that the currently retrieved item should be operated upon:
69 |Syntax | 72 |Description | 73 |
---|---|
Value := RegRead() |
76 | Reads the current item. If the current item is a key, an exception is thrown. | 77 |
RegWrite Value RegWrite |
80 | Writes to the current item. If Value is omitted, the item will be made 0 or blank depending on its type. If the current item is a key, an exception is thrown and the registry is not modified. | 81 |
RegDelete |
84 | Deletes the current item if it is a value. If the current item is a key, its default value will be deleted instead. | 85 |
RegDeleteKey |
88 | Deletes the current item if it is a key. If the current item is a value, the key which contains that value will be deleted, including all subkeys and values. | 89 |
RegCreateKey |
92 | Targets a key as described above for RegDeleteKey. If the key is deleted during the loop, RegCreateKey can be used to recreate it. Otherwise, RegCreateKey merely verifies that the script has write access to the key. | 93 |
When accessing a remote registry (via the KeyName parameter described above), the following notes apply:
96 |The One True Brace (OTB) style may optionally be used, which allows the open-brace to appear on the same line rather than underneath. For example: Loop Reg "HKLM\Software\AutoHotkey", "V" {
.
See Loop for information about Blocks, Break, Continue, and the A_Index variable (which exists in every type of loop).
104 |The loop may optionally be followed by an Else statement, which is executed if no registry items of the specified type were found (i.e. the loop had zero iterations).
105 | 106 |Loop, Break, Continue, Blocks, RegRead, RegWrite, RegDelete, RegDeleteKey, SetRegView
108 | 109 |Retrieves the contents of the specified registry subkey, one item at a time.
112 |Loop Reg, "HKEY_LOCAL_MACHINE\Software\SomeApplication" 113 | MsgBox A_LoopRegName114 |
Deletes Internet Explorer's history of URLs typed by the user.
118 |Loop Reg, "HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\TypedURLs" 119 | RegDelete120 |
Loop Reg, "HKCU\Software\Microsoft\Windows", "R KV" ; Recursively retrieve keys and values. 125 | { 126 | if A_LoopRegType = "key" 127 | value := "" 128 | else 129 | { 130 | try 131 | value := RegRead() 132 | catch 133 | value := "*error*" 134 | } 135 | Result := MsgBox(A_LoopRegName " = " value " (" A_LoopRegType ")`n`nContinue?",, "y/n") 136 | } 137 | Until Result = "No"138 |
Recursively searches the entire registry for particular value(s).
142 |143 | RegSearch("Notepad") 144 | 145 | RegSearch(Target) 146 | { 147 | Loop Reg, "HKEY_LOCAL_MACHINE", "KVR" 148 | { 149 | if !CheckThisRegItem() ; It told us to stop. 150 | return 151 | } 152 | Loop Reg, "HKEY_USERS", "KVR" 153 | { 154 | if !CheckThisRegItem() ; It told us to stop. 155 | return 156 | } 157 | Loop Reg, "HKEY_CURRENT_CONFIG", "KVR" 158 | { 159 | if !CheckThisRegItem() ; It told us to stop. 160 | return 161 | } 162 | ; Note: I believe HKEY_CURRENT_USER does not need to be searched if 163 | ; HKEY_USERS is being searched. Similarly, HKEY_CLASSES_ROOT provides a 164 | ; combined view of keys from HKEY_LOCAL_MACHINE and HKEY_CURRENT_USER, so 165 | ; searching all three isn't necessary. 166 | 167 | CheckThisRegItem() 168 | { 169 | if A_LoopRegType = "KEY" ; Remove these two lines if you want to check key names too. 170 | return true 171 | try 172 | RegValue := RegRead() 173 | catch 174 | return true 175 | if InStr(RegValue, Target) 176 | { 177 | Result := MsgBox( 178 | ( 179 | "The following match was found: 180 | " A_LoopRegKey "\" A_LoopRegName " 181 | Value = " RegValue " 182 | 183 | Continue?" 184 | ),, "y/n") 185 | if Result = "No" 186 | return false ; Tell our caller to stop searching. 187 | } 188 | return true 189 | } 190 | } 191 |192 |
class Map extends Object16 | 17 |
A Map object associates or maps one set of values, called keys, to another set of values. A key and the value it is mapped to are known as a key-value pair. A map can contain any number of key-value pairs, but each key must be unique.
18 |A key may be any Integer, object reference or null-terminated String. Comparison of string keys is case-sensitive, while objects are compared by reference/address. Float keys are automatically converted to String.
19 |The simplest use of a map is to retrieve or set a key-value pair via the implicit __Item property, by simply writing the key between brackets following the map object. For example:
20 |clrs := Map() 21 | clrs["Red"] := "ff0000" 22 | clrs["Green"] := "00ff00" 23 | clrs["Blue"] := "0000ff" 24 | for clr in Array("Blue", "Green") 25 | MsgBox clrs[clr] 26 |27 |
"MapObj" is used below as a placeholder for any Map object, as "Map" is the class itself.
28 |In addition to the methods and property inherited from Object, Map objects have the following predefined methods and properties.
29 | 30 |Creates a Map and sets items.
64 |MapObj := Map(Key1, Value1, Key2, Value2, ...)
65 | MapObj := Map.Call(Key1, Value1, Key2, Value2, ...)
66 | This is equivalent to setting each item with MapObj[Key] := Value
, except that __Item is not called and Capacity is automatically adjusted to avoid expanding multiple times during a single call.
Parameters are defined by __New.
68 |Removes all key-value pairs from a map.
74 |MapObj.Clear()
75 | Returns a shallow copy of a map.
79 |Clone := MapObj.Clone()
80 | All key-value pairs are copied to the new map. Object references are copied (like with a normal assignment), not the objects themselves.
81 |Own properties, own methods and base are copied as per Obj.Clone.
82 |Removes a key-value pair from a map.
86 |RemovedValue := MapObj.Delete(Key)
87 | Type: Integer, Object or String
92 |Any single key. If the map does not contain this key, an UnsetItemError is thrown.
93 |Type: Any
97 |This method returns the removed value.
98 |Returns the value associated with a key, or a default value.
102 |Value := MapObj.Get(Key , Default)103 |
This method does the following:
104 |MapObj.Default
, if defined.When Default is omitted, this is equivalent to MapObj[Key]
, except that __Item is not called.
Returns true if the specified key has an associated value within a map, otherwise false.
115 |MapObj.Has(Key)
116 | Sets zero or more items.
120 |MapObj.Set(Key, Value, Key2, Value2, ...)121 |
This is equivalent to setting each item with MapObj[Key] := Value
, except that __Item is not called and Capacity is automatically adjusted to avoid expanding multiple times during a single call.
Type: Object
124 |This method returns the Map.
125 |Enumerates key-value pairs.
129 |For Key , Value in MapObj
130 | Returns a new enumerator. This method is typically not called directly. Instead, the map object is passed directly to a for-loop, which calls __Enum once and then calls the enumerator once for each iteration of the loop. Each call to the enumerator returns the next key and/or value. The for-loop's variables correspond to the enumerator's parameters, which are:
131 | 143 |Sets items. Equivalent to Set.
147 |MapObj.__New(Key, Value, Key2, Value2, ...)148 |
This method exists to support Call, and is not intended to be called directly. See Construction and Destruction.
149 |Retrieves the number of key-value pairs present in a map.
155 |Count := MapObj.Count
156 | Retrieves or sets the current capacity of a map.
160 |MaxItems := MapObj.Capacity
161 | MapObj.Capacity := MaxItems
162 | MaxItems is an integer representing the maximum number of key-value pairs the map should be able to contain before it must be automatically expanded. If setting a value less than the current number of key-value pairs, that number is used instead, and any unused space is freed.
163 |Retrieves or sets a map's case sensitivity setting.
167 |CurrentSetting := MapObj.CaseSense
168 | MapObj.CaseSense := NewSetting
169 | CurrentSetting is NewSetting if assigned, otherwise On by default (but note that this property only retrieves the string variant of the current setting).
170 |NewSetting is one of the following strings or integers (boolean):
171 |On or 1 (true): Key lookups are case-sensitive. This is the default setting.
172 |Off or 0 (false): Key lookups are not case-sensitive, i.e. the letters A-Z are considered identical to their lowercase counterparts.
173 |Locale: Key lookups are not case-sensitive according to the rules of the current user's locale. For example, most English and Western European locales treat not only the letters A-Z as identical to their lowercase counterparts, but also non-ASCII letters like Ä and Ü as identical to theirs. Locale is 1 to 8 times slower than Off depending on the nature of the strings being compared.
174 |Attempting to assign to this property causes an exception to be thrown if the Map is not empty.
175 |Defines the default value returned when a key is not found.
179 |MapObj.Default := Value
180 | This property actually doesn't exist by default, but can be defined by the script. If defined, its value is returned by __Item or Get if the requested item cannot be found, instead of throwing an UnsetItemError. It can be implemented by any of the normal means, including a dynamic property or meta-function, but determining which key was queried would require overriding __Item or Get instead.
181 |Retrieves or sets the value of a key-value pair.
185 |Value := MapObj[Key]
186 | Value := MapObj.__Item[Key]
187 | MapObj[Key] := Value
188 | MapObj.__Item[Key] := Value
189 | When retrieving a value, Key must be a unique value previously associated with another value. An UnsetItemError is thrown if Key has no associated value within the map, unless a Default property is defined, in which case its value is returned.
190 |When assigning a value, Key can be any value to associate with Value; in other words, the key used to later access Value. Float keys are automatically converted to String.
191 |The property name __Item is typically omitted, as shown above, but is used when overriding the property.
192 |Functions for performing various mathematical operations such as rounding, exponentiation, squaring, etc.
15 | 16 |Returns the absolute value of the specified number.
50 |Value := Abs(Number)
51 | The return value is the same type as Number (integer or floating point).
52 |MsgBox Abs(-1.2) ; Returns 1.253 | 54 |
Returns the specified number rounded up to the nearest integer (without any .00 suffix).
56 |Value := Ceil(Number)
57 | MsgBox Ceil(1.2) ; Returns 2 58 | MsgBox Ceil(-1.2) ; Returns -159 | 60 |
Returns the result of raising e (which is approximately 2.71828182845905) to the Nth power.
62 |Value := Exp(N)
63 | N may be negative and may contain a decimal point. To raise numbers other than e to a power, use the ** operator.
64 |MsgBox Exp(1.2) ; Returns 3.32011765 | 66 |
Returns the specified number rounded down to the nearest integer (without any .00 suffix).
68 |Value := Floor(Number)
69 | MsgBox Floor(1.2) ; Returns 1 70 | MsgBox Floor(-1.2) ; Returns -271 | 72 |
Returns the logarithm (base 10) of the specified number.
74 |Value := Log(Number)
75 | The result is a floating-point number. If Number is negative, a ValueError is thrown.
76 |MsgBox Log(1.2) ; Returns 0.07918177 | 78 |
Returns the natural logarithm (base e) of the specified number.
80 |Value := Ln(Number)
81 | The result is a floating-point number. If Number is negative, a ValueError is thrown.
82 |MsgBox Ln(1.2) ; Returns 0.18232283 | 84 |
Returns the highest number from a set of numbers.
86 |Number := Max(Number1 , Number2, ...)87 |
MsgBox Max(2.11, -2, 0) ; Returns 2.1188 |
You can also specify a variadic parameter to pass an array of numbers. For example:
89 |Numbers := [1, 2, 3, 4] 90 | MsgBox Max(Numbers*) ; Returns 4 91 |92 | 93 |
Returns the lowest number from a set of numbers.
95 |Number := Min(Number1 , Number2, ...)96 |
MsgBox Min(2.11, -2, 0) ; Returns -297 |
You can also specify a variadic parameter to pass an array of numbers. For example:
98 |Numbers := [1, 2, 3, 4] 99 | MsgBox Min(Numbers*) ; Returns 1100 | 101 |
Modulo. Returns the remainder of a number (dividend) divided by another number (divisor).
103 |Value := Mod(Dividend, Divisor)
104 | The sign of the result is always the same as the sign of the first parameter. If either input is a floating point number, the result is also a floating point number. If the second parameter is zero, a ZeroDivisionError is thrown.
105 |MsgBox Mod(7.5, 2) ; Returns 1.5 (2 x 3 + 1.5)106 | 107 |
Returns the specified number rounded to N decimal places.
109 |Value := Round(Number , N)110 |
If N is omitted or 0, Number is rounded to the nearest integer:
111 |MsgBox Round(3.14) ; Returns 3112 |
If N is positive, Number is rounded to N decimal places:
113 |MsgBox Round(3.14, 1) ; Returns 3.1114 |
If N is negative, Number is rounded by N digits to the left of the decimal point:
115 |MsgBox Round(345, -1) ; Returns 350 116 | MsgBox Round(345, -2) ; Returns 300117 |
The result is an integer if N is omitted or less than 1. Otherwise, the result is a numeric string with exactly N decimal places. If a pure number is needed, simply perform another math operation on Round's return value; for example: Round(3.333, 1)+0
.
Returns the square root of the specified number.
121 |Value := Sqrt(Number)
122 | The result is a floating-point number. If Number is negative, a ValueError is thrown.
123 |MsgBox Sqrt(16) ; Returns 4124 | 125 |
Note: To convert a radians value to degrees, multiply it by 180/pi (approximately 57.29578). To convert a degrees value to radians, multiply it by pi/180 (approximately 0.01745329252). The value of pi (approximately 3.141592653589793) is 4 times the arctangent of 1.
127 | 128 |Returns the trigonometric sine of the specified number.
130 |Value := Sin(Number)
131 | Number must be expressed in radians.
132 |MsgBox Sin(1.2) ; Returns 0.932039133 | 134 |
Returns the trigonometric cosine of the specified number.
136 |Value := Cos(Number)
137 | Number must be expressed in radians.
138 |MsgBox Cos(1.2) ; Returns 0.362358139 | 140 |
Returns the trigonometric tangent of the specified number.
142 |Value := Tan(Number)
143 | Number must be expressed in radians.
144 |MsgBox Tan(1.2) ; Returns 2.572152145 | 146 |
Returns the arcsine (the number whose sine is the specified number) in radians.
148 |Value := ASin(Number)
149 | If Number is less than -1 or greater than 1, a ValueError is thrown.
150 |MsgBox ASin(0.2) ; Returns 0.201358151 | 152 |
Returns the arccosine (the number whose cosine is the specified number) in radians.
154 |Value := ACos(Number)
155 | If Number is less than -1 or greater than 1, a ValueError is thrown.
156 |MsgBox ACos(0.2) ; Returns 1.369438157 | 158 |
Returns the arctangent (the number whose tangent is the specified number) in radians.
160 |Value := ATan(Number)
161 | MsgBox ATan(1.2) ; Returns 0.876058162 | 163 |
These functions throw an exception if any incoming parameters are non-numeric or an invalid operation (such as divide by zero) is attempted.
165 | 166 | 167 | 168 | -------------------------------------------------------------------------------- /docs/lib/Menu.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Provides an interface to create and modify a menu or menu bar, add and modify menu items, and retrieve information about the menu or menu bar.
16 |class Menu extends Object17 |
Menu objects are used to define, modify and display popup menus. Menu(), MenuFromHandle and A_TrayMenu return an object of this type.
18 |class MenuBar extends Menu19 |
MenuBar objects are used to define and modify menu bars for use with Gui.MenuBar. They are created with MenuBar(). MenuFromHandle returns an object of this type if given a menu bar handle.
20 | 21 |"MyMenu" is used below as a placeholder for any Menu object, as "Menu" is the class itself.
22 |In addition to the methods and property inherited from Object, Menu objects have the following predefined methods and properties.
23 | 24 |Creates a new Menu or MenuBar object.
71 |72 | MyMenu := Menu() 73 | MyMenuBar := MenuBar() 74 | MyMenu := Menu.Call() 75 | MyMenuBar := MenuBar.Call() 76 |77 |
Adds or modifies a menu item.
83 |MyMenu.Add(MenuItemName, CallbackOrSubmenu, Options)84 |
Type: String
89 |The text to display on the menu item, or the position of an existing item to modify. See MenuItemName.
90 |Type: Function Object or Menu
94 |The function to call as a new thread when the menu item is selected, or a reference to a Menu object to use as a submenu.
95 |This parameter is required when creating a new item, but optional when updating the options of an existing item.
96 |The callback accepts three parameters and can be defined as follows:
97 |MyCallback(ItemName, ItemPos, MyMenu) { ...98 |
Although the names you give the parameters do not matter, the following values are sequentially assigned to them:
99 |You can omit one or more parameters from the end of the callback's parameter list if the corresponding information is not needed, but in this case an asterisk must be specified as the final parameter, e.g. MyCallback(Param1, *)
.
Type: String
109 |If blank or omitted, it defaults to no options. Otherwise, specify one or more options from the list below (not case-sensitive). Separate each option from the next with a space or tab. To remove an option, precede it with a minus sign. To add an option, a plus sign is permitted but not required.
110 |Pn: Specify for n the menu item's thread priority, e.g. P1
. If this option is omitted when adding a menu item, the priority will be 0, which is the standard default. If omitted when updating a menu item, the item's priority will not be changed. Use a decimal (not hexadecimal) number as the priority.
Radio: If the item is checked, a bullet point is used instead of a check mark.
112 |Right: The item is right-justified within the menu bar. This only applies to menu bars, not popup menus or submenus.
113 |Break: The item begins a new column in a popup menu.
114 |BarBreak: As above, but with a dividing line between columns.
115 |To change an existing item's options without affecting its callback or submenu, simply omit the CallbackOrSubmenu parameter.
116 |This is a multipurpose method that adds a menu item, updates one with a new submenu or callback, or converts one from a normal item into a submenu (or vice versa). If MenuItemName does not yet exist, it will be added to the menu. Otherwise, MenuItemName is updated with the newly specified CallbackOrSubmenu and/or Options.
120 |To add a menu separator line, omit all three parameters.
121 |This method always adds new menu items at the bottom of the menu, while the Insert method can be used to insert an item before an existing custom menu item.
122 |Adds the standard tray menu items.
127 |MyMenu.AddStandard()
128 | This method can be used with the tray menu or any other menu.
129 |The standard items are inserted after any existing items. Any standard items already in the menu are not duplicated, but any missing items are added. The table below shows the names and positions of the standard items after calling AddStandard on an empty menu:
130 | 151 |&Open | 1 | 0 |
&Help | 2 | |
3 | ||
&Window Spy | 4 | |
&Reload Script | 5 | |
&Edit Script | 6 | |
7 | ||
&Suspend Hotkeys | 8 | 1 |
&Pause Script | 9 | 2 |
E&xit | 10 | 3 |
Compiled scripts include only the last three by default. &Open
is included only if A_AllowMainWindow is 1 when AddStandard is called (in that case, add 1 to the positions shown in the third column). If the tray menu contains standard items, &Open
is inserted or removed whenever A_AllowMainWindow is changed. For other menus, &Open
has no effect if A_AllowMainWindow is 0.
Each standard item has an internal menu item ID corresponding to the function it performs, but can otherwise be modified or deleted like any other menu item. AddStandard detects existing items by ID, not by name. If the Add method is used to change the callback function associated with a standard menu item, it is assigned a new unique ID and is no longer considered to be a standard item.
165 |Adding the &Open
item to the tray menu causes it to become the default item if there wasn't one already.
Adds a visible checkmark in the menu next to a menu item (if there isn't one already).
171 |MyMenu.Check(MenuItemName)
172 | Type: String
177 |The name or position of a menu item. See MenuItemName.
178 |Deletes one or all menu items.
185 |MyMenu.Delete(MenuItemName)186 |
Type: String
191 |If omitted, all menu items are deleted from the menu, leaving the menu empty. Otherwise, specify the name or position of a menu item. See MenuItemName.
192 |An empty menu still exists and thus any other menus that use it as a submenu will retain those submenus.
196 |To delete a separator line, identify it by its position in the menu. For example, use MyMenu.Delete("3&")
if there are two items preceding the separator.
If the default menu item is deleted, the effect will be similar to having set MyMenu.Default := ""
.
Grays out a menu item to indicate that the user cannot select it.
203 |MyMenu.Disable(MenuItemName)
204 | Type: String
209 |The name or position of a menu item. See MenuItemName.
210 |Allows the user to once again select a menu item if it was previously disabled (grayed out).
217 |MyMenu.Enable(MenuItemName)
218 | Type: String
223 |The name or position of a menu item. See MenuItemName.
224 |Inserts a new item before the specified item.
231 |MyMenu.Insert(MenuItemName, ItemToInsert, CallbackOrSubmenu, Options)232 |
Type: String
237 |If blank or omitted, ItemToInsert will be added at the bottom of the menu. Otherwise, specify the name or position of an existing custom menu item before which ItemToInsert should be inserted. See MenuItemName.
238 |Type: String
242 |The name of a new menu item to insert before MenuItemName. Unlike the Add method, a new item is always created, even if ItemToInsert matches the name of an existing item.
243 |See the Add method's CallbackOrSubmenu parameter.
247 |See the Add method's Options parameter.
251 |To insert a menu separator line before an existing custom menu item, omit all parameters except MenuItemName. To add a menu separator line at the bottom of the menu, omit all parameters.
255 |Renames a menu item.
260 |MyMenu.Rename(MenuItemName , NewName)261 |
Type: String
266 |The name or position of a menu item. See MenuItemName.
267 |Type: String
271 |If blank or omitted, MenuItemName will be converted into a separator line. Otherwise, specify the new name.
272 |The menu item's current callback or submenu is unchanged.
276 |A separator line can be converted to a normal item by specifying the position of the separator such as "1&"
for MenuItemName and a non-blank name for NewName, and then using the Add method to give the item a callback or submenu.
Changes the background color of the menu.
282 |MyMenu.SetColor(ColorValue, ApplyToSubmenus)283 |
If blank or omitted, it defaults to the word Default, which restores the default color of the menu. Otherwise, specify one of the 16 primary HTML color names, a hexadecimal RGB color string (the 0x prefix is optional), or a pure numeric RGB color value. Example values: "Silver"
, "FFFFAA"
, 0xFFFFAA
, "Default"
.
Type: Boolean
294 |If omitted, it defaults to true.
295 |If true, the color will be applied to all of the menu's submenus.
296 |If false, the color will be applied to the menu only.
297 |Sets the icon to be displayed next to a menu item.
304 |MyMenu.SetIcon(MenuItemName, FileName , IconNumber, IconWidth)305 |
Type: String
310 |The name or position of a menu item. See MenuItemName.
311 |Type: String
315 |The path to an icon or image file, or a bitmap or icon handle such as "HICON:" handle
. For a list of supported formats, see the Picture control.
Specify an empty string or "*"
to remove the item's current icon.
Type: Integer
321 |If omitted, it defaults to 1 (the first icon group). Otherwise, specify the number of the icon group to be used in the file. For example, MyMenu.SetIcon(MenuItemName, "Shell32.dll", 2)
would use the default icon from the second icon group. If negative, its absolute value is assumed to be the resource ID of an icon within an executable file.
Type: Integer
326 |If omitted, it defaults to the width of a small icon recommended by the OS (usually 16 pixels). If 0, the original width is used. Otherwise, specify the desired width of the icon, in pixels. If the icon group indicated by IconNumber contains multiple icon sizes, the closest match is used and the icon is scaled to the specified size.
327 |Currently it is necessary to specify the "actual size" when setting the icon to preserve transparency, e.g.
331 | MyMenu.SetIcon(MenuItemName, "Filename.png",, 0)
.
Displays the menu.
337 |MyMenu.Show(X, Y)338 |
Type: Integer
343 |If omitted, the menu will be shown near the mouse cursor. Otherwise, specify the X and Y coordinates at which to display the upper left corner of the menu. The coordinates are relative to the active window's client area unless overridden by using CoordMode or A_CoordModeMenu.
344 |Displaying the menu allows the user to select an item with arrow keys, menu shortcuts (underlined letters), or the mouse.
348 |Any popup menu can be shown, including submenus and the tray menu. However, an exception is thrown if MyMenu is a MenuBar object.
349 |Adds a checkmark if there wasn't one; otherwise, removes it.
354 |MyMenu.ToggleCheck(MenuItemName)
355 | Type: String
360 |The name or position of a menu item. See MenuItemName.
361 |Disables a menu item if it was previously enabled; otherwise, enables it.
368 |MyMenu.ToggleEnable(MenuItemName)
369 | Type: String
374 |The name or position of a menu item. See MenuItemName.
375 |Removes the checkmark (if there is one) from a menu item.
382 |MyMenu.Uncheck(MenuItemName)
383 | Type: String
388 |The name or position of a menu item. See MenuItemName.
389 |Retrieves or sets how many times the tray icon must be clicked to select its default menu item.
397 |CurrentCount := MyMenu.ClickCount
398 | MyMenu.ClickCount := NewCount
399 | CurrentCount is NewCount if assigned, otherwise 2 by default.
400 |NewCount can be 1 to allow a single-click to select the tray menu's default menu item, or 2 to return to the default behavior (double-click). Any other value is invalid and throws an exception.
401 |Retrieves or sets the default menu item.
406 |CurrentDefault := MyMenu.Default
407 | MyMenu.Default := MenuItemName
408 | CurrentDefault is the name of the default menu item, or an empty string if there is no default.
409 |MenuItemName is the name or position of a menu item. See MenuItemName. If MenuItemName is an empty string, there will be no default.
410 |Setting the default item makes that item's font bold (setting a default item in menus other than the tray menu is currently purely cosmetic). When the user double-clicks the tray icon, its default menu item is selected (even if the item is disabled). If there is no default, double-clicking has no effect.
411 |The default item for the tray menu is initially &Open
, if present. Adding &Open
to the tray menu by calling AddStandard or changing A_AllowMainWindow also causes it to become the default item if there wasn't one already.
If the default item is deleted, the menu is left without one.
413 |Returns a handle to a Win32 menu (a handle of type HMENU
), constructing it if necessary.
Handle := MyMenu.Handle
419 | The returned handle is valid only until the Win32 menu is destroyed, which typically occurs when the Menu object is freed. Once the menu is destroyed, the operating system may reassign the handle value to any menus subsequently created by the script or any other program.
420 |The name or position of a menu item. Some common rules apply to this parameter across all methods which use it:
424 |To underline one of the letters in a menu item's name, precede that letter with an ampersand (&). When the menu is displayed, such an item can be selected by pressing the corresponding key on the keyboard. To display a literal ampersand, specify two consecutive ampersands as in this example: "Save && Exit"
When referring to an existing menu item, the name is not case-sensitive but any ampersands must be included. For example: "&Open"
The names of menu items can be up to 260 characters long.
427 |To identify an existing item by its position in the menu, write the item's position followed by an ampersand. For example, "1&"
indicates the first item.
Windows provides a set of functions and notifications for creating, modifying and displaying menus with standard appearance and behavior. We refer to a menu created by one of these functions as a Win32 menu.
431 |As items are added to a menu or modified, the name and other properties of each item are stored in the Menu object. A Win32 menu is constructed the first time the menu or its parent menu is attached to a GUI or shown. It is destroyed automatically when the menu object is deleted (which occurs when its reference count reaches zero).
432 |Menu.Handle returns a handle to a Win32 menu (a handle of type HMENU
), constructing it if necessary.
Any modifications which are made to the menu directly by Win32 functions are not reflected by the script's Menu object, so may be lost if an item is modified by one of the built-in methods.
434 |Each menu item is assigned an ID when it is first added to the menu. Scripts cannot rely on an item receiving a particular ID, but can retrieve the ID of an item by using GetMenuItemID as shown in example #5. This ID cannot be used with the Menu object, but can be used with various Win32 functions.
435 | 436 |A menu usually looks like this:
438 | 439 |If a menu ever becomes completely empty -- such as by using MyMenu.Delete()
-- it cannot be shown. If the tray menu becomes empty, right-clicking and double-clicking the tray icon will have no effect (in such cases it is usually better to use #NoTrayIcon).
If a menu item's callback is already running and the user selects the same menu item again, a new thread will be created to run that same callback, interrupting the previous thread. To instead buffer such events until later, use Critical as the callback's first line (however, this will also buffer/defer other threads such as the press of a hotkey).
441 |Whenever a function is called via a menu item, it starts off fresh with the default values for settings such as SendMode. These defaults can be changed during script startup.
442 |When building a menu whose contents are not always the same, one approach is to point all such menu items to the same function and have that function refer to its parameters to determine what action to take. Alternatively, a function object, closure or fat arrow function can be used to bind one or more values or variables to the menu item's callback function.
443 | 444 |GUI, Threads, Thread, Critical, #NoTrayIcon, Functions, Return, SetTimer
446 | 447 |Adds a new menu item to the bottom of the tray icon menu.
451 |A_TrayMenu.Add() ; Creates a separator line. 452 | A_TrayMenu.Add("Item1", MenuHandler) ; Creates a new menu item. 453 | Persistent 454 | 455 | MenuHandler(ItemName, ItemPos, MyMenu) { 456 | MsgBox "You selected " ItemName " (position " ItemPos ")" 457 | }458 |
Creates a popup menu that is displayed when the user presses a hotkey.
462 |; Create the popup menu by adding some items to it. 463 | MyMenu := Menu() 464 | MyMenu.Add("Item 1", MenuHandler) 465 | MyMenu.Add("Item 2", MenuHandler) 466 | MyMenu.Add() ; Add a separator line. 467 | 468 | ; Create another menu destined to become a submenu of the above menu. 469 | Submenu1 := Menu() 470 | Submenu1.Add("Item A", MenuHandler) 471 | Submenu1.Add("Item B", MenuHandler) 472 | 473 | ; Create a submenu in the first menu (a right-arrow indicator). When the user selects it, the second menu is displayed. 474 | MyMenu.Add("My Submenu", Submenu1) 475 | 476 | MyMenu.Add() ; Add a separator line below the submenu. 477 | MyMenu.Add("Item 3", MenuHandler) ; Add another menu item beneath the submenu. 478 | 479 | MenuHandler(Item, *) { 480 | MsgBox("You selected " Item) 481 | } 482 | 483 | #z::MyMenu.Show() ; i.e. press the Win-Z hotkey to show the menu.484 |
Demonstrates some of the various menu object members.
488 |#SingleInstance 489 | Persistent 490 | Tray := A_TrayMenu ; For convenience. 491 | Tray.Delete() ; Delete the standard items. 492 | Tray.Add() ; separator 493 | Tray.Add("TestToggleCheck", TestToggleCheck) 494 | Tray.Add("TestToggleEnable", TestToggleEnable) 495 | Tray.Add("TestDefault", TestDefault) 496 | Tray.Add("TestAddStandard", TestAddStandard) 497 | Tray.Add("TestDelete", TestDelete) 498 | Tray.Add("TestDeleteAll", TestDeleteAll) 499 | Tray.Add("TestRename", TestRename) 500 | Tray.Add("Test", Test) 501 | 502 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 503 | 504 | TestToggleCheck(*) 505 | { 506 | Tray.ToggleCheck("TestToggleCheck") 507 | Tray.Enable("TestToggleEnable") ; Also enables the next test since it can't undo the disabling of itself. 508 | Tray.Add("TestDelete", TestDelete) ; Similar to above. 509 | } 510 | 511 | TestToggleEnable(*) 512 | { 513 | Tray.ToggleEnable("TestToggleEnable") 514 | } 515 | 516 | TestDefault(*) 517 | { 518 | if Tray.Default = "TestDefault" 519 | Tray.Default := "" 520 | else 521 | Tray.Default := "TestDefault" 522 | } 523 | 524 | TestAddStandard(*) 525 | { 526 | Tray.AddStandard() 527 | } 528 | 529 | TestDelete(*) 530 | { 531 | Tray.Delete("TestDelete") 532 | } 533 | 534 | TestDeleteAll(*) 535 | { 536 | Tray.Delete() 537 | } 538 | 539 | TestRename(*) 540 | { 541 | static OldName := "", NewName := "" 542 | if NewName != "renamed" 543 | { 544 | OldName := "TestRename" 545 | NewName := "renamed" 546 | } 547 | else 548 | { 549 | OldName := "renamed" 550 | NewName := "TestRename" 551 | } 552 | Tray.Rename(OldName, NewName) 553 | } 554 | 555 | Test(Item, *) 556 | { 557 | MsgBox("You selected " Item) 558 | }559 |
Demonstrates how to add icons to menu items.
563 |FileMenu := Menu() 564 | FileMenu.Add("Script Icon", MenuHandler) 565 | FileMenu.Add("Suspend Icon", MenuHandler) 566 | FileMenu.Add("Pause Icon", MenuHandler) 567 | FileMenu.SetIcon("Script Icon", A_AhkPath, 2) ; 2nd icon group from the file 568 | FileMenu.SetIcon("Suspend Icon", A_AhkPath, -206) ; icon with resource ID 206 569 | FileMenu.SetIcon("Pause Icon", A_AhkPath, -207) ; icon with resource ID 207 570 | MyMenuBar := MenuBar() 571 | MyMenuBar.Add("&File", FileMenu) 572 | MyGui := Gui() 573 | MyGui.MenuBar := MyMenuBar 574 | MyGui.Add("Button",, "Exit This Example").OnEvent("Click", (*) => WinClose()) 575 | MyGui.Show() 576 | 577 | MenuHandler(*) { 578 | ; For this example, the menu items don't do anything. 579 | }580 |
Reports the number of items in a menu and the ID of the last item.
584 |585 | MyMenu := Menu() 586 | MyMenu.Add("Item 1", NoAction) 587 | MyMenu.Add("Item 2", NoAction) 588 | MyMenu.Add("Item B", NoAction) 589 | 590 | ; Retrieve the number of items in a menu. 591 | item_count := DllCall("GetMenuItemCount", "ptr", MyMenu.Handle) 592 | 593 | ; Retrieve the ID of the last item. 594 | last_id := DllCall("GetMenuItemID", "ptr", MyMenu.Handle, "int", item_count-1) 595 | 596 | MsgBox("MyMenu has " item_count " items, and its last item has ID " last_id) 597 | 598 | NoAction(*) { 599 | ; Do nothing. 600 | } 601 |602 |
Retrieves the Menu or MenuBar object corresponding to a Win32 menu handle.
17 | 18 |Menu := MenuFromHandle(Handle)
19 | Type: Integer
23 |A handle to a Win32 menu (of type HMENU
).
If the handle is invalid or does not correspond to a menu created by this script, the function returns an empty string.
29 | 30 |Win32 Menus, Menu/MenuBar object, Menu.Handle, Menu()
32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /docs/lib/MenuSelect.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Invokes a menu item from the menu bar of the specified window.
17 | 18 |MenuSelect WinTitle, WinText, Menu , SubMenu1, SubMenu2, SubMenu3, SubMenu4, SubMenu5, SubMenu6, ExcludeTitle, ExcludeText19 |
Type: String, Integer or Object
25 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
26 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
27 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
28 |Type: String
33 |The name (or a prefix of the name) of the top-level menu item, e.g. "File"
, "Edit"
, "View"
. It can also be the position of the desired menu item by using "1&"
to represent the first menu, "2&"
the second, and so on.
The search is case-insensitive according to the rules of the current user's locale, and stops at the first matching item. The use of ampersand (&) to indicate the underlined letter in a menu item is usually not necessary (i.e. "&File"
is the same as "File"
).
Known limitation: If the parameter contains an ampersand, it must match the item name exactly, including all non-literal ampersands (which are hidden or displayed as an underline). If the parameter does not contain an ampersand, all ampersands are ignored, including literal ones. For example, an item displayed as "a & b" may match a parameter value of a && b
or a b
.
Specify "0&"
to use the window's system menu.
Type: String
42 |The name of the menu item to select or its position. This can be omitted if the top-level item does not contain a menu (rare).
43 |Type: String
48 |If the previous submenu itself contains a menu, this is the name of the menu item inside, or its position.
49 |A TargetError is thrown if the window or control could not be found, or does not have a standard Win32 menu.
55 |A ValueError is thrown if a menu, submenu or menu item could not be found, or if the final menu parameter corresponds to a menu item which opens a submenu.
56 | 57 |For this function to work, the target window need not be active. However, some windows might need to be in a non-minimized state.
59 |This function will not work with applications that use non-standard menu bars. Examples include Microsoft Outlook and Outlook Express, which use disguised toolbars for their menu bars. In these cases, consider using ControlSend or PostMessage, which should be able to interact with some of these non-standard menu bars.
60 |The menu name parameters can also specify positions. This method exists to support menus that don't contain text (perhaps because they contain pictures of text rather than actual text). Position 1& is the first menu item (e.g. the File menu), position 2& is the second menu item (e.g. the Edit menu), and so on. Menu separator lines count as menu items for the purpose of determining the position of a menu item.
61 | 62 |Menu can be "0&"
to select an item within the window's system menu, which typically appears when the user presses Alt+Space or clicks on the icon in the window's title bar. For example:
; Paste a command into cmd.exe without activating the window. 65 | A_Clipboard := "echo Hello, world!`r" 66 | MenuSelect "ahk_exe cmd.exe",, "0&", "Edit", "Paste"67 |
Caution: Use this only on windows which have custom items in their system menu.
68 |If the window does not already have a custom system menu, a copy of the standard system menu will be created and assigned to the target window as a side effect. This copy is destroyed by the system when the script exits, leaving other scripts unable to access it. Therefore, avoid using 0& for the standard items which appear on all windows. Instead, post the WM_SYSCOMMAND message directly. For example:
69 |; Like [WinMinimize "A"], but also play the system sound for minimizing. 70 | WM_SYSCOMMAND := 0x0112 71 | SC_MINIMIZE := 0xF020 72 | PostMessage WM_SYSCOMMAND, SC_MINIMIZE, 0,, "A"73 | 74 |
Selects File -> Open
in Notepad. This example may fail on Windows 11 or later, as it requires the classic version of Notepad.
MenuSelect "Untitled - Notepad",, "File", "Open"80 |
Same as above except it is done by position instead of name. On Windows 10, 2& must be replaced with 3& due to the new "New Window" menu item. This example may fail on Windows 11 or later, as it requires the classic version of Notepad.
84 |MenuSelect "Untitled - Notepad",, "1&", "2&"85 |
Selects View -> Lines most recently executed
in the main window.
WinShow "ahk_class AutoHotkey" 90 | MenuSelect "ahk_class AutoHotkey",, "View", "Lines most recently executed"91 |
Functions for retrieving screen resolution and multi-monitor info. Click on a function name for details.
17 |Function | 20 |Description | 21 |
---|---|
MonitorGet | 24 |Checks if the specified monitor exists and optionally retrieves its bounding coordinates. | 25 |
MonitorGetCount | 28 |Returns the total number of monitors. | 29 |
MonitorGetName | 32 |Returns the operating system's name of the specified monitor. | 33 |
MonitorGetPrimary | 36 |Returns the number of the primary monitor. | 37 |
MonitorGetWorkArea | 40 |Checks if the specified monitor exists and optionally retrieves the bounding coordinates of its working area. | 41 |
The built-in variables A_ScreenWidth and A_ScreenHeight contain the dimensions of the primary monitor, in pixels.
46 |SysGet can be used to retrieve the bounding rectangle of all display monitors. For example, this retrieves the width and height of the virtual screen:
47 |MsgBox SysGet(78) " x " SysGet(79)48 | 49 |
DllCall, Win functions, SysGet
51 | 52 |Displays info about each monitor.
55 |MonitorCount := MonitorGetCount() 56 | MonitorPrimary := MonitorGetPrimary() 57 | MsgBox "Monitor Count:`t" MonitorCount "`nPrimary Monitor:`t" MonitorPrimary 58 | Loop MonitorCount 59 | { 60 | MonitorGet A_Index, &L, &T, &R, &B 61 | MonitorGetWorkArea A_Index, &WL, &WT, &WR, &WB 62 | MsgBox 63 | ( 64 | "Monitor:`t#" A_Index " 65 | Name:`t" MonitorGetName(A_Index) " 66 | Left:`t" L " (" WL " work) 67 | Top:`t" T " (" WT " work) 68 | Right:`t" R " (" WR " work) 69 | Bottom:`t" B " (" WB " work)" 70 | ) 71 | }72 |
Checks if the specified monitor exists and optionally retrieves its bounding coordinates.
17 | 18 |ActualN := MonitorGet(N, &Left, &Top, &Right, &Bottom)19 | 20 |
Type: Integer
25 |If omitted, the primary monitor will be used. Otherwise, specify the monitor number, between 1 and the number returned by MonitorGetCount.
26 |Type: VarRef
31 |If omitted, the corresponding value will not be stored. Otherwise, specify references to the output variables in which to store the bounding coordinates, in pixels.
32 |Type: Integer
37 |This function returns the monitor number (the same as N unless N was omitted).
38 | 39 |On failure, an exception is thrown and the output variables are not modified.
41 | 42 |The built-in variables A_ScreenWidth and A_ScreenHeight contain the dimensions of the primary monitor, in pixels.
44 |SysGet can be used to retrieve the bounding rectangle of all display monitors. For example, this retrieves the width and height of the virtual screen:
45 |MsgBox SysGet(78) " x " SysGet(79)46 | 47 |
MonitorGetWorkArea, SysGet, Monitor functions
49 | 50 |Shows the bounding coordinates of the second monitor in a message box.
53 |try 54 | { 55 | MonitorGet 2, &Left, &Top, &Right, &Bottom 56 | MsgBox "Left: " Left " -- Top: " Top " -- Right: " Right " -- Bottom: " Bottom 57 | } 58 | catch 59 | MsgBox "Monitor 2 doesn't exist or an error occurred."60 |
See example #1 on the Monitor Functions page for another demonstration of this function.
63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /docs/lib/MonitorGetCount.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the total number of monitors.
17 | 18 |Count := MonitorGetCount()
19 |
20 | This function has no parameters.
22 | 23 |Type: Integer
25 |This function returns the total number of monitors.
26 | 27 |Unlike the SM_CMONITORS system property retrieved via SysGet(80)
, the return value includes all monitors, even those not being used as part of the desktop.
See example #1 on the Monitor Functions page for a demonstration of this function.
35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /docs/lib/MonitorGetName.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the operating system's name of the specified monitor.
17 | 18 |Name := MonitorGetName(N)19 | 20 |
Type: Integer
25 |If omitted, the primary monitor will be used. Otherwise, specify the monitor number, between 1 and the number returned by MonitorGetCount.
26 |Type: String
31 |This function returns the operating system's name for the specified monitor.
32 | 33 |An exception is thrown on failure.
35 | 36 |See example #1 on the Monitor Functions page for a demonstration of this function.
41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /docs/lib/MonitorGetPrimary.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the number of the primary monitor.
17 | 18 |Primary := MonitorGetPrimary()
19 |
20 | This function has no parameters.
22 | 23 |Type: Integer
25 |This function returns the number of the primary monitor. In a single-monitor system, this will be always 1.
26 | 27 |See example #1 on the Monitor Functions page for a demonstration of this function.
32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /docs/lib/MonitorGetWorkArea.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Checks if the specified monitor exists and optionally retrieves the bounding coordinates of its working area.
17 | 18 |ActualN := MonitorGetWorkArea(N, &Left, &Top, &Right, &Bottom)19 | 20 |
Type: Integer
25 |If omitted, the primary monitor will be used. Otherwise, specify the monitor number, between 1 and the number returned by MonitorGetCount.
26 |Type: VarRef
31 |If omitted, the corresponding value will not be stored. Otherwise, specify references to the output variables in which to store the bounding coordinates of the working area, in pixels.
32 |Type: Integer
37 |This function returns the monitor number (the same as N unless N was omitted).
38 | 39 |On failure, an exception is thrown and the output variables are not modified.
41 | 42 |The working area of a monitor excludes the area occupied by the taskbar and other registered desktop toolbars.
44 | 45 |MonitorGet, SysGet, Monitor functions
47 | 48 |See example #1 on the Monitor Functions page for a demonstration of this function.
50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /docs/lib/MouseClick.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Clicks or holds down a mouse button, or turns the mouse wheel. Note: The Click function is generally more flexible and easier to use.
16 | 17 |MouseClick WhichButton, X, Y, ClickCount, Speed, DownOrUp, Relative18 |
Type: String
24 |If blank or omitted, it defaults to Left (the left mouse button). Otherwise, specify the button to click or the rotate/push direction of the mouse wheel.
25 |Button: Left, Right, Middle (or just the first letter of each of these); or X1 (fourth button) or X2 (fifth button). For example: MouseClick "X1"
.
Left and Right correspond to the primary button and secondary button. If the user swaps the buttons via system settings, the physical positions of the buttons are swapped but the effect stays the same.
27 |Mouse wheel: Specify WheelUp or WU to turn the wheel upward (away from you); specify WheelDown or WD to turn the wheel downward (toward you). Specify WheelLeft (or WL) or WheelRight (or WR) to push the wheel left or right, respectively. ClickCount is the number of notches to turn the wheel.
28 |Type: Integer
33 |If omitted, the cursor's current position is used. Otherwise, specify the X and Y coordinates to which the mouse cursor is moved prior to clicking. Coordinates are relative to the active window's client area unless CoordMode was used to change that.
34 |Type: Integer
39 |If omitted, it defaults to 1. Otherwise, specify the number of times to click the mouse button or turn the mouse wheel.
40 |Type: Integer
45 |If omitted, the default speed (as set by SetDefaultMouseSpeed or 2 otherwise) will be used. Otherwise, specify the speed to move the mouse in the range 0 (fastest) to 100 (slowest). A speed of 0 will move the mouse instantly.
46 |Speed is ignored for the modes SendInput and SendPlay; they move the mouse instantaneously (though SetMouseDelay has a mode that applies to SendPlay). To visually move the mouse more slowly -- such as a script that performs a demonstration for an audience -- use SendEvent "{Click 100 200}"
or SendMode "Event"
(optionally in conjuction with BlockInput).
Type: String
52 |If blank or omitted, each click consists of a down-event followed by an up-event. Otherwise, specify one of the following letters:
53 |D: Press the mouse button down but do not release it (i.e. generate a down-event).
54 |U: Release the mouse button (i.e. generate an up-event).
55 |Type: String
60 |If blank or omitted, the X and Y coordinates will be used for absolute positioning. Otherwise, specify the following letter:
61 |R: The X and Y coordinates will be treated as offsets from the current mouse position. In other words, the cursor will be moved from its current position by X pixels to the right (left if negative) and Y pixels down (up if negative).
62 |This function uses the sending method set by SendMode.
68 |The Click function is recommended over MouseClick because it is generally easier to use. However, MouseClick supports the Speed parameter, whereas adjusting the speed of movement by Click requires the use of SetDefaultMouseSpeed.
69 |To perform a shift-click or control-click, use the Send function before and after the operation as shown in these examples:
70 |; Example #1: 71 | Send "{Control down}" 72 | MouseClick "left", 55, 233 73 | Send "{Control up}"74 |
75 | ; Example #2: 76 | Send "{Shift down}" 77 | MouseClick "left", 55, 233 78 | Send "{Shift up}"79 |
The SendPlay mode is able to successfully generate mouse events in a broader variety of games than the other modes. In addition, some applications and games may have trouble tracking the mouse if it moves too quickly. The Speed parameter or SetDefaultMouseSpeed can be used to reduce the speed (in SendEvent mode only).
80 |Some applications do not obey a ClickCount higher than 1 for the mouse wheel. For them, use a Loop such as the following:
81 |Loop 5 82 | MouseClick "WheelUp"83 |
The BlockInput function can be used to prevent any physical mouse activity by the user from disrupting the simulated mouse events produced by the mouse functions. However, this is generally not needed for the modes SendInput and SendPlay because they automatically postpone the user's physical mouse activity until afterward.
84 |There is an automatic delay after every click-down and click-up of the mouse (except for SendInput mode and for turning the mouse wheel). Use SetMouseDelay to change the length of the delay.
85 |CoordMode, SendMode, SetDefaultMouseSpeed, SetMouseDelay, Click, MouseClickDrag, MouseGetPos, MouseMove, ControlClick, BlockInput
87 |Double-clicks at the current mouse position.
90 |MouseClick "left" 91 | MouseClick "left"92 |
Moves the mouse cursor to a specific position, then right-clicks once.
101 |MouseClick "right", 200, 300102 |
Simulates the turning of the mouse wheel.
106 |#up::MouseClick "WheelUp",,, 2 ; Turn it by two notches. 107 | #down::MouseClick "WheelDown",,, 2108 |
Clicks and holds the specified mouse button, moves the mouse to the destination coordinates, then releases the button.
16 | 17 |MouseClickDrag WhichButton, X1, Y1, X2, Y2 , Speed, Relative18 |
Type: String
24 |If blank or omitted, it defaults to Left (the left mouse button). Otherwise, specify Left, Right, Middle (or just the first letter of each of these); or X1 (fourth button) or X2 (fifth button). For example: MouseClickDrag "X1", 0, 0, 10, 10
.
Left and Right correspond to the primary button and secondary button. If the user swaps the buttons via system settings, the physical positions of the buttons are swapped but the effect stays the same.
26 |Type: Integer
31 |Specify the X and Y coordinates of the drag's starting position (the mouse will be moved to these coordinates right before the drag is started). Coordinates are relative to the active window's client area unless CoordMode was used to change that.
32 |[v2.0.7+]: If both X1 and Y1 are omitted, the mouse cursor's current position is used. Due to a bug, X1 and Y1 were mandatory in previous versions.
33 |Type: Integer
38 |The X and Y coordinates to drag the mouse to (that is, while the button is held down). Coordinates are relative to the active window's client area unless CoordMode was used to change that.
39 |Type: Integer
44 |If omitted, the default speed (as set by SetDefaultMouseSpeed or 2 otherwise) will be used. Otherwise, specify the speed to move the mouse in the range 0 (fastest) to 100 (slowest). A speed of 0 will move the mouse instantly.
45 |Speed is ignored for the modes SendInput and SendPlay; they move the mouse instantaneously (though SetMouseDelay has a mode that applies to SendPlay). To visually move the mouse more slowly -- such as a script that performs a demonstration for an audience -- use SendEvent "{Click 100 200}"
or SendMode "Event"
(optionally in conjuction with BlockInput).
Type: String
51 |If blank or omitted, the X and Y coordinates will be used for absolute positioning. Otherwise, specify the following letter:
52 |R: The X1 and Y1 coordinates will be treated as offsets from the current mouse position. In other words, the cursor will be moved from its current position by X1 pixels to the right (left if negative) and Y1 pixels down (up if negative). Similarly, the X2 and Y2 coordinates will be treated as offsets from the X1 and Y1 coordinates. For example, the following would first move the cursor down and to the right by 5 pixels from its starting position, and then drag it from that position down and to the right by 10 pixels: MouseClickDrag "Left", 5, 5, 10, 10, , "R"
.
This function uses the sending method set by SendMode.
59 |Dragging can also be done via the various Send functions, which is more flexible because the mode can be specified via the function name. For example:
60 |SendEvent "{Click 6 52 Down}{click 45 52 Up}"61 |
Another advantage of the method above is that unlike MouseClickDrag, it automatically compensates when the user has swapped the left and right mouse buttons via the system's control panel.
62 |The SendPlay mode is able to successfully generate mouse events in a broader variety of games than the other modes. However, dragging via SendPlay might not work in RichEdit controls (and possibly others) such as those of WordPad and Metapad.
63 |Some applications and games may have trouble tracking the mouse if it moves too quickly. The Speed parameter or SetDefaultMouseSpeed can be used to reduce the speed (in SendEvent mode only).
64 |The BlockInput function can be used to prevent any physical mouse activity by the user from disrupting the simulated mouse events produced by the mouse functions. However, this is generally not needed for the modes SendInput and SendPlay because they automatically postpone the user's physical mouse activity until afterward.
65 |There is an automatic delay after every click-down and click-up of the mouse (except for SendInput mode). This delay also occurs after the movement of the mouse during the drag operation. Use SetMouseDelay to change the length of the delay.
66 |CoordMode, SendMode, SetDefaultMouseSpeed, SetMouseDelay, Click, MouseClick, MouseGetPos, MouseMove, BlockInput
68 |Clicks and holds the left mouse button, moves the mouse cursor to the destination coordinates, then releases the button.
71 |MouseClickDrag "left", 0, 200, 600, 40072 |
Opens MS Paint and draws a little house.
76 |Run "mspaint.exe" 77 | if !WinWaitActive("ahk_class MSPaintApp",, 2) 78 | return 79 | MouseClickDrag "L", 150, 450, 150, 350 80 | MouseClickDrag "L", 150, 350, 200, 300 81 | MouseClickDrag "L", 200, 300, 250, 350 82 | MouseClickDrag "L", 250, 350, 150, 350 83 | MouseClickDrag "L", 150, 350, 250, 450 84 | MouseClickDrag "L", 250, 450, 250, 350 85 | MouseClickDrag "L", 250, 350, 150, 450 86 | MouseClickDrag "L", 150, 450, 250, 45087 |
Retrieves the current position of the mouse cursor, and optionally which window and control it is hovering over.
16 | 17 |MouseGetPos &OutputVarX, &OutputVarY, &OutputVarWin, &OutputVarControl, Flag18 |
Type: VarRef
24 |If omitted, the corresponding value will not be stored. Otherwise, specify references to the output variables in which to store the X and Y coordinates. The retrieved coordinates are relative to the active window's client area unless CoordMode was used to change to screen coordinates.
25 |Type: VarRef
30 |If omitted, the corresponding value will not be stored. Otherwise, specify a reference to the output variable in which to store the unique ID number of the window under the mouse cursor. If the window cannot be determined, this variable will be made blank.
31 |The window does not have to be active to be detected. Hidden windows cannot be detected.
32 |Type: VarRef
37 |If omitted, the corresponding value will not be stored. Otherwise, specify a reference to the output variable in which to store the name (ClassNN) of the control under the mouse cursor. If the control cannot be determined, this variable will be made blank.
38 |The names of controls should always match those shown by the Window Spy. The window under the mouse cursor does not have to be active for a control to be detected.
39 |Type: Integer
44 |If omitted, it defaults to 0, meaning the function uses the default method to determine OutputVarControl and stores the control's ClassNN. Otherwise, specify a combination (sum) of the following numbers:
45 |1: Uses a simpler method to determine OutputVarControl. This method correctly retrieves the active/topmost child window of an Multiple Document Interface (MDI) application such as SysEdit or TextPad. However, it is less accurate for other purposes such as detecting controls inside a GroupBox control.
46 |2: Stores the control's HWND in OutputVarControl rather than the control's ClassNN.
47 |For example, to put both options into effect, the Flag parameter must be set to 3.
48 |Any of the output variables may be omitted if the corresponding information is not needed.
54 |On systems with multiple screens which have different DPI settings, the returned position may be different than expected due to OS DPI scaling.
55 | 56 |CoordMode, Win functions, SetDefaultMouseSpeed, Click
58 | 59 |Reports the position of the mouse cursor.
62 |MouseGetPos &xpos, &ypos 63 | MsgBox "The cursor is at X" xpos " Y" ypos64 |
Shows the HWND, class name, title and controls of the window currently under the mouse cursor.
68 |SetTimer WatchCursor, 100 69 | 70 | WatchCursor() 71 | { 72 | MouseGetPos , , &id, &control 73 | ToolTip 74 | ( 75 | "ahk_id " id " 76 | ahk_class " WinGetClass(id) " 77 | " WinGetTitle(id) " 78 | Control: " control 79 | ) 80 | }81 |
Moves the mouse cursor.
16 | 17 |MouseMove X, Y , Speed, Relative18 |
Type: Integer
24 |The X and Y coordinates to move the mouse to. Coordinates are relative to the active window's client area unless CoordMode was used to change that.
25 |Type: Integer
30 |If omitted, the default speed (as set by SetDefaultMouseSpeed or 2 otherwise) will be used. Otherwise, specify the speed to move the mouse in the range 0 (fastest) to 100 (slowest). A speed of 0 will move the mouse instantly.
31 |Speed is ignored for the modes SendInput and SendPlay; they move the mouse instantaneously (though SetMouseDelay has a mode that applies to SendPlay). To visually move the mouse more slowly -- such as a script that performs a demonstration for an audience -- use SendEvent "{Click 100 200}"
or SendMode "Event"
(optionally in conjuction with BlockInput).
Type: String
37 |If blank or omitted, the X and Y coordinates will be used for absolute positioning. Otherwise, specify the following letter:
38 |R: The X and Y coordinates will be treated as offsets from the current mouse position. In other words, the cursor will be moved from its current position by X pixels to the right (left if negative) and Y pixels down (up if negative).
39 |This function uses the sending method set by SendMode.
45 |The SendPlay mode is able to successfully generate mouse events in a broader variety of games than the other modes. In addition, some applications and games may have trouble tracking the mouse if it moves too quickly. The Speed parameter or SetDefaultMouseSpeed can be used to reduce the speed (in SendEvent mode only).
46 |The BlockInput function can be used to prevent any physical mouse activity by the user from disrupting the simulated mouse events produced by the mouse functions. However, this is generally not needed for the modes SendInput and SendPlay because they automatically postpone the user's physical mouse activity until afterward.
47 |There is an automatic delay after every movement of the mouse (except for SendInput mode). Use SetMouseDelay to change the length of the delay.
48 |The following is an alternate way to move the mouse cursor that may work better in certain multi-monitor configurations:
49 |DllCall("SetCursorPos", "int", 100, "int", 400) ; The first number is the X-coordinate and the second is the Y (relative to the screen).50 |
On a related note, the mouse cursor can be temporarily hidden via the hide-cursor example.
51 |CoordMode, SendMode, SetDefaultMouseSpeed, SetMouseDelay, Click, MouseClick, MouseClickDrag, MouseGetPos, BlockInput
53 |Moves the mouse cursor slowly (speed 50 vs. 2) by 20 pixels to the right and 30 pixels down from its current location.
61 |MouseMove 20, 30, 50, "R"62 |
Displays the specified text in a small window containing one or more buttons (such as Yes and No).
24 | 25 |MsgBox Text, Title, Options 26 | Result := MsgBox(Text, Title, Options)27 |
Type: String
33 |If omitted and "OK" is the only button present, it defaults to the string "Press OK to continue.". If omitted in any other case, it defaults to an empty string. Otherwise, specify the text to display inside the message box.
34 |Escape sequences can be used to denote special characters. For example, `n indicates a linefeed character, which ends the current line and begins a new one. Thus, using text1`n`ntext2
would create a blank line between text1 and text2.
If Text is long, it can be broken up into several shorter lines by means of a continuation section, which might improve readability and maintainability.
36 |Type: String
41 |If omitted, it defaults to the current value of A_ScriptName. Otherwise, specify the title of the message box.
42 |Type: String
47 |If blank or omitted, it defaults to 0 (only an OK button is displayed). Otherwise, specify a combination (sum) of values or a string of one or more options from the tables below to indicate the type of message box and the possible button combinations.
48 |In addition, zero or more of the following options can be specified:
49 |Owner: To specify an owner window for the message box, use the word Owner followed immediately by a HWND (window ID).
50 |T: Timeout. To have the message box close automatically if the user has not closed it within a specified time, use the letter T followed by the timeout in seconds, which can contain a decimal point. If this value exceeds 2147483 (24.8 days), it will be set to 2147483. If the message box times out, the return value is the word Timeout.
51 |The Options parameter can be either a combination (sum) of numeric values from the following groups, which is passed directly to the operating system's MessageBox function, or a string of zero or more case-insensitive options separated by at least one space or tab. One or more numeric options may also be included in the string.
57 | 58 |To indicate the buttons displayed in the message box, add one of the following values:
60 |Function | 63 |Dec | 64 |Hex | 65 |String | 66 |
---|---|---|---|
OK | 69 |0 | 70 |0x0 | 71 |OK or O |
72 |
OK, Cancel | 75 |1 | 76 |0x1 | 77 |OKCancel , O/C or OC |
78 |
Abort, Retry, Ignore | 81 |2 | 82 |0x2 | 83 |AbortRetryIgnore , A/R/I or ARI |
84 |
Yes, No, Cancel | 87 |3 | 88 |0x3 | 89 |YesNoCancel , Y/N/C or YNC |
90 |
Yes, No | 93 |4 | 94 |0x4 | 95 |YesNo , Y/N or YN |
96 |
Retry, Cancel | 99 |5 | 100 |0x5 | 101 |RetryCancel , R/C or RC |
102 |
Cancel, Try Again, Continue | 105 |6 | 106 |0x6 | 107 |CancelTryAgainContinue , C/T/C or CTC |
108 |
To display an icon in the message box, add one of the following values:
113 |Function | 116 |Dec | 117 |Hex | 118 |String | 119 |
---|---|---|---|
Icon Hand (stop/error) | 122 |16 | 123 |0x10 | 124 |Iconx |
125 |
Icon Question | 128 |32 | 129 |0x20 | 130 |Icon? |
131 |
Icon Exclamation | 134 |48 | 135 |0x30 | 136 |Icon! |
137 |
Icon Asterisk (info) | 140 |64 | 141 |0x40 | 142 |Iconi |
143 |
To indicate the default button, add one of the following values:
148 |Function | 151 |Dec | 152 |Hex | 153 |String | 154 |
---|---|---|---|
Makes the 2nd button the default | 157 |256 | 158 |0x100 | 159 |Default2 |
160 |
Makes the 3rd button the default | 163 |512 | 164 |0x200 | 165 |Default3 |
166 |
Makes the 4th button the default (requires the Help button to be present) |
169 | 768 | 170 |0x300 | 171 |Default4 |
172 |
To indicate the modality of the dialog box, add one of the following values:
177 |Function | 180 |Dec | 181 |Hex | 182 |String | 183 |
---|---|---|---|
System Modal (always on top) | 186 |4096 | 187 |0x1000 | 188 |N/A | 189 |
Task Modal | 192 |8192 | 193 |0x2000 | 194 |N/A | 195 |
Always-on-top (style WS_EX_TOPMOST) (like System Modal but omits title bar icon) |
198 | 262144 | 199 |0x40000 | 200 |N/A | 201 |
To specify other options, add one or more of the following values:
206 |Function | 209 |Dec | 210 |Hex | 211 |String | 212 |
---|---|---|---|
Adds a Help button (see remarks below) | 215 |16384 | 216 |0x4000 | 217 |N/A | 218 | 219 |
Makes the text right-justified | 222 |524288 | 223 |0x80000 | 224 |N/A | 225 |
Right-to-left reading order for Hebrew/Arabic | 228 |1048576 | 229 |0x100000 | 230 |N/A | 231 |
Type: String
236 |This function returns one of the following strings to represent which button the user pressed:
237 |If the dialog could not be displayed, an empty string is returned. This typically only occurs as a result of the MsgBox limit being reached, but may occur in other unusual cases.
250 | 251 |An Error is thrown on failure, such as if the options are invalid, the MsgBox limit has been reached, or the message box could not be displayed for some other reason.
253 | 254 |A message box usually looks like this:
256 | 257 |To determine which button the user pressed, use the function's return value. For example:
258 |Result := MsgBox("Would you like to continue? (press Yes or No)",, "YesNo") 259 | if Result = "Yes" 260 | MsgBox "You pressed Yes." 261 | else 262 | MsgBox "You pressed No." 263 | 264 | if MsgBox("Retry or cancel?",, "R/C") = "Retry" 265 | MsgBox("You pressed Retry.")266 |
To customize the names of the buttons, see Changing MsgBox's Button Names.
267 |Note: Pressing Ctrl+C while a message box is active will copy its text to the clipboard. This applies to all message boxes, not just those produced by AutoHotkey.
268 |Using MsgBox with GUI windows: A GUI window may display a modal message box by means of the OwnDialogs option. A modal message box prevents the user from interacting with the GUI window until the message box is dismissed. In such a case, it is not necessary to specify the System Modal or Task Modal options from the table above.
269 |When the OwnDialogs option is not in effect, the Task Modal option (8192) can be used to disable all the script's windows until the user dismisses the message box.
270 |If the OwnerHWND
option is specified, it takes precedence over any other setting. HWND can be the HWND of any window, even one not owned by the script.
The Help button: When the Help button option (16384) is present in Options, pressing the Help button will have no effect unless both of the following are true:
272 |OnMessage(0x0053, WM_HELP)
. When the WM_HELP function is called, it may guide the user by means such as showing another window or message box.The Close button (in the message box's title bar): Since the message box is a built-in feature of the operating system, its X button is enabled only when certain buttons are present. If there is only an OK button, clicking the X button is the same as pressing OK. Otherwise, the X button is disabled unless there is a Cancel button, in which case clicking the X is the same as pressing Cancel.
277 |Maximum 7 ongoing calls: The thread displaying a message box can typically be interrupted, allowing the new thread to display its own message box before the previous call returns. A maximum of 7 ongoing calls to MsgBox are permitted, but any calls beyond the 7th cause an Error to be thrown. Note that a call to MsgBox in an interrupted thread cannot return until the thread is resumed.
278 | 279 |InputBox, FileSelect, DirSelect, ToolTip, Gui object
281 |Shows a message box with specific text. A quick and easy way to show information. The user can press an OK button to close the message box and continue execution.
284 |MsgBox "This is a string."285 |
Shows a message box with specific text and a title.
289 |MsgBox "This MsgBox has a custom title.", "A Custom Title"290 |
Shows a message box with default text. Mainly useful for debugging purposes, for example to quickly set a breakpoint in the script.
294 |MsgBox ; "Press OK to continue."295 |
Shows a message box with specific text, a title and an info icon. Besides, a continuation section is used to display the multi-line text in a more clear manner.
299 |300 | MsgBox " 301 | ( 302 | The first parameter is displayed as the message. 303 | The second parameter becomes the window title. 304 | The third parameter determines the type of message box. 305 | )", "Window Title", "iconi" 306 |307 |
Use the return value to determine which button the user pressed in the message box. Note that in this case the MsgBox function call must be specified with parentheses.
311 |result := MsgBox("Do you want to continue? (Press YES or NO)",, "YesNo") 312 | if (result = "No") 313 | return314 |
Use the T (timeout) option to automatically close the message box after a certain number of seconds.
318 |result := MsgBox("This MsgBox will time out in 5 seconds. Continue?",, "Y/N T5") 319 | if (result = "Timeout") 320 | MsgBox "You didn't press YES or NO within the 5-second period." 321 | else if (result = "No") 322 | return323 |
Include a variable or sub-expression in the message. See also: Concatenation
327 |328 | var := 10 329 | MsgBox "The initial value is: " var 330 | MsgBox "The result is: " var * 2 331 | MsgBox Format("The result is: {1}", var * 2) 332 |333 |
Returns the binary number stored at the specified address+offset.
15 |Number := NumGet(Source, Offset, Type) 16 | Number := NumGet(Source, Type)17 | 18 |
A Buffer-like object or memory address.
25 |Any object which implements Ptr and Size properties may be used, but this function is optimized for the native Buffer object. Passing an object with these properties ensures that the function does not read memory from an invalid location; doing so could cause crashes or other unpredictable behaviour.
26 |Type: Integer
31 |If blank or omitted (or when using 2-parameter mode), it defaults to 0. Otherwise, specify an offset in bytes which is added to Source to determine the source address.
32 |Type: String
37 |One of the following strings: UInt, Int, Int64, Short, UShort, Char, UChar, Double, Float, Ptr or UPtr
38 |Unsigned 64-bit integers are not supported, as AutoHotkey's native integer type is Int64. Therefore, to work with numbers greater than or equal to 0x8000000000000000, omit the U prefix and interpret any negative values as large integers. For example, a value of -1 as an Int64 is really 0xFFFFFFFFFFFFFFFF if it is intended to be a UInt64. On 64-bit builds, UPtr is equivalent to Int64.
39 |For details see DllCall Types.
40 |This function returns the binary number at the specified address+offset.
47 | 48 |If only two parameters are present, the second parameter must be Type. For example, NumGet(var, "int")
is valid.
An exception may be thrown if the source address is invalid. However, some invalid addresses cannot be detected as such and may cause unpredictable behaviour. Passing a Buffer object instead of an address ensures that the source address can always be validated.
51 | 52 |NumPut, DllCall, Buffer object, VarSetStrCapacity
54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /docs/lib/NumPut.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Stores one or more numbers in binary format at the specified address+offset.
15 |NumPut Type, Number, Type2, Number2, ... Target , Offset16 | 17 |
Type: String
23 |One of the following strings: UInt, UInt64, Int, Int64, Short, UShort, Char, UChar, Double, Float, Ptr or UPtr
24 |For all integer types, or when passing pure integers, signed vs. unsigned does not affect the result due to the use of two's complement to represent signed integers.
25 |For details see DllCall Types.
26 |Type: Integer
31 |The number to store.
32 |A Buffer-like object or memory address.
38 |Any object which implements Ptr and Size properties may be used, but this function is optimized for the native Buffer object. Passing an object with these properties ensures that the function does not write to an invalid memory location; doing so could cause crashes or other unpredictable behaviour.
39 |Type: Integer
44 |If omitted, it defaults to 0. Otherwise, specify an offset in bytes which is added to Target to determine the target address.
45 |Type: Integer
51 |This function returns the address to the right of the last item written. This can be used when writing a non-contiguous sequence of numbers, such as in a structure for use with DllCall, where some fields are not being set. However, in many cases it is simpler and more efficient to specify multiple Type, Number pairs instead. Passing the address back to NumPut is less safe than passing a Buffer-like object with an updated Offset.
52 | 53 |A sequence of numbers can be written by repeating Type and Number any number of times after the first Number. Each number is written at the next byte after the previous number, with no padding. When creating a structure for use with DllCall, be aware that some fields may need explicit padding added due to data alignment requirements.
55 |If an integer is too large to fit in the specified Type, its most significant bytes are ignored; e.g. NumPut("Char", 257, buf)
would store the number 1.
An exception may be thrown if the target address is invalid. However, some invalid addresses cannot be detected as such and may cause unpredictable behaviour. Passing a Buffer object instead of an address ensures that the target address can always be validated.
57 | 58 |NumGet, DllCall, Buffer object, VarSetStrCapacity
60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /docs/lib/Number.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Converts a numeric string to a pure integer or floating-point number.
16 |NumValue := Number(Value)
17 |
18 | This function returns the result of converting Value to a pure integer or floating-point number, or Value itself if it is already an Integer or Float value.
21 | 22 |If the value cannot be converted, a TypeError is thrown.
24 |To determine if a value can be converted to a number, use the IsNumber function.
25 |Number is actually a class, but can be called as a function. Value is Number
can be used to check whether a value is a pure number.
Type, Float, Integer, String, Values, Expressions, Is functions
29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /docs/lib/ObjAddRef.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Increments or decrements an object's reference count.
17 | 18 |NewRefCount := ObjAddRef(Ptr) 19 | NewRefCount := ObjRelease(Ptr)20 |
Type: Integer
26 |An unmanaged object pointer or COM interface pointer.
27 |Type: Integer
33 |These functions return the new reference count. This value should be used only for debugging purposes.
34 | 35 |Although the following articles discuss reference counting as it applies to COM, they cover some important concepts and rules which generally also apply to AutoHotkey objects: IUnknown::AddRef, IUnknown::Release, Reference Counting Rules.
38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /docs/lib/ObjBindMethod.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Creates a BoundFunc object which calls a method of a given object.
16 | 17 |BoundFunc := ObjBindMethod(Obj , Method, Params)18 | 19 |
Type: Object
25 |Any object.
26 |Type: String
31 |A method name. If omitted, the bound function calls Obj itself.
32 |Any number of parameters.
37 |For details and examples, see BoundFunc object.
43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /docs/lib/Object.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |class Object extends Any15 | 16 |
Object is the basic class from which other AutoHotkey object classes derive. Each instance of Object consists of a set of "own properties" and a base object, from which more properties are inherited. Objects also have methods, but these are just properties which can be called.
17 |There are value properties and dynamic properties. Value properties simply contain a value. Dynamic properties do not contain a value, but instead call an accessor function depending on how they are accessed (get, set or call).
18 |"Obj" is used below as a placeholder for any instance of the Object class.
19 |All instances of Object are based on Object.Prototype
, which is based on Any.Prototype
. In addition to the methods and property inherited from Any, Objects have the following predefined methods and properties.
Creates a new Object.
57 |Obj := Object()
58 | Obj := Object.Call()
59 | Returns a shallow copy of an object.
65 |Clone := Obj.Clone()
66 | Each property or method owned by the object is copied into the clone. Object references are copied (like with a normal assignment), not the objects themselves; in other words, if a property contains a reference to an object, the clone will contain a reference to the same object.
67 |Dynamic properties are copied, not invoked.
68 |The clone has the same base object as the original object.
69 |A TypeError is thrown if Obj is derived from an unsupported built-in type. This implementation of Clone supports Object, Class and Error objects. See also: Clone (Array), Clone (Map).
70 |Defines or modifies an own property.
74 |Obj := Obj.DefineProp(Name, Descriptor)
75 | Type: String
80 |The name of the property.
81 |Type: Object
85 |To define or modify a dynamic property, specify an object with one or more of the following own properties:
86 |Get: The function object to call when the property's value is retrieved.
87 |Set: The function object to call when the property is assigned a value. Its second parameter is the value being assigned.
88 |Call: The function object to call when the property is called.
89 |To define a value property, specify an object with the following own property:
90 |Value: Any value to assign to the property.
91 |Type: Object
95 |This method returns the target object.
96 |Defining a value property overwrites any existing value or accessor functions.
98 |Defining a dynamic property overwrites any existing value, but retains any existing accessor functions which aren't specified by the descriptor.
99 |If a dynamic property lacks any one of the accessor functions, behavior is inherited from a base object.
100 |this
. Note that a new value would overwrite any dynamic property in this
itself, and override any inherited accessor functions.As with methods, the first parameter of Get, Set or Call is this
(the target object). For Set, the second parameter is value
(the value being assigned). These parameters are defined automatically by method and property definitions within a class, but must be defined explicitly if using normal functions. Any other parameters passed by the caller are appended to the parameter list.
The MaxParams and IsVariadic properties of the function objects are evaluated to determine whether the property may accept parameters. If MaxParams is 1 for Get or 2 for Set and IsVariadic is false or undefined, the property cannot accept parameters; they are instead forwarded to the __Item property of the object returned by get.
108 |Removes an own property from an object.
112 |RemovedValue := Obj.DeleteProp(Name)
113 | Type: String
118 |A property name.
119 |Type: Any
123 |This method returns the value of the removed property (blank if none).
124 |Returns a descriptor for a given own property, compatible with DefineProp.
128 |Descriptor := Obj.GetOwnPropDesc(Name)
129 | Type: String
134 |A property name.
135 |Type: Object
139 |For a dynamic property, the return value is a new object with an own property for each accessor function: Get, Set, Call. Each property is present only if the corresponding accessor function is defined in Obj itself. For a value property, the return value is a new object with a property named Value. In such cases, Obj.GetOwnPropDesc(Name).Value == Obj.%Name%
.
Modifying the returned object has no effect on Obj unless DefineProp is called.
141 |A PropertyError is thrown if Obj does not own a property by that name. The script can determine whether a property is dynamic by checking not desc.HasProp("Value")
, where desc is the return value of GetOwnPropDesc.
Returns 1 (true) if an object owns a property by the specified name, otherwise 0 (false).
147 |HasOwnProp := Obj.HasOwnProp(Name)
148 | The default implementation of this method is also defined as a function: ObjHasOwnProp(Obj, Name)
.
Enumerates an object's own properties.
153 |For Name , Value in Obj.OwnProps()154 |
This method returns a new enumerator. The enumerator is typically passed directly to a for-loop, which calls the enumerator once for each iteration of the loop. Each call to the enumerator returns the next property name and/or value. The for-loop's variables correspond to the enumerator's parameters, which are:
155 |Type: String
159 |The property's name.
160 |Type: Any
164 |The property's value.
165 |If the property has a getter method, it is called to obtain the value (unless Value is omitted).
166 |Dynamic properties are included in the enumeration. However:
169 |Note: Properties defined by a method definition typically do not have a getter, so are skipped.
177 |To enumerate own properties without calling property getters, or to enumerate all properties regardless of type, pass only a single variable to the for-loop or enumerator. GetOwnPropDesc can be used to differentiate value properties from dynamic properties, while also retrieving the value or getter/setter/method.
184 |Methods are typically excluded from enumeration in the two-parameter mode, because evaluation of the property normally depends on whether the object has a corresponding getter or value, either in the same object or a base object. To avoid inconsistency when two variables are specified, OwnProps skips over own properties that have only a Call accessor function. For example:
185 |The default implementation of this method is also defined as a function: ObjOwnProps(Obj)
.
Retrieves or sets an object's base object.
196 |CurrentBaseObj := Obj.Base
197 | Obj.Base := NewBaseObj
198 | NewBaseObj must be an Object.
199 |If assigning the new base would change the native type of the object, an exception is thrown. An object's native type is decided by the nearest prototype object belonging to a built-in class, such as Object.Prototype
or Array.Prototype
. For example, an instance of Array must always derive from Array.Prototype
, either directly or indirectly.
Properties and methods are inherited from the base object dynamically, so changing an object's base also changes which inherited properties and methods are available.
201 |This property is inherited from Any; however, it can be set only for instances of Object.
202 |See also: ObjGetBase, ObjSetBase
203 |Sets an object's base object.
208 |ObjSetBase(Obj, BaseObj)
209 | No meta-functions or property functions are called. Overriding the Base property does not affect the behaviour of this function.
210 |An exception is thrown if Obj or BaseObj is of an incorrect type.
211 |See also: ObjGetBase, Base property
212 | 213 |Returns the number of properties owned by an object.
215 |Count := ObjOwnPropCount(Obj)
216 |
217 | Sets the current capacity of the object's internal array of own properties.
219 |MaxProps := ObjSetCapacity(Obj, MaxProps)
220 | Type: Integer
225 |The new capacity. If less than the current number of own properties, that number is used instead, and any unused space is freed.
226 |Type: Integer
230 |This function returns the new capacity.
231 |An exception is thrown if Obj is of an incorrect type.
233 | 234 |Returns the current capacity of the object's internal array of properties.
236 |MaxItems := ObjGetCapacity(Obj)
237 | An exception is thrown if Obj is of an incorrect type.
238 | 239 | 240 | 241 | -------------------------------------------------------------------------------- /docs/lib/OnClipboardChange.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Registers a function to be called automatically whenever the clipboard's content changes.
15 | 16 |OnClipboardChange Callback , AddRemove17 |
Type: Function Object
23 |The function to call.
24 |The callback accepts one parameter and can be defined as follows:
25 |MyCallback(DataType) { ...26 |
Although the name you give the parameter does not matter, it is assigned one of the following numbers:
27 |You can omit the callback's parameter if the corresponding information is not needed, but in this case an asterisk must be specified, e.g. MyCallback(*)
.
If this is the last or only callback, the return value is ignored. Otherwise, it can return a non-zero integer to prevent subsequent callbacks from being called.
34 |Type: Integer
39 |If omitted, it defaults to 1. Otherwise, specify one of the following numbers:
40 |If the clipboard changes while a callback is already running, that notification event is lost. If this is undesirable, use Critical. However, this will also buffer/defer other threads (such as the press of a hotkey) that occur while the OnClipboardChange thread is running.
51 |If the script itself changes the clipboard, the callbacks are typically not executed immediately; that is, statements immediately below the statement that changed the clipboard are likely to execute beforehand. To force the callbacks to execute immediately, use a short delay such as Sleep 20
after changing the clipboard.
A_Clipboard, OnExit, OnMessage, CallbackCreate
55 | 56 |Briefly displays a tooltip for each clipboard change.
59 |OnClipboardChange ClipChanged 60 | 61 | ClipChanged(DataType) { 62 | ToolTip "Clipboard data type: " DataType 63 | Sleep 1000 64 | ToolTip ; Turn off the tip. 65 | }66 |
Registers a function to be called automatically whenever an unhandled error occurs.
15 | 16 |OnError Callback , AddRemove17 | 18 |
Type: Function Object
24 |The function to call.
25 |The callback accepts two parameters and can be defined as follows:
26 |MyCallback(Thrown, Mode) { ...27 |
Although the names you give the parameters do not matter, the following values are sequentially assigned to them:
28 |You can omit one or more parameters from the end of the callback's parameter list if the corresponding information is not needed, but in this case an asterisk must be specified as the final parameter, e.g. MyCallback(Param1, *)
.
The callback can return one of the following values (other values are reserved for future use and should be avoided):
34 |0
, ""
or no Return: Allow error handling to proceed as normal.1
: Suppress the default error dialog and any remaining error callbacks.-1
: As above, but if Mode (the second parameter) contains the word Return, execution of the current thread is permitted to continue.Type: Integer
44 |If omitted, it defaults to 1. Otherwise, specify one of the following numbers:
45 |Mode | 58 |Description | 59 |
---|---|
Return | 62 |The thrown value is a continuable runtime error. The thread continues if the callback returns -1; otherwise the thread exits. | 63 |
Exit | 66 |The thrown value is a non-continuable runtime error or a value thrown by the script. The thread will exit. | 67 |
ExitApp | 70 |The thrown value is a critical runtime error, such as corruption detected by DllCall. The program will exit. | 71 |
Callback is called only for errors or exceptions which would normally cause an error message to be displayed. It cannot be called for a load-time error, since OnError cannot be called until after the script has loaded.
76 |Callback is called on the current thread, before it exits (that is, before the call stack unwinds).
77 | 78 |Logs errors caused by the script into a text file instead of displaying them to the user.
84 |85 | OnError LogError 86 | i := Integer("cause_error") 87 | 88 | LogError(exception, mode) { 89 | FileAppend "Error on line " exception.Line ": " exception.Message "`n" 90 | , "errorlog.txt" 91 | return true 92 | }93 |
Use OnError to implement alternative error handling methods. Caveat: OnError is ineffective while Try is active.
97 |98 | AccumulateErrors() 99 | { 100 | local ea := ErrorAccumulator() 101 | ea.Start() 102 | return ea 103 | } 104 | 105 | class ErrorAccumulator 106 | { 107 | Errors := [] ; Array for accumulated errors. 108 | _cb := AccumulateError.Bind(this.Errors) 109 | Start() => OnError(this._cb, -1) ; Register our cb before others. 110 | Stop() => OnError(this._cb, 0) ; Unregister our cb. 111 | Last => this.Errors[-1] ; Most recent error. 112 | Count => this.Errors.Length ; Number of accumulated errors. 113 | __item[i] => this.Errors[i] ; Shortcut for indexing. 114 | __delete() => this.Stop() ; For tying to function scope. 115 | } 116 | 117 | ; This is the OnError callback. 'errors' is given a value via Bind(). 118 | AccumulateError(errors, e, mode) 119 | { 120 | if mode != "Return" ; Not continuable. 121 | return 122 | if e.What = "" ; Expression defect or similar, not a built-in function. 123 | return 124 | try { 125 | ; Try to print the error to stdout. 126 | FileAppend Format("{1} ({2}) : ({3}) {4}`n", e.File, e.Line, e.What, e.Message), "*" 127 | if HasProp(e, "extra") 128 | FileAppend " Specifically: " e.Extra "`n", "*" 129 | } 130 | errors.Push(e) 131 | return -1 ; Continue. 132 | } 133 | 134 | RearrangeWindows() 135 | { 136 | ; Start accumulating errors in 'err'. 137 | local err := AccumulateErrors() 138 | 139 | ; Do some things that might fail... 140 | MonitorGetWorkArea , &left, &top, &right, &bottom 141 | width := (right-left)//2, height := bottom-top 142 | WinMove left, top, width, height, A_ScriptFullPath 143 | WinMove left+width, top, width, height, "AutoHotkey v2 Help" 144 | 145 | ; Check if any errors occurred. 146 | if err.Count 147 | MsgBox err.Count " error(s); last error at line #" err.Last.Line 148 | else 149 | MsgBox "No errors" 150 | 151 | ; Stop is called automatically when the variable goes out of scope, 152 | ; since only we have a reference to the object. This causes OnError 153 | ; to be called to unregister the callback. 154 | ;err.Stop() 155 | } 156 | 157 | ; Call the test function which suppresses and accumulates errors. 158 | RearrangeWindows() 159 | ; Call another function to show normal error behaviour is restored. 160 | WinMove 0, 0, 0, 0, "non-existent window" 161 |162 |
Registers a function to be called automatically whenever the script exits.
16 | 17 |OnExit Callback , AddRemove18 |
Type: Function Object
24 |The function to call.
25 |The callback accepts two parameters and can be defined as follows:
26 |MyCallback(ExitReason, ExitCode) { ...27 |
Although the names you give the parameters do not matter, the following values are sequentially assigned to them:
28 |You can omit one or more parameters from the end of the callback's parameter list if the corresponding information is not needed, but in this case an asterisk must be specified as the final parameter, e.g. MyCallback(Param1, *)
.
The callback can return a non-zero integer to prevent the script from exiting (with some rare exceptions) and calling more callbacks. Otherwise, the script exits after all registered callbacks are called.
34 |Type: Integer
39 |If omitted, it defaults to 1. Otherwise, specify one of the following numbers:
40 |Any number of callbacks can be registered. A callback usually should not call ExitApp; if it does, the script terminates immediately.
51 |The callbacks are called when the script exits by any means (except when it is killed by something like "End Task"). It is also called whenever #SingleInstance and Reload ask a previous instance to terminate.
52 |A script can detect and optionally abort a system shutdown or logoff via OnMessage(0x0011, On_WM_QUERYENDSESSION)
(see OnMessage example #2 for a working script).
The OnExit thread does not obey #MaxThreads (it will always launch when needed). In addition, while it is running, it cannot be interrupted by any thread, including hotkeys, custom menu items, and timed subroutines. However, it will be interrupted (and the script will terminate) if the user chooses Exit from the tray menu or main menu, or the script is asked to terminate as a result of Reload or #SingleInstance. Because of this, a callback should be designed to finish quickly unless the user is aware of what it is doing.
54 |If the OnExit thread encounters a failure condition such as a runtime error, the script will terminate.
55 |If the OnExit thread was launched due to Exit or ExitApp that specified an exit code, that exit code is used unless a callback returns 1 (true) to prevent exit or calls ExitApp.
56 |Whenever an exit attempt is made, each callback starts off fresh with the default values for settings such as SendMode. These defaults can be changed during script startup.
57 | 58 |Reason | 62 |Description | 63 |
---|---|
Logoff | 66 |The user is logging off. | 67 |
Shutdown | 70 |The system is being shut down or restarted, such as by the Shutdown function. | 71 |
Close | 74 |
75 | The script was sent a WM_CLOSE or WM_QUIT message, had a critical error, or is being closed in some other way. Although all of these are unusual, WM_CLOSE might be caused by WinClose having been used on the script's main window. To close (hide) the window without terminating the script, use WinHide. 76 |If the script is exiting due to a critical error or its main window being destroyed, it will unconditionally terminate after the OnExit thread completes. 77 |If the main window is being destroyed, it may still exist but cannot be displayed. This condition can be detected by monitoring the WM_DESTROY message with OnMessage. 78 | |
79 |
Error | 82 |A runtime error occurred in a script that is not persistent. An example of a runtime error is Run/RunWait being unable to launch the specified program or document. | 83 |
Menu | 86 |The user selected Exit from the main window's menu or from the standard tray menu. | 87 |
Exit | 90 |Exit or ExitApp was used (includes custom menu items). | 91 |
Reload | 94 |The script is being reloaded via the Reload function or menu item. | 95 |
Single | 98 |The script is being replaced by a new instance of itself as a result of #SingleInstance. | 99 |
OnError, OnMessage, CallbackCreate, OnClipboardChange, ExitApp, Shutdown, Persistent, Threads, Return
104 | 105 |Asks the user before exiting the script. To test this example, right-click the tray icon and click Exit.
108 |Persistent ; Prevent the script from exiting automatically. 109 | OnExit ExitFunc 110 | 111 | ExitFunc(ExitReason, ExitCode) 112 | { 113 | if ExitReason != "Logoff" and ExitReason != "Shutdown" 114 | { 115 | Result := MsgBox("Are you sure you want to exit?",, 4) 116 | if Result = "No" 117 | return 1 ; Callbacks must return non-zero to avoid exit. 118 | } 119 | ; Do not call ExitApp -- that would prevent other callbacks from being called. 120 | }121 |
Registers a method to be called on exit.
125 |Persistent ; Prevent the script from exiting automatically. 126 | OnExit MyObject.Exiting 127 | 128 | class MyObject 129 | { 130 | static Exiting(*) 131 | { 132 | MsgBox "MyObject is cleaning up prior to exiting..." 133 | /* 134 | this.SayGoodbye() 135 | this.CloseNetworkConnections() 136 | */ 137 | } 138 | }139 |
Registers a function to be called automatically whenever the script receives the specified message.
16 | 17 |OnMessage MsgNumber, Callback , MaxThreads18 |
Type: Integer
24 |The number of the message to monitor or query, which should be between 0 and 4294967295 (0xFFFFFFFF). If you do not wish to monitor a system message (that is, one below 0x0400), it is best to choose a number greater than 4096 (0x1000) to the extent you have a choice. This reduces the chance of interfering with messages used internally by current and future versions of AutoHotkey.
25 |Type: Function Object
30 |The function to call.
31 |The callback accepts four parameters and can be defined as follows:
32 |MyCallback(wParam, lParam, msg, hwnd) { ...33 |
Although the names you give the parameters do not matter, the following values are sequentially assigned to them:
34 |You can omit one or more parameters from the end of the callback's parameter list if the corresponding information is not needed, but in this case an asterisk must be specified as the final parameter, e.g. MyCallback(Param1, *)
.
WPARAM and LPARAM are unsigned 32-bit integers (from 0 to 232-1) or signed 64-bit integers (from -263 to 263-1) depending on whether the exe running the script is 32-bit or 64-bit. For 32-bit scripts, if an incoming parameter is intended to be a signed integer, any negative numbers can be revealed by following this example:
42 |if (A_PtrSize = 4 && wParam > 0x7FFFFFFF) ; Checking A_PtrSize ensures the script is 32-bit. 43 | wParam := -(~wParam) - 144 |
Type: Integer
49 |If omitted, it defaults to 1, meaning the callback is limited to one thread at a time. This is usually best because otherwise, the script would process messages out of chronological order whenever the callback interrupts itself. Therefore, as an alternative to MaxThreads, consider using Critical as described below.
50 |If the callback directly or indirectly causes the message to be sent again while the callback is still running, it is necessary to specify a MaxThreads value greater than 1 or less than -1 to allow the callback to be called for the new message (if desired). Messages sent (not posted) by the script's own process to itself cannot be delayed or buffered.
51 |Specify 0 to unregister the previously registered callback identified by Callback.
52 |By default, when multiple callbacks are registered for a single MsgNumber, they are called in the order that they were registered. To register a callback to be called before any previously registered callbacks, specify a negative value for MaxThreads. For example, OnMessage Msg, Fn, -2
registers Fn
to be called before any other callbacks previously registered for Msg, and allows Fn a maximum of 2 threads. However, if the callback is already registered, the order will not change unless it is unregistered and then re-registered.
Any number of callbacks can monitor a given MsgNumber.
59 |Either of these two lines registers a callback to be called after any previously registered callbacks:
60 |OnMessage MsgNumber, Callback ; Option 1 - omit MaxThreads 61 | OnMessage MsgNumber, Callback, 1 ; Option 2 - specify MaxThreads 162 |
This registers a callback to be called before any previously registered callbacks:
63 |OnMessage MsgNumber, Callback, -164 |
To unregister a callback, specify 0 for MaxThreads:
65 |OnMessage MsgNumber, Callback, 066 | 67 |
In addition to the received parameters mentioned above, the callback may also consult the built-in variable A_EventInfo, which contains 0 if the message was sent via SendMessage. If sent via PostMessage, it contains the tick-count time the message was posted.
69 |A callback's last found window starts off as the parent window to which the message was sent (even if it was sent to a control). If the window is hidden but not a GUI window (such as the script's main window), turn on DetectHiddenWindows before using it. For example:
70 |DetectHiddenWindows True 71 | MsgParentWindow := WinExist() ; This stores the unique ID of the window to which the message was sent.72 | 73 |
If a callback uses Return without any parameters, or it specifies a blank value such as "" (or it never uses Return at all), the incoming message goes on to be processed normally when the callback finishes. The same thing happens if the callback exits or causes a runtime error such as running a nonexistent file. By contrast, returning an integer causes it to be sent immediately as a reply; that is, the program does not process the message any further. For example, a callback monitoring WM_LBUTTONDOWN (0x0201) may return an integer to prevent the target window from being notified that a mouse click has occurred. In many cases (such as a message arriving via PostMessage), it does not matter which integer is returned; but if in doubt, 0 is usually safest.
75 |The range of valid return values depends on whether the exe running the script is 32-bit or 64-bit. Non-empty return values must be between -231 and 232-1 for 32-bit scripts (A_PtrSize = 4
) and between -263 and 263-1 for 64-bit scripts (A_PtrSize = 8
).
If there are multiple callbacks monitoring a given message number, they are called one by one until one returns a non-empty value.
77 | 78 |Unlike a normal function-call, the arrival of a monitored message calls the callback as a new thread. Because of this, the callback starts off fresh with the default values for settings such as SendMode and DetectHiddenWindows. These defaults can be changed during script startup.
80 |Messages sent to a control (rather than being posted) are not monitored because the system routes them directly to the control behind the scenes. This is seldom an issue for system-generated messages because most of them are posted.
81 |If the script is intended to stay running in an idle state to monitor for incoming messages, it may be necessary to call the Persistent function to prevent the script from exiting. OnMessage does not automatically make the script persistent, as it is sometimes unnecessary or undesired. For instance, when OnMessage is used to monitor input to a GUI window (such as in the WM_LBUTTONDOWN example), it is often more appropriate to allow the script to exit automatically when the last GUI window is closed.
82 |If a message arrives while its callback is still running due to a previous arrival of the same message, by default the callback will not be called again; instead, the message will be treated as unmonitored. If this is undesirable, there are multiple ways it can be avoided:
83 |If a monitored message that is numerically greater than 0x0311 is posted while the script is uninterruptible, the message is buffered; that is, its callback is not called until the script becomes interruptible. However, messages which are sent rather than posted cannot be buffered as they must provide a return value. Posted messages also might not be buffered when a modal message loop is running, such as for a system dialog, ListView drag-drop operation or menu.
90 |If a monitored message arrives and is not buffered, its callback is called immediately even if the thread is uninterruptible when the message is received.
91 |The priority of OnMessage threads is always 0. Consequently, no messages are monitored or buffered when the current thread's priority is higher than 0.
92 |Caution should be used when monitoring system messages (those below 0x0400). For example, if a callback does not finish quickly, the response to the message might take longer than the system expects, which might cause side-effects. Unwanted behavior may also occur if a callback returns an integer to suppress further processing of a message, but the system expected different processing or a different response.
93 |When the script is displaying a system dialog such as MsgBox, any message posted to a control is not monitored. For example, if the script is displaying a message box and the user clicks a button in a GUI window, the WM_LBUTTONDOWN message is sent directly to the button without calling the callback.
94 |Although an external program may post messages directly to a script's thread via PostThreadMessage() or other API call, this is not recommended because the messages would be lost if the script is displaying a system window such as a message box. Instead, it is usually best to post or send the messages to the script's main window or one of its GUI windows.
95 |CallbackCreate, OnExit, OnClipboardChange, PostMessage, SendMessage, Functions, Windows Messages, Threads, Critical, DllCall
97 |Monitors mouse clicks in a GUI window. Related topic: ContextMenu event
100 |MyGui := Gui(, "Example Window") 101 | MyGui.Add("Text",, "Click anywhere in this window.") 102 | MyGui.Add("Edit", "w200") 103 | MyGui.Show() 104 | OnMessage 0x0201, WM_LBUTTONDOWN 105 | 106 | WM_LBUTTONDOWN(wParam, lParam, msg, hwnd) 107 | { 108 | X := lParam & 0xFFFF 109 | Y := lParam >> 16 110 | Control := "" 111 | thisGui := GuiFromHwnd(hwnd) 112 | thisGuiControl := GuiCtrlFromHwnd(hwnd) 113 | if thisGuiControl 114 | { 115 | thisGui := thisGuiControl.Gui 116 | Control := "`n(in control " . thisGuiControl.ClassNN . ")" 117 | } 118 | ToolTip "You left-clicked in Gui window '" thisGui.Title "' at client coordinates " X "x" Y "." Control 119 | }120 |
Detects system shutdown/logoff and allows the user to abort it. On Windows Vista and later, the system displays a user interface showing which program is blocking shutdown/logoff and allowing the user to force shutdown/logoff. On older OSes, the script displays a confirmation prompt. Related topic: OnExit
124 |; The following DllCall is optional: it tells the OS to shut down this script first (prior to all other applications). 125 | DllCall("kernel32.dll\SetProcessShutdownParameters", "UInt", 0x4FF, "UInt", 0) 126 | OnMessage(0x0011, On_WM_QUERYENDSESSION) 127 | Persistent 128 | 129 | On_WM_QUERYENDSESSION(wParam, lParam, *) 130 | { 131 | ENDSESSION_LOGOFF := 0x80000000 132 | if (lParam & ENDSESSION_LOGOFF) ; User is logging off. 133 | EventType := "Logoff" 134 | else ; System is either shutting down or restarting. 135 | EventType := "Shutdown" 136 | try 137 | { 138 | ; Set a prompt for the OS shutdown UI to display. We do not display 139 | ; our own confirmation prompt because we have only 5 seconds before 140 | ; the OS displays the shutdown UI anyway. Also, a program without 141 | ; a visible window cannot block shutdown without providing a reason. 142 | BlockShutdown("Example script attempting to prevent " EventType ".") 143 | return false 144 | } 145 | catch 146 | { 147 | ; ShutdownBlockReasonCreate is not available, so this is probably 148 | ; Windows XP, 2003 or 2000, where we can actually prevent shutdown. 149 | Result := MsgBox(EventType " in progress. Allow it?",, "YN") 150 | if (Result = "Yes") 151 | return true ; Tell the OS to allow the shutdown/logoff to continue. 152 | else 153 | return false ; Tell the OS to abort the shutdown/logoff. 154 | } 155 | } 156 | 157 | BlockShutdown(Reason) 158 | { 159 | ; If your script has a visible GUI, use it instead of A_ScriptHwnd. 160 | DllCall("ShutdownBlockReasonCreate", "ptr", A_ScriptHwnd, "wstr", Reason) 161 | OnExit StopBlockingShutdown 162 | } 163 | 164 | StopBlockingShutdown(*) 165 | { 166 | OnExit StopBlockingShutdown, 0 167 | DllCall("ShutdownBlockReasonDestroy", "ptr", A_ScriptHwnd) 168 | }169 |
Receives a custom message and up to two numbers from some other script or program (to send strings rather than numbers, see the example after this one).
173 |OnMessage 0x5555, MsgMonitor 174 | Persistent 175 | 176 | MsgMonitor(wParam, lParam, msg, *) 177 | { 178 | ; Since returning quickly is often important, it is better to use ToolTip than 179 | ; something like MsgBox that would prevent the callback from finishing: 180 | ToolTip "Message " msg " arrived:`nWPARAM: " wParam "`nLPARAM: " lParam 181 | } 182 | 183 | ; The following could be used inside some other script to run the callback inside the above script: 184 | SetTitleMatchMode 2 185 | DetectHiddenWindows True 186 | if WinExist("Name of Receiving Script.ahk ahk_class AutoHotkey") 187 | PostMessage 0x5555, 11, 22 ; The message is sent to the "last found window" due to WinExist above. 188 | DetectHiddenWindows False ; Must not be turned off until after PostMessage.189 |
Sends a string of any length from one script to another. To use this, save and run both of the following scripts then press Win+Space to show an input box that will prompt you to type in a string. Both scripts must use the same native encoding.
193 |Save the following script as Receiver.ahk then launch it.
194 |#SingleInstance 195 | OnMessage 0x004A, Receive_WM_COPYDATA ; 0x004A is WM_COPYDATA 196 | Persistent 197 | 198 | Receive_WM_COPYDATA(wParam, lParam, msg, hwnd) 199 | { 200 | StringAddress := NumGet(lParam, 2*A_PtrSize, "Ptr") ; Retrieves the CopyDataStruct's lpData member. 201 | CopyOfData := StrGet(StringAddress) ; Copy the string out of the structure. 202 | ; Show it with ToolTip vs. MsgBox so we can return in a timely fashion: 203 | ToolTip A_ScriptName "`nReceived the following string:`n" CopyOfData 204 | return true ; Returning 1 (true) is the traditional way to acknowledge this message. 205 | }206 |
Save the following script as Sender.ahk then launch it. After that, press the Win+Space hotkey.
207 |TargetScriptTitle := "Receiver.ahk ahk_class AutoHotkey" 208 | 209 | #space:: ; Win+Space hotkey. Press it to show an input box for entry of a message string. 210 | { 211 | ib := InputBox("Enter some text to Send:", "Send text via WM_COPYDATA") 212 | if ib.Result = "Cancel" ; User pressed the Cancel button. 213 | return 214 | result := Send_WM_COPYDATA(ib.Value, TargetScriptTitle) 215 | if result = "" 216 | MsgBox "SendMessage failed or timed out. Does the following WinTitle exist?:`n" TargetScriptTitle 217 | else if (result = 0) 218 | MsgBox "Message sent but the target window responded with 0, which may mean it ignored it." 219 | } 220 | 221 | Send_WM_COPYDATA(StringToSend, TargetScriptTitle) 222 | ; This function sends the specified string to the specified window and returns the reply. 223 | ; The reply is 1 if the target window processed the message, or 0 if it ignored it. 224 | { 225 | CopyDataStruct := Buffer(3*A_PtrSize) ; Set up the structure's memory area. 226 | ; First set the structure's cbData member to the size of the string, including its zero terminator: 227 | SizeInBytes := (StrLen(StringToSend) + 1) * 2 228 | NumPut( "Ptr", SizeInBytes ; OS requires that this be done. 229 | , "Ptr", StrPtr(StringToSend) ; Set lpData to point to the string itself. 230 | , CopyDataStruct, A_PtrSize) 231 | Prev_DetectHiddenWindows := A_DetectHiddenWindows 232 | Prev_TitleMatchMode := A_TitleMatchMode 233 | DetectHiddenWindows True 234 | SetTitleMatchMode 2 235 | TimeOutTime := 4000 ; Optional. Milliseconds to wait for response from receiver.ahk. Default is 5000 236 | ; Must use SendMessage not PostMessage. 237 | RetValue := SendMessage(0x004A, 0, CopyDataStruct,, TargetScriptTitle,,,, TimeOutTime) ; 0x004A is WM_COPYDATA. 238 | DetectHiddenWindows Prev_DetectHiddenWindows ; Restore original setting for the caller. 239 | SetTitleMatchMode Prev_TitleMatchMode ; Same. 240 | return RetValue ; Return SendMessage's reply back to our caller. 241 | }242 |
See the WinLIRC client script for a demonstration of how to use OnMessage to receive notification when data has arrived on a network connection.
245 | 246 | 247 | 248 | -------------------------------------------------------------------------------- /docs/lib/Ord.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the ordinal value (numeric character code) of the first character in the specified string.
16 | 17 |Number := Ord(String)
18 | Type: String
24 |The string whose ordinal value is retrieved.
25 |Type: Integer
31 |This function returns the ordinal value of String, or 0 if String is empty. If String begins with a Unicode supplementary character, this function returns the corresponding Unicode character code (a number between 0x10000 and 0x10FFFF). Otherwise it returns a value in the range 0 to 255 (for ANSI) or 0 to 0xFFFF (for Unicode). See Unicode vs ANSI for details.
32 | 33 |Both message boxes below show 116, because only the first character is considered.
38 |MsgBox Ord("t") 39 | MsgBox Ord("test")40 |
Sends a string to the debugger (if any) for display.
16 | 17 |OutputDebug Text
18 | Type: String
24 |The text to send to the debugger for display. This text may include linefeed characters (`n) to start new lines. In addition, a single long line can be broken up into several shorter ones by means of a continuation section.
25 |If the script's process has no debugger, the system debugger displays the string. If the system debugger is not active, this function has no effect.
31 |One example of a debugger is DebugView, which is free and available at microsoft.com.
32 |See also: other debugging methods
33 |FileAppend, continuation sections
35 |Sends a string to the debugger (if any) for display.
38 |OutputDebug A_Now ': Because the window "' TargetWindowTitle '" did not exist, the process was aborted.'39 |
Pauses the script's current thread or sets the pause state of the underlying thread.
16 | 17 |18 | Pause UnderlyingThreadState 19 |20 |
Type: Integer
26 |If omitted, the current thread is paused. Otherwise, specify one of the following values:
27 |1
or True
: Marks the underlying thread as paused. The current thread is not paused and continues running. When the current thread finishes, the underlying thread resumes any interrupted function the underlying thread was running. Once the underlying thread finishes the function (if any), it enters a paused state. If there is no thread underneath the current thread, the script itself is paused, which prevents timers from running (this effect is the same as having used the menu item "Pause Script" while the script has no threads).
0
or False
: Unpauses the underlying thread.
-1
: Toggles the pause state of the underlying thread.
By default, the script can also be paused via its tray icon or main window.
36 |Unlike Suspend -- which disables hotkeys and hotstrings -- turning on pause will freeze the thread (the current thread if UnderlyingThreadState was omitted, otherwise the underlying thread). As a side-effect, any interrupted threads underneath it will lie dormant until the current thread is unpaused and finishes.
37 |Whenever any thread or the script itself is paused, timers will not run. By contrast, explicitly launched threads such as hotkeys and menu items can still be launched; but when their threads finish, the underlying thread will still be paused. In other words, each thread can be paused independently of the others.
38 |The tray icon changes to (or to if the script is also suspended), whenever the script's current thread is in a paused state. This icon change can be avoided by freezing the icon, which is achieved by using TraySetIcon(,, true)
.
To disable timers without pausing the script, use Thread NoTimers.
40 |A script is always halted (though not officially paused) while it is displaying any kind of menu (tray menu, menu bar, GUI context menu, etc.)
41 |The built-in variable A_IsPaused contains 1 if the thread immediately underneath the current thread is paused and 0 otherwise.
42 | 43 |Suspend, Menu object, ExitApp, Threads, SetTimer
45 | 46 |Use Pause to halt the script, such as to inspect variables.
49 |ListVars 50 | Pause 51 | ExitApp ; This line will not execute until the user unpauses the script.52 |
Press a hotkey once to pause the script. Press it again to unpause.
56 |Pause::Pause -1 ; The Pause/Break key. 57 | #p::Pause -1 ; Win+P58 |
Sends a Pause command to another script.
62 |DetectHiddenWindows True 63 | WM_COMMAND := 0x0111 64 | ID_FILE_PAUSE := 65403 65 | PostMessage WM_COMMAND, ID_FILE_PAUSE,,, "C:\YourScript.ahk ahk_class AutoHotkey"66 |
Prevents the script from exiting automatically when its last thread completes, allowing it to stay running in an idle state.
17 |Persistent Persist18 | 19 |
Type: Boolean
24 |If omitted, it defaults to true.
25 |If true, the script will be kept running after all threads have exited, even if none of the other conditions for keeping the script running are met.
26 |If false, the default behaviour is restored.
27 |Type: Integer (boolean)
32 |This function returns the previous setting; either 0 (false) or 1 (true).
33 | 34 |If Persistent is not used, the default setting is 0 (false).
36 |If the script is persistent, it will stay running after startup completes and all other threads have exited. It is usually unnecessary to call this function because the script is automatically persistent in most of the common cases where the user would want it to keep running, such as to respond to hotkeys, execute timers or display a GUI.
37 |Some cases where this function might be needed (if it is intended to stay running when there are no running threads or hotkeys, timers, etc.) include:
38 |If this function is added to an existing script, some or all occurrences of Exit might need to be changed to ExitApp. This is because Exit will not terminate a persistent script; it terminates only the current thread.
44 | 45 |Prevent the script from exiting automatically.
50 |; This script will not exit automatically, even though it has nothing to do. 51 | ; However, you can use its tray icon to open the script in an editor, or to 52 | ; launch Window Spy or the Help file. 53 | Persistent54 |
Retrieves the color of the pixel at the specified X and Y coordinates.
16 | 17 |Color := PixelGetColor(X, Y , Mode)18 |
Type: Integer
24 |The X and Y coordinates of the pixel. Coordinates are relative to the active window's client area unless CoordMode was used to change that.
25 |Type: String
30 |If blank or omitted, the pixel is retrieved using the normal method. Otherwise, specify one or more of the following words. If more than one word is present, separate each from the next with a space (e.g. "Alt Slow"
).
Alt: Uses an alternate method to retrieve the color, which should be used when the normal method produces invalid or inaccurate colors for a particular type of window. This method is about 10 % slower than the normal method.
32 |Slow: Uses a more elaborate method to retrieve the color, which may work in certain full-screen applications when the other methods fail. This method is about three times slower than the normal method. Note: Slow takes precedence over Alt, so there is no need to specify Alt in this case.
33 |Type: String
39 |This function returns a hexadecimal numeric string representing the RGB (red-green-blue) color of the pixel. For example, the color purple is defined 0x800080 because it has an intensity of 0x80 (128) for its blue and red components but an intensity of 0x00 (0) for its green component.
40 | 41 |An OSError is thrown on failure.
43 | 44 |The pixel must be visible; in other words, it is not possible to retrieve the pixel color of a window hidden behind another window. By contrast, pixels beneath the mouse cursor can usually be detected. The exception to this is game cursors, which in most cases will obstruct any pixels beneath them.
46 |Use Window Spy (available in tray icon menu) or the example at the bottom of this page to determine the colors currently on the screen.
47 |Known limitations:
48 |PixelSearch, ImageSearch, CoordMode, MouseGetPos
54 |Press a hotkey to show the color of the pixel located at the current position of the mouse cursor.
57 |^!z:: ; Control+Alt+Z hotkey. 58 | { 59 | MouseGetPos &MouseX, &MouseY 60 | MsgBox "The color at the current cursor position is " PixelGetColor(MouseX, MouseY) 61 | }62 |
Searches a region of the screen for a pixel of the specified color.
16 | 17 |PixelSearch &OutputVarX, &OutputVarY, X1, Y1, X2, Y2, ColorID , Variation18 |
Type: VarRef
24 |References to the output variables in which to store the X and Y coordinates of the first pixel that matches ColorID (if no match is found, the variables are made blank). Coordinates are relative to the active window's client area unless CoordMode was used to change that.
25 |Type: Integer
30 |The X and Y coordinates of the starting corner of the rectangle to search. Coordinates are relative to the active window's client area unless CoordMode was used to change that.
31 |Type: Integer
36 |The X and Y coordinates of the ending corner of the rectangle to search. Coordinates are relative to the active window's client area unless CoordMode was used to change that.
37 |Type: Integer
42 |The color ID to search for. This is typically expressed as a hexadecimal number in Red-Green-Blue (RGB) format. For example: 0x9d6346
. Color IDs can be determined using Window Spy (accessible from the tray menu) or via PixelGetColor.
Type: Integer
48 |If omitted, it defaults to 0. Otherwise, specify a number between 0 and 255 (inclusive) to indicate the allowed number of shades of variation in either direction for the intensity of the red, green, and blue components of the color. For example, if 2 is specified and ColorID is 0x444444, any color from 0x424242 to 0x464646 will be considered a match. This parameter is helpful if the color sought is not always exactly the same shade. If you specify 255 shades of variation, all colors will match.
49 |Type: Integer (boolean)
55 |This function returns 1 (true) if the color was found in the specified region, or 0 (false) if it was not found.
56 | 57 |An OSError is thrown if there was a problem that prevented the function from conducting the search.
59 | 60 |The region to be searched must be visible; in other words, it is not possible to search a region of a window hidden behind another window. By contrast, pixels beneath the mouse cursor can usually be detected. The exception to this is game cursors, which in most cases will obstruct any pixels beneath them.
62 |Although color depths as low as 8-bit (256-color) are supported, PixelSearch performs much better in 24-bit or 32-bit color.
63 |The search starts at the coordinates specified by X1 and Y1 and checks all pixels in the row from X1 to X2 for a match. If no match is found there, the search continues toward Y2, row by row, until it finds a matching pixel.
64 |The search order depends on the order of the parameters. In other words, if X1 is greater than X2, the search will be conducted from right to left, starting at column X1. Similarly, if Y1 is greater than Y2, the search will be conducted from bottom to top.
65 |If the region to be searched is large and the search is repeated with high frequency, it may consume a lot of CPU time. To alleviate this, keep the size of the area to a minimum.
66 | 67 |PixelGetColor, ImageSearch, CoordMode, MouseGetPos
69 |Searches a region of the active window for a pixel and stores in Px and Py the X and Y coordinates of the first pixel that matches the specified color with 3 shades of variation.
72 |if PixelSearch(&Px, &Py, 200, 200, 300, 300, 0x9d6346, 3) 73 | MsgBox "A color within 3 shades of variation was found at X" Px " Y" Py 74 | else 75 | MsgBox "That color was not found in the specified region." 76 |77 |
Places a message in the message queue of a window or control.
16 | 17 |PostMessage MsgNumber , wParam, lParam, Control, WinTitle, WinText, ExcludeTitle, ExcludeText18 |
Type: Integer
24 |The message number to send. See the message list to determine the number.
25 |Type: Integer
30 |If either is omitted, 0 will be sent. Otherwise, specify the first and second component of the message.
31 |Each parameter must be an integer.
32 |If AutoHotkey or the target window is 32-bit, only the parameter's low 32 bits are used; that is, values are truncated if outside the range -2147483648 to 2147483647 (-0x80000000 to 0x7FFFFFFF) for signed values, or 0 to 4294967295 (0xFFFFFFFF) for unsigned values. If AutoHotkey and the target window are both 64-bit, any integer value supported by AutoHotkey can be used.
33 |Type: String, Integer or Object
38 |If omitted, the message will be posted directly to the target window rather than one of its controls. Otherwise, specify the control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
If this parameter specifies a HWND (as an integer or object), it is not required to be the HWND of a control (child window). That is, it can also be the HWND of a top-level window.
40 |Type: String, Integer or Object
45 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
46 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
47 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
48 |A TargetError is thrown if the window or control could not be found.
54 |An OSError is thrown if the message could not be posted. For example, if the target window is running at a higher integrity level than the script (i.e. it is running as admin while the script is not), messages may be blocked.
55 | 56 |This function should be used with caution because sending a message to the wrong window (or sending an invalid message) might cause unexpected behavior or even crash the target application. This is because most applications are not designed to expect certain types of messages from external sources.
58 |PostMessage places the message in the message queue associated with the target window and does not wait for acknowledgement or reply. By contrast, SendMessage waits for the target window to process the message, up until the timeout period expires.
59 |Unlike SendMessage, PostMessage usually only sends basic numeric values, not pointers to structures or strings.
60 |To send a message to all windows in the system, including those that are hidden or disabled, specify 0xFFFF
for WinTitle (0xFFFF is HWND_BROADCAST). This technique should be used only for messages intended to be broadcast.
To have a script receive a message, use OnMessage.
62 |See the Message Tutorial for an introduction to using this function.
63 | 64 |SendMessage, Message List, Message Tutorial, OnMessage, Automating Winamp, DllCall, ControlSend, MenuSelect
66 |Switches the active window's keyboard layout/language to English (US).
69 |PostMessage 0x0050, 0, 0x4090409,, "A" ; 0x0050 is WM_INPUTLANGCHANGEREQUEST.70 |
Functions for retrieving information about a process or for performing various operations on a process. Click on a function name for details.
16 |Function | 19 |Description | 20 |
---|---|
ProcessClose | 23 |Forces the first matching process to close. | 24 |
ProcessExist | 27 |Checks if the specified process exists. | 28 |
ProcessGetName | 31 |Returns the name of the specified process. | 32 |
ProcessGetParent | 35 |Returns the process ID (PID) of the process which created the specified process. | 36 |
ProcessGetPath | 39 |Returns the path of the specified process. | 40 |
ProcessSetPriority | 43 |Changes the priority level of the first matching process. | 44 |
ProcessWait | 47 |Waits for the specified process to exist. | 48 |
ProcessWaitClose | 51 |Waits for all matching processes to close. | 52 |
Process list: Although there is no ProcessList function, example #1 and example #2 demonstrate how to retrieve a list of processes via DllCall or COM.
57 | 58 |Run, WinClose, WinKill, WinWait, WinWaitClose, WinExist, Win functions
60 | 61 |Shows a list of running processes retrieved via DllCall.
65 |d := " | " ; string separator 66 | s := 4096 ; size of buffers and arrays (4 KB) 67 | 68 | ScriptPID := ProcessExist() ; The PID of this running script. 69 | ; Get the handle of this script with PROCESS_QUERY_INFORMATION (0x0400): 70 | h := DllCall("OpenProcess", "UInt", 0x0400, "Int", false, "UInt", ScriptPID, "Ptr") 71 | ; Open an adjustable access token with this process (TOKEN_ADJUST_PRIVILEGES = 32): 72 | DllCall("Advapi32.dll\OpenProcessToken", "Ptr", h, "UInt", 32, "PtrP", &t := 0) 73 | ; Retrieve the locally unique identifier of the debug privilege: 74 | DllCall("Advapi32.dll\LookupPrivilegeValue", "Ptr", 0, "Str", "SeDebugPrivilege", "Int64P", &luid := 0) 75 | ti := Buffer(16, 0) ; structure of privileges 76 | NumPut( "UInt", 1 ; one entry in the privileges array... 77 | , "Int64", luid 78 | , "UInt", 2 ; Enable this privilege: SE_PRIVILEGE_ENABLED = 2 79 | , ti) 80 | ; Update the privileges of this process with the new access token: 81 | r := DllCall("Advapi32.dll\AdjustTokenPrivileges", "Ptr", t, "Int", false, "Ptr", ti, "UInt", 0, "Ptr", 0, "Ptr", 0) 82 | DllCall("CloseHandle", "Ptr", t) ; Close the access token handle to save memory. 83 | DllCall("CloseHandle", "Ptr", h) ; Close the process handle to save memory. 84 | 85 | hModule := DllCall("LoadLibrary", "Str", "Psapi.dll") ; Increase performance by preloading the library. 86 | a := Buffer(s) ; An array that receives the list of process identifiers: 87 | c := 0 ; counter for process idendifiers 88 | l := "" 89 | DllCall("Psapi.dll\EnumProcesses", "Ptr", a, "UInt", s, "UIntP", &r) 90 | Loop r // 4 ; Parse array for identifiers as DWORDs (32 bits): 91 | { 92 | id := NumGet(a, A_Index * 4, "UInt") 93 | ; Open process with: PROCESS_VM_READ (0x0010) | PROCESS_QUERY_INFORMATION (0x0400) 94 | h := DllCall("OpenProcess", "UInt", 0x0010 | 0x0400, "Int", false, "UInt", id, "Ptr") 95 | if !h 96 | continue 97 | n := Buffer(s, 0) ; A buffer that receives the base name of the module: 98 | e := DllCall("Psapi.dll\GetModuleBaseName", "Ptr", h, "Ptr", 0, "Ptr", n, "UInt", s//2) 99 | if !e ; Fall-back method for 64-bit processes when in 32-bit mode: 100 | e := DllCall("Psapi.dll\GetProcessImageFileName", "Ptr", h, "Ptr", n, "UInt", s//2) 101 | SplitPath StrGet(n), &n 102 | DllCall("CloseHandle", "Ptr", h) ; Close the process handle to save memory. 103 | if (n && e) ; If image is not null add to list: 104 | l .= n "`n", c++ 105 | } 106 | DllCall("FreeLibrary", "Ptr", hModule) ; Unload the library to free memory. 107 | ;l := Sort(l) ; Uncomment this line to sort the list alphabetically. 108 | MsgBox StrReplace(l, "`n", d), c " Processes", 0109 |
Shows a list of running processes retrieved via COM and Win32_Process.
113 |MyGui := Gui(, "Process List") 114 | LV := MyGui.Add("ListView", "x2 y0 w400 h500", ["Process Name", "Command Line"]) 115 | for process in ComObjGet("winmgmts:").ExecQuery("Select * from Win32_Process") 116 | LV.Add("", process.Name, process.CommandLine) 117 | MyGui.Show()118 |
Forces the first matching process to close.
17 | 18 |ProcessClose PIDOrName
19 |
20 | Specify either a number (the PID) or a process name:
26 |PID: The Process ID, which is a number that uniquely identifies one specific process (this number is valid only during the lifetime of that process). The PID of a newly launched process can be determined via the Run function. Similarly, the PID of a window can be determined with WinGetPID. ProcessExist can also be used to discover a PID.
27 |Name: The name of a process is usually the same as its executable (without path), e.g. notepad.exe or winword.exe. Since a name might match multiple running processes, only the first process will be operated upon. The name is not case-sensitive.
28 |Type: Integer
33 |This function returns the Process ID (PID) of the specified process. If a matching process is not found or cannot be manipulated, zero is returned.
34 | 35 |Since the process will be abruptly terminated -- possibly interrupting its work at a critical point or resulting in the loss of unsaved data in its windows (if it has any) -- this function should be used only if a process cannot be closed by using WinClose on one of its windows.
37 | 38 |Run, WinClose, WinKill, Process functions, Win functions
40 | 41 |Forces the first matching process to close (be warned that any unsaved data will be lost).
44 |ProcessClose "notepad.exe"45 |
Forces all matching processes to close.
48 |ProcessCloseAll(PIDOrName) 49 | { 50 | While ProcessExist(PIDOrName) 51 | ProcessClose PIDOrName 52 | } 53 | 54 | ; Example: 55 | Loop 3 56 | Run "notepad.exe" 57 | Sleep 3000 58 | ProcessCloseAll "notepad.exe"59 |
Checks if the specified process exists.
17 | 18 |PID := ProcessExist(PIDOrName)19 | 20 |
If omitted, the script's own process is used. Otherwise, specify either a number (the PID) or a process name:
26 |PID: The Process ID, which is a number that uniquely identifies one specific process (this number is valid only during the lifetime of that process). The PID of a newly launched process can be determined via the Run function. Similarly, the PID of a window can be determined with WinGetPID.
27 |Name: The name of a process is usually the same as its executable (without path), e.g. notepad.exe or winword.exe. Since a name might match multiple running processes, only the first process will be operated upon. The name is not case-sensitive.
28 |Type: Integer
33 |This function returns the Process ID (PID) of the specified process. If there is no matching process, zero is returned.
34 | 35 |Run, WinExist, Process functions, Win functions
37 | 38 |Checks if a process of Notepad exists.
41 |if (PID := ProcessExist("notepad.exe")) 42 | MsgBox "Notepad exists and has the Process ID " PID "." 43 | else 44 | MsgBox "Notepad does not exist."45 |
Returns the name or path of the specified process.
17 | 18 |Name := ProcessGetName(PIDOrName) 19 | Path := ProcessGetPath(PIDOrName)20 | 21 |
If omitted, the script's own process is used. Otherwise, specify either a number (the PID) or a process name:
27 |PID: The Process ID, which is a number that uniquely identifies one specific process (this number is valid only during the lifetime of that process). The PID of a newly launched process can be determined via the Run function. Similarly, the PID of a window can be determined with WinGetPID. ProcessExist can also be used to discover a PID.
28 |Name: The name of a process is usually the same as its executable (without path), e.g. notepad.exe or winword.exe. Since a name might match multiple running processes, only the first process will be operated upon. The name is not case-sensitive.
29 |Type: String
34 |ProcessGetName returns the name of the specified process. For example: notepad.exe.
35 |ProcessGetPath returns the path of the specified process. For example: C:\Windows\notepad.exe.
36 | 37 |A TargetError is thrown if the process could not be found.
39 |An OSError is thrown if the name/path could not be retrieved.
40 | 41 |Process functions, Run, WinGetProcessName, WinGetProcessPath
43 | 44 |Get the name and path of a process used to open a document.
47 |Run "license.rtf",,, &pid ; This is likely to exist in C:\Windows\System32. 48 | try { 49 | name := ProcessGetName(pid) 50 | path := ProcessGetPath(pid) 51 | } 52 | MsgBox "Name: " (name ?? "could not be retrieved") "`n" 53 | . "Path: " (path ?? "could not be retrieved") 54 |55 |
Returns the process ID (PID) of the process which created the specified process.
17 | 18 |PID := ProcessGetParent(PIDOrName)19 | 20 |
If omitted, the script's own process is used. Otherwise, specify either a number (the PID) or a process name:
26 |PID: The Process ID, which is a number that uniquely identifies one specific process (this number is valid only during the lifetime of that process). The PID of a newly launched process can be determined via the Run function. Similarly, the PID of a window can be determined with WinGetPID. ProcessExist can also be used to discover a PID.
27 |Name: The name of a process is usually the same as its executable (without path), e.g. notepad.exe or winword.exe. Since a name might match multiple running processes, only the first process will be operated upon. The name is not case-sensitive.
28 |Type: Integer
33 |This function returns the process ID (PID) of the process which created the specified process.
34 | 35 |A TargetError is thrown if the specified process could not be found.
37 | 38 |If the parent process is no longer running, there is some risk that the returned PID has been reused by the system, and now identifies a different process.
40 | 41 |Display the name of the process which launched the script.
47 |try 48 | MsgBox ProcessGetName(ProcessGetParent()) 49 | catch 50 | MsgBox "Unable to retrieve parent process name; the process has likely exited." 51 |52 |
Changes the priority level of the first matching process.
17 | 18 |ProcessSetPriority Level , PIDOrName19 | 20 |
Type: String
25 |Specify one of the following words or letters:
26 |Note that any process not designed to run at Realtime priority might reduce system stability if set to that level.
35 |If omitted, the script's own process is used. Otherwise, specify either a number (the PID) or a process name:
40 |PID: The Process ID, which is a number that uniquely identifies one specific process (this number is valid only during the lifetime of that process). The PID of a newly launched process can be determined via the Run function. Similarly, the PID of a window can be determined with WinGetPID. ProcessExist can also be used to discover a PID.
41 |Name: The name of a process is usually the same as its executable (without path), e.g. notepad.exe or winword.exe. Since a name might match multiple running processes, only the first process will be operated upon. The name is not case-sensitive.
42 |Type: Integer
47 |This function returns the Process ID (PID) of the specified process. If a matching process is not found or cannot be manipulated, zero is returned.
48 | 49 |The current priority level of a process can be seen in the Windows Task Manager.
51 | 52 |Run, Process functions, Win functions
54 | 55 |Launches Notepad, sets its priority to high and reports its current PID.
59 |Run "notepad.exe", , , &NewPID 60 | ProcessSetPriority "High", NewPID 61 | MsgBox "The newly launched Notepad's PID is " NewPID62 |
Press a hotkey to change the priority of the active window's process.
66 |#z:: ; Win+Z hotkey 67 | { 68 | active_pid := WinGetPID("A") 69 | active_title := WinGetTitle("A") 70 | MyGui := Gui(, "Set Priority") 71 | MyGui.Add("Text",, " 72 | ( 73 | Press ESCAPE to cancel, or double-click a new 74 | priority level for the following window: 75 | )") 76 | MyGui.Add("Text", "wp", active_title) 77 | LB := MyGui.Add("ListBox", "r5 Choose1", ["Normal", "High", "Low", "BelowNormal", "AboveNormal"]) 78 | LB.OnEvent("DoubleClick", SetPriority) 79 | MyGui.Add("Button", "default", "OK").OnEvent("Click", SetPriority) 80 | MyGui.OnEvent("Escape", (*) => MyGui.Destroy()) 81 | MyGui.OnEvent("Close", (*) => MyGui.Destroy()) 82 | MyGui.Show() 83 | 84 | SetPriority(*) 85 | { 86 | new_prio := LB.Text 87 | MyGui.Destroy() 88 | if ProcessSetPriority(new_prio, active_pid) 89 | MsgBox "Success: Its priority was changed to " new_prio 90 | else 91 | MsgBox "Error: Its priority could not be changed to " new_prio 92 | } 93 | }94 |
Waits for the specified process to exist.
17 | 18 |PID := ProcessWait(PIDOrName , Timeout)19 | 20 |
Specify either a number (the PID) or a process name:
26 |PID: The Process ID, which is a number that uniquely identifies one specific process (this number is valid only during the lifetime of that process). The PID of a newly launched process can be determined via the Run function. Similarly, the PID of a window can be determined with WinGetPID. ProcessExist can also be used to discover a PID.
27 |Name: The name of a process is usually the same as its executable (without path), e.g. notepad.exe or winword.exe. Since a name might match multiple running processes, only the first process will be operated upon. The name is not case-sensitive.
28 |If omitted, the function will wait indefinitely. Otherwise, specify the number of seconds (can contain a decimal point) to wait before timing out.
33 |Type: Integer
38 |If the specified process is discovered, this function returns the Process ID (PID) of the process. If the function times out, zero is returned.
39 | 40 |Processes are checked every 100 milliseconds; the moment the condition is satisfied, the function stops waiting. In other words, rather than waiting for the timeout to expire, it immediately returns and continues execution of the script. Also, while the function is in a waiting state, new threads can be launched via hotkey, custom menu item, or timer.
42 | 43 |ProcessWaitClose, Run, WinWait, Process functions, Win functions
45 | 46 |Waits for a Notepad process to appear. If one appears within 5.5 seconds, its priority is set to low and the script's own priority is set to high. After that, an attempt is made to close the process within 5 seconds.
50 |NewPID := ProcessWait("notepad.exe", 5.5) 51 | if not NewPID 52 | { 53 | MsgBox "The specified process did not appear within 5.5 seconds." 54 | return 55 | } 56 | ; Otherwise: 57 | MsgBox "A matching process has appeared (Process ID is " NewPID ")." 58 | ProcessSetPriority "Low", NewPID 59 | ProcessSetPriority "High" ; Have the script set itself to high priority. 60 | WinClose "Untitled - Notepad" 61 | WaitPID := ProcessWaitClose(NewPID, 5) 62 | if WaitPID ; The PID still exists. 63 | MsgBox "The process did not close within 5 seconds."64 |
Waits for all matching processes to close.
17 | 18 |PID := ProcessWaitClose(PIDOrName , Timeout)19 | 20 |
Specify either a number (the PID) or a process name:
26 |PID: The Process ID, which is a number that uniquely identifies one specific process (this number is valid only during the lifetime of that process). The PID of a newly launched process can be determined via the Run function. Similarly, the PID of a window can be determined with WinGetPID. ProcessExist can also be used to discover a PID.
27 |Name: The name of a process is usually the same as its executable (without path), e.g. notepad.exe or winword.exe. Since a name might match multiple running processes, only the first process will be operated upon. The name is not case-sensitive.
28 |If omitted, the function will wait indefinitely. Otherwise, specify the number of seconds (can contain a decimal point) to wait before timing out.
33 |Type: Integer
38 |If all matching processes are closed, zero is returned. If this function times out, it returns the Process ID (PID) of the first matching process that still exists.
39 | 40 |Processes are checked every 100 milliseconds; the moment the condition is satisfied, the function stops waiting. In other words, rather than waiting for the timeout to expire, it immediately returns and continues execution of the script. Also, while the function is in a waiting state, new threads can be launched via hotkey, custom menu item, or timer.
42 | 43 |ProcessWait, Run, WinWaitClose, Process functions, Win functions
45 | 46 |See example #1 on the ProcessWait page.
48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /docs/lib/Random.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Generates a pseudo-random number.
16 | 17 |N := Random(A, B)18 |
If both are omitted, the default is 0.0 to 1.0. If only one parameter is specified, the other parameter defaults to 0. Otherwise, specify the minimum and maximum number to be generated, in either order.
25 |For integers, the minimum value and maximum value are both included in the set of possible numbers that may be returned. The full range of 64-bit integers is supported.
26 |For floating point numbers, the maximum value is generally excluded.
27 |This function returns a pseudo-randomly generated number, which is a number that simulates a true random number but is really a number based on a complicated formula to make determination/guessing of the next number extremely difficult.
34 |If either A or B is a floating point number or both are omitted, the result will be a floating point number. Otherwise, the result will be an integer.
35 | 36 |All numbers within the specified range have approximately the same probability of being generated.
38 |Although the specified maximum value is excluded by design when returning a floating point number, it may in theory be returned due to floating point rounding errors. This has not been confirmed, and might only be possible if the chosen bounds are larger than 2**53. Also note that since there may be up to 2**53 possible values (such as in the range 0.0 to 1.0), the probability of generating exactly the lower bound is generally very low.
39 | 40 |Generates a random integer in the range 1 to 10 and stores it in N.
43 |N := Random(1, 10)44 |
Generates a random floating point number in the range 0.0 to 1.0 and stores it in fraction.
53 |fraction := Random(0.0, 1.0) 54 | fraction := Random() ; Equivalent to the line above.55 |
Creates a registry key without writing a value.
17 | 18 |RegCreateKey KeyName19 |
Type: String
25 |The full name of the registry key, e.g. "HKLM\Software\SomeApplication"
.
This must start with HKEY_LOCAL_MACHINE (or HKLM), HKEY_USERS (or HKU), HKEY_CURRENT_USER (or HKCU), HKEY_CLASSES_ROOT (or HKCR), or HKEY_CURRENT_CONFIG (or HKCC).
27 |To access a remote registry, prepend the computer name and a backslash, e.g. "\\workstation01\HKLM"
.
KeyName can be omitted only if a registry loop is running, in which case it defaults to the key of the current loop item (even if the key has been deleted during the loop). If the item is a subkey, the full name of that subkey is used by default.
29 |An OSError is thrown on failure.
34 |A_LastError is set to the result of the operating system's GetLastError() function.
35 | 36 |If KeyName specifies an existing registry key, RegCreateKey verifies that the script has write access to the key, but makes no changes. Otherwise, RegCreateKey attempts to create the key (along with its ancestors, if necessary).
38 |For details about how to access the registry of a remote computer, see the remarks in registry loop.
39 |To create subkeys in the 64-bit sections of the registry in a 32-bit script or vice versa, use SetRegView.
40 | 41 |RegDelete, RegDeleteKey, RegRead, RegWrite, registry loop, SetRegView
43 | 44 |Creates an empty registry key. If Notepad++ is installed, this has the effect of adding it to the "open with" menu for .ahk files.
47 |RegCreateKey "HKCU\Software\Classes\.ahk\OpenWithList\notepad++.exe"48 |
Deletes a value from the registry.
16 | 17 |RegDelete KeyName, ValueName18 |
Type: String
24 |The full name of the registry key, e.g. "HKLM\Software\SomeApplication"
.
This must start with HKEY_LOCAL_MACHINE (or HKLM), HKEY_USERS (or HKU), HKEY_CURRENT_USER (or HKCU), HKEY_CLASSES_ROOT (or HKCR), or HKEY_CURRENT_CONFIG (or HKCC).
26 |To access a remote registry, prepend the computer name and a backslash, e.g. "\\workstation01\HKLM"
.
KeyName can be omitted only if a registry loop is running, in which case it defaults to the key of the current loop item. If the item is a subkey, the full name of that subkey is used by default. If the item is a value, ValueName defaults to the name of that value, but can be overridden.
28 |Type: String
33 |If blank or omitted, the key's default value will be deleted (except as noted above), which is the value displayed as "(Default)" by RegEdit. Otherwise, specify the name of the value to delete.
34 |An OSError is thrown on failure.
39 |A_LastError is set to the result of the operating system's GetLastError() function.
40 | 41 |Warning: Deleting from the registry is potentially dangerous - please exercise caution!
43 |To retrieve and operate upon multiple registry keys or values, consider using a registry loop.
44 |Within a registry loop, RegDelete does not necessarily delete the current loop item. If the item is a subkey, RegDelete()
only deletes its default value.
For details about how to access the registry of a remote computer, see the remarks in registry loop.
46 |To delete entries from the 64-bit sections of the registry in a 32-bit script or vice versa, use SetRegView.
47 | 48 |RegCreateKey, RegDeleteKey, RegRead, RegWrite, registry loop, SetRegView, IniDelete
50 | 51 |Deletes a value from the registry.
54 |RegDelete "HKEY_LOCAL_MACHINE\Software\SomeApplication", "TestValue"55 |
Deletes a subkey from the registry.
17 | 18 |RegDeleteKey KeyName19 |
Type: String
25 |The full name of the registry key, e.g. "HKLM\Software\SomeApplication"
.
This must start with HKEY_LOCAL_MACHINE (or HKLM), HKEY_USERS (or HKU), HKEY_CURRENT_USER (or HKCU), HKEY_CLASSES_ROOT (or HKCR), or HKEY_CURRENT_CONFIG (or HKCC).
27 |To access a remote registry, prepend the computer name and a backslash, e.g. "\\workstation01\HKLM"
.
KeyName can be omitted only if a registry loop is running, in which case it defaults to the key of the current loop item. If the item is a subkey, the full name of that subkey is used by default.
29 |An OSError is thrown on failure.
34 |A_LastError is set to the result of the operating system's GetLastError() function.
35 | 36 |Warning: Deleting from the registry is potentially dangerous - please exercise caution!
38 |To retrieve and operate upon multiple registry keys or values, consider using a registry loop.
39 |Within a registry loop, RegDeleteKey does not necessarily delete the current loop item. If the item is a subkey, RegDeleteKey()
deletes the key itself. If the item is a value, RegDeleteKey()
deletes the key which contains that value, including all subkeys and values.
For details about how to access the registry of a remote computer, see the remarks in registry loop.
41 |To delete entries from the 64-bit sections of the registry in a 32-bit script or vice versa, use SetRegView.
42 | 43 |RegCreateKey, RegDelete, RegRead, RegWrite, registry loop, SetRegView, IniDelete
45 | 46 |Deletes a subkey from the registry.
49 |RegDeleteKey "HKEY_LOCAL_MACHINE\Software\SomeApplication"50 |
Determines whether a string contains a pattern (regular expression).
16 | 17 |FoundPos := RegExMatch(Haystack, NeedleRegEx , &OutputVar, StartingPos)18 |
Type: String
24 |The string whose content is searched. This may contain binary zero.
25 |Type: String
30 |The pattern to search for, which is a Perl-compatible regular expression (PCRE). The pattern's options (if any) must be included at the beginning of the string followed by a close-parenthesis. For example, the pattern i)abc.*123 would turn on the case-insensitive option and search for "abc", followed by zero or more occurrences of any character, followed by "123". If there are no options, the ")" is optional; for example, )abc is equivalent to abc.
31 |Although NeedleRegEx cannot contain binary zero, the pattern \x00
can be used to match a binary zero within Haystack.
Type: VarRef
37 |If omitted, no output variable will be used. Otherwise, specify a reference to the output variable in which to store a match object, which can be used to retrieve the position, length and value of the overall match and of each captured subpattern, if any are present.
38 |If the pattern is not found (that is, if the function returns 0), this variable is made blank.
39 |Type: Integer
44 |If omitted, it defaults to 1 (the beginning of Haystack). Otherwise, specify 2 to start at the second character, 3 to start at the third, and so on. If StartingPos is beyond the length of Haystack, the search starts at the empty string that lies at the end of Haystack (which typically results in no match).
45 |Specify a negative StartingPos to start at that position from the right. For example, -1 starts at the last character and -2 starts at the next-to-last character. If StartingPos tries to go beyond the left end of Haystack, all of Haystack is searched.
46 |Specify 0 to start at the end of Haystack; i.e. the position to the right of the last character. This can be used with zero-width assertions such as (?<=a)
.
Regardless of the value of StartingPos, the return value is always relative to the first character of Haystack. For example, the position of "abc" in "123abc789" is always 4.
48 |Type: Integer
54 |This function returns the position of the leftmost occurrence of NeedleRegEx in the string Haystack. Position 1 is the first character. Zero is returned if the pattern is not found.
55 | 56 |Syntax errors: If the pattern contains a syntax error, an Error is thrown with a message in the following form: Compile error N at offset M: description. In that string, N is the PCRE error number, M is the position of the offending character inside the regular expression, and description is the text describing the error.
58 |Execution errors: If an error occurs during the execution of the regular expression, an Error is thrown. The Extra property of the error object contains the PCRE error number. Although such errors are rare, the ones most likely to occur are "too many possible empty-string matches" (-22), "recursion too deep" (-21), and "reached match limit" (-8). If these happen, try to redesign the pattern to be more restrictive, such as replacing each * with a ?, +, or a limit like {0,3} wherever feasible.
59 | 60 |See RegEx Quick Reference for options such as i)abc, which turns off case-sensitivity.
62 | 63 |If a match is found, an object containing information about the match is stored in OutputVar. This object has the following methods and properties:
65 |Match.Pos, Match.Pos[N] or Match.Pos(N): Returns the position of the overall match or a captured subpattern.
66 |Match.Len, Match.Len[N] or Match.Len(N): Returns the length of the overall match or a captured subpattern.
67 |Match.Name[N] or Match.Name(N): Returns the name of the given subpattern, if it has one.
68 |Match.Count: Returns the overall number of subpatterns (capturing groups), which is also the maximum value for N.
69 |Match.Mark: Returns the NAME of the last encountered (*MARK:NAME), when applicable.
70 |Match[] or Match[N]: Returns the overall match or a captured subpattern.
71 |All of the above allow N to be any of the following:
72 |Match.N: Shorthand for Match["N"], where N is any unquoted name or number which does not conflict with a defined property (listed above). For example, match.1
or match.Year
.
The object also supports enumeration; that is, the for-loop is supported. Alternatively, use Loop Match.Count
.
To search for a simple substring inside a larger string, use InStr because it is faster than RegExMatch.
82 |To improve performance, the 100 most recently used regular expressions are kept cached in memory (in compiled form).
83 |The study option (S) can sometimes improve the performance of a regular expression that is used many times (such as in a loop).
84 | 85 |A subpattern may be given a name such as the word Year in the pattern (?P<Year>\d{4}). Such names may consist of up to 32 alphanumeric characters and underscores. Note that named subpatterns are also numbered, so if an unnamed subpattern occurs after "Year", it would be stored in OutputVar[2]
, not OutputVar[1]
.
Most characters like abc123 can be used literally inside a regular expression. However, any of the characters in the set \.*?+[{|()^$
must be preceded by a backslash to be seen as literal. For example, \. is a literal period and \\ is a literal backslash. Escaping can be avoided by using \Q...\E. For example: \QLiteral Text\E.
Within a regular expression, special characters such as tab and newline can be escaped with either an accent (`) or a backslash (\). For example, `t is the same as \t except when the x option is used.
89 |To learn the basics of regular expressions (or refresh your memory of pattern syntax), see the RegEx Quick Reference.
90 |AutoHotkey's regular expressions are implemented using Perl-compatible Regular Expressions (PCRE) from www.pcre.org.
91 |Within an expression, a ~= b
can be used as shorthand for RegExMatch(a, b)
.
RegExReplace, RegEx Quick Reference, Regular Expression Callouts, InStr, SubStr, SetTitleMatchMode RegEx, Global matching and Grep (archived forum link)
94 |Common sources of text data: FileRead, Download, A_Clipboard, GUI Edit controls
95 | 96 |For general RegEx examples, see the RegEx Quick Reference.
98 | 99 |Reports 4, which is the position where the match was found.
101 |MsgBox RegExMatch("xxxabc123xyz", "abc.*xyz")102 |
Reports 7 because the $ requires the match to be at the end.
106 |MsgBox RegExMatch("abc123123", "123$")107 |
Reports 1 because a match was achieved via the case-insensitive option.
111 |MsgBox RegExMatch("abc123", "i)^ABC")112 |
Reports 1 and stores "XYZ" in SubPat[1].
116 |MsgBox RegExMatch("abcXYZ123", "abc(.*)123", &SubPat)117 |
Reports 7 instead of 1 due to the starting position 2 instead of 1.
121 |MsgBox RegExMatch("abc123abc456", "abc\d+",, 2)122 |
Demonstrates the usage of the Match object.
126 |FoundPos := RegExMatch("Michiganroad 72", "(.*) (?<nr>\d+)", &SubPat) 127 | MsgBox SubPat.Count ": " SubPat[1] " " SubPat.Name[2] "=" SubPat.nr ; Displays "2: Michiganroad nr=72"128 |
Retrieves the extension of a file. Note that SplitPath can also be used for this, which is more reliable.
132 |Path := "C:\Foo\Bar\Baz.txt" 133 | RegExMatch(Path, "\w+$", &Extension) 134 | MsgBox Extension[] ; Reports "txt".135 |
Similar to AutoHotkey v1's Transform Deref, the following function expands variable references and escape sequences contained inside other variables. Furthermore, this example shows how to find all matches in a string rather than stopping at the first match (similar to the g flag in JavaScript's RegEx).
139 |var1 := "abc" 140 | var2 := 123 141 | MsgBox Deref("%var1%def%var2%") ; Reports abcdef123. 142 | 143 | Deref(Str) 144 | { 145 | spo := 1 146 | out := "" 147 | while (fpo:=RegexMatch(Str, "(%(.*?)%)|``(.)", &m, spo)) 148 | { 149 | out .= SubStr(Str, spo, fpo-spo) 150 | spo := fpo + StrLen(m[0]) 151 | if (m[1]) 152 | out .= %m[2]% 153 | else switch (m[3]) 154 | { 155 | case "a": out .= "`a" 156 | case "b": out .= "`b" 157 | case "f": out .= "`f" 158 | case "n": out .= "`n" 159 | case "r": out .= "`r" 160 | case "t": out .= "`t" 161 | case "v": out .= "`v" 162 | default: out .= m[3] 163 | } 164 | } 165 | return out SubStr(Str, spo) 166 | }167 |
Replaces occurrences of a pattern (regular expression) inside a string.
16 | 17 |NewStr := RegExReplace(Haystack, NeedleRegEx , Replacement, &OutputVarCount, Limit, StartingPos)18 |
Type: String
24 |The string whose content is searched and replaced. This may contain binary zero.
25 |Type: String
30 |The pattern to search for, which is a Perl-compatible regular expression (PCRE). The pattern's options (if any) must be included at the beginning of the string followed by a close-parenthesis. For example, the pattern i)abc.*123 would turn on the case-insensitive option and search for "abc", followed by zero or more occurrences of any character, followed by "123". If there are no options, the ")" is optional; for example, )abc is equivalent to abc.
31 |Although NeedleRegEx cannot contain binary zero, the pattern \x00
can be used to match a binary zero within Haystack.
Type: String
37 |If blank or omitted, NeedleRegEx will be replaced with blank (empty), meaning it will be omitted from the return value. Otherwise, specify the string to be substituted for each match, which is plain text (not a regular expression).
38 |This parameter may include backreferences like $1, which brings in the substring from Haystack that matched the first subpattern. The simplest backreferences are $0 through $9, where $0 is the substring that matched the entire pattern, $1 is the substring that matched the first subpattern, $2 is the second, and so on. For backreferences greater than 9 (and optionally those less than or equal to 9), enclose the number in braces; e.g. ${10}, ${11}, and so on. For named subpatterns, enclose the name in braces; e.g. ${SubpatternName}. To specify a literal $, use $$ (this is the only character that needs such special treatment; backslashes are never needed to escape anything).
39 |To convert the case of a subpattern, follow the $ with one of the following characters: U or u (uppercase), L or l (lowercase), T or t (title case, in which the first letter of each word is capitalized but all others are made lowercase). For example, both $U1 and $U{1} transcribe an uppercase version of the first subpattern.
40 |Nonexistent backreferences and those that did not match anything in Haystack -- such as one of the subpatterns in (abc)|(xyz) -- are transcribed as empty strings.
41 |Type: VarRef
46 |If omitted, the corresponding value will not be stored. Otherwise, specify a reference to the output variable in which to store the number of replacements that occurred (0 if none).
47 |Type: Integer
52 |If omitted, it defaults to -1, which replaces all occurrences of the pattern found in Haystack. Otherwise, specify the maximum number of replacements to allow. The part of Haystack to the right of the last replacement is left unchanged.
53 |Type: Integer
58 |If omitted, it defaults to 1 (the beginning of Haystack). Otherwise, specify 2 to start at the second character, 3 to start at the third, and so on. If StartingPos is beyond the length of Haystack, the search starts at the empty string that lies at the end of Haystack (which typically results in no replacements).
59 |Specify a negative StartingPos to start at that position from the right. For example, -1 starts at the last character and -2 starts at the next-to-last character. If StartingPos tries to go beyond the left end of Haystack, all of Haystack is searched.
60 |Specify 0 to start at the end of Haystack; i.e. the position to the right of the last character. This can be used with zero-width assertions such as (?<=a)
.
Regardless of the value of StartingPos, the return value is always a complete copy of Haystack -- the only difference is that more of its left side might be unaltered compared to what would have happened with a StartingPos of 1.
62 |Type: String
68 |This function returns a version of Haystack whose contents have been replaced by the operation. If no replacements are needed, Haystack is returned unaltered.
69 | 70 |An Error is thrown if:
72 |For details, see RegExMatch.
77 | 78 |See RegEx Quick Reference for options such as i)abc, which turns off case-sensitivity.
80 |To replace simple substrings, use StrReplace because it is faster than RegExReplace.
82 |If you know what the maximum number of replacements will be, specifying that for the Limit parameter improves performance because the search can be stopped early (this might also reduce the memory load on the system during the operation). For example, if you know there can be only one match near the beginning of a large string, specify a limit of 1.
83 |To improve performance, the 100 most recently used regular expressions are kept cached in memory (in compiled form).
84 |The study option (S) can sometimes improve the performance of a regular expression that is used many times (such as in a loop).
85 |Most characters like abc123 can be used literally inside a regular expression. However, any of the characters in the set \.*?+[{|()^$
must be preceded by a backslash to be seen as literal. For example, \. is a literal period and \\ is a literal backslash. Escaping can be avoided by using \Q...\E. For example: \QLiteral Text\E.
Within a regular expression, special characters such as tab and newline can be escaped with either an accent (`) or a backslash (\). For example, `t is the same as \t except when the x option is used.
88 |To learn the basics of regular expressions (or refresh your memory of pattern syntax), see the RegEx Quick Reference.
89 |RegExMatch, RegEx Quick Reference, Regular Expression Callouts, StrReplace, InStr
91 |Common sources of text data: FileRead, Download, A_Clipboard, GUI Edit controls
92 |For general RegEx examples, see the RegEx Quick Reference.
94 |Reports "abc123xyz" because the $ allows a match only at the end.
96 |MsgBox RegExReplace("abc123123", "123$", "xyz")97 |
Reports "123" because a match was achieved via the case-insensitive option.
101 |MsgBox RegExReplace("abc123", "i)^ABC")102 |
Reports "aaaXYZzzz" by means of the $1 backreference.
106 |MsgBox RegExReplace("abcXYZ123", "abc(.*)123", "aaa$1zzz")107 |
Reports an empty string and stores 2 in ReplacementCount.
111 |MsgBox RegExReplace("abc123abc456", "abc\d+", "", &ReplacementCount)112 |
Reads a value from the registry.
16 | 17 |Value := RegRead(KeyName, ValueName, Default) 18 |19 |
Type: String
25 |The full name of the registry key, e.g. "HKLM\Software\SomeApplication"
.
This must start with HKEY_LOCAL_MACHINE (or HKLM), HKEY_USERS (or HKU), HKEY_CURRENT_USER (or HKCU), HKEY_CLASSES_ROOT (or HKCR), or HKEY_CURRENT_CONFIG (or HKCC).
27 |To access a remote registry, prepend the computer name and a backslash, e.g. "\\workstation01\HKLM"
.
KeyName can be omitted only if a registry loop is running, in which case it defaults to the key of the current loop item. If the item is a subkey, the full name of that subkey is used by default. If the item is a value, ValueName defaults to the name of that value, but can be overridden.
29 |Type: String
34 |If blank or omitted, the key's default value will be retrieved (except as noted above), which is the value displayed as "(Default)" by RegEdit. Otherwise, specify the name of the value to retrieve. If there is no default value (that is, if RegEdit displays "value not set"), an OSError is thrown.
35 |Type: Any
40 |If omitted, an OSError is thrown instead of returning a default value. Otherwise, specify the value to return if the specified key or value does not exist.
41 |This function returns a value of the specified registry key.
48 | 49 |An OSError is thrown if there was a problem, such as a nonexistent key or value when Default is omitted, or a permission error.
51 |A_LastError is set to the result of the operating system's GetLastError() function.
52 | 53 |Currently only the following value types are supported: REG_SZ, REG_EXPAND_SZ, REG_MULTI_SZ, REG_DWORD, and REG_BINARY.
55 |In the registry, REG_DWORD values are always expressed as positive decimal numbers. If the number was intended to be negative, convert it to a signed 32-bit integer by using OutputVar := OutputVar << 32 >> 32
or similar.
When reading a REG_BINARY key the result is a string of hex characters. For example, the REG_BINARY value of 01,a9,ff,77 will be read as the string 01A9FF77.
57 |When reading a REG_MULTI_SZ key, each of the components ends in a linefeed character (`n). If there are no components, an empty string is returned. To extract the individual components from the return value, use a parsing loop.
58 |To retrieve and operate upon multiple registry keys or values, consider using a registry loop.
59 |For details about how to access the registry of a remote computer, see the remarks in registry loop.
60 |To read and write entries from the 64-bit sections of the registry in a 32-bit script or vice versa, use SetRegView.
61 | 62 |RegCreateKey, RegDelete, RegDeleteKey, RegWrite, registry loop, SetRegView, IniRead
64 | 65 |Reads a value from the registry and store it in TestValue.
68 |TestValue := RegRead("HKEY_LOCAL_MACHINE\Software\SomeApplication", "TestValue")69 |
Retrieves and reports the path of the "Program Files" directory. See EnvGet example #2 for an alternative method.
73 |; The line below ensures that the path of the 64-bit Program Files 74 | ; directory is returned if the OS is 64-bit and the script is not. 75 | SetRegView 64 76 | 77 | ProgramFilesDir := RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion", "ProgramFilesDir") 78 | MsgBox "Program files are in: " ProgramFilesDir79 |
Retrieves the type of a registry value (e.g. REG_SZ or REG_DWORD).
84 |MsgBox RegKeyType("HKCU", "Environment", "TEMP") 85 | return 86 | 87 | RegKeyType(RootKey, SubKey, ValueName) ; This function returns the type of the specified value. 88 | { 89 | Loop Reg, RootKey "\" SubKey 90 | if (A_LoopRegName = ValueName) 91 | return A_LoopRegType 92 | return "Error" 93 | }94 |
Writes a value to the registry.
16 | 17 |RegWrite Value, ValueType, KeyName , ValueName 18 | RegWrite Value , ValueType, , ValueName 19 |20 |
The value to be written. Long text values can be broken up into several shorter lines by means of a continuation section, which might improve readability and maintainability.
27 |Type: String
32 |Must be either REG_SZ, REG_EXPAND_SZ, REG_MULTI_SZ, REG_DWORD, or REG_BINARY.
33 |ValueType can be omitted only if KeyName is omitted and the current registry loop item is a value, as noted below.
34 |Type: String
39 |The full name of the registry key, e.g. "HKLM\Software\SomeApplication"
.
This must start with HKEY_LOCAL_MACHINE (or HKLM), HKEY_USERS (or HKU), HKEY_CURRENT_USER (or HKCU), HKEY_CLASSES_ROOT (or HKCR), or HKEY_CURRENT_CONFIG (or HKCC).
41 |To access a remote registry, prepend the computer name and a backslash, e.g. "\\workstation01\HKLM"
.
KeyName can be omitted only if a registry loop is running, in which case it defaults to the key of the current loop item. If the item is a subkey, the full name of that subkey is used by default. If the item is a value, ValueType and ValueName default to the type and name of that value, but can be overridden.
43 |Type: String
48 |If blank or omitted, the key's default value will be used (except as noted above), which is the value displayed as "(Default)" by RegEdit. Otherwise, specify the name of the value that will be written to.
49 |An OSError is thrown on failure.
55 |A_LastError is set to the result of the operating system's GetLastError() function.
56 | 57 |If KeyName specifies a subkey which does not exist, RegWrite attempts to create it (along with its ancestors, if necessary). Although RegWrite can write directly into a root key, some operating systems might refuse to write into HKEY_CURRENT_USER's top level.
59 |To create a key without writing any values to it, use RegCreateKey.
60 |If ValueType is REG_DWORD, Value should be between -2147483648 and 4294967295 (0xFFFFFFFF). In the registry, REG_DWORD values are always expressed as positive decimal numbers. To read it as a negative number with means such as RegRead, convert it to a signed 32-bit integer by using OutputVar := OutputVar << 32 >> 32
or similar.
When writing a REG_BINARY key, use a string of hex characters, e.g. the REG_BINARY value of 01,a9,ff,77 can be written by using the string 01A9FF77.
62 |When writing a REG_MULTI_SZ key, you must separate each component from the next with a linefeed character (`n). The last component may optionally end with a linefeed as well. No blank components are allowed. In other words, do not specify two linefeeds in a row (`n`n) because that will result in a shorter-than-expected value being written to the registry.
63 |To retrieve and operate upon multiple registry keys or values, consider using a registry loop.
64 |For details about how to access the registry of a remote computer, see the remarks in registry loop.
65 |To read and write entries from the 64-bit sections of the registry in a 32-bit script or vice versa, use SetRegView.
66 | 67 |RegCreateKey, RegDelete, RegDeleteKey, RegRead, registry loop, SetRegView, IniWrite
69 | 70 |Writes a string to the registry.
73 |RegWrite "Test Value", "REG_SZ", "HKEY_LOCAL_MACHINE\SOFTWARE\TestKey", "MyValueName"74 |
Writes binary data to the registry.
78 |RegWrite "01A9FF77", "REG_BINARY", "HKEY_CURRENT_USER\Software\TEST_APP", "TEST_NAME"79 |
Writes a multi-line string to the registry.
83 |RegWrite "Line1`nLine2", "REG_MULTI_SZ", "HKEY_CURRENT_USER\Software\TEST_APP", "TEST_NAME"84 |
Replaces the currently running instance of the script with a new one.
16 | 17 |Reload
18 | This function is useful for scripts that are frequently changed. By assigning a hotkey to this function, you can easily restart the script after saving your changes in an editor.
19 |By default, the script can also be reloaded via its tray icon or main window.
20 |If the /include switch was passed to the script's current instance, it is automatically passed to the new instance.
21 |Any other command-line parameters passed to the script's current instance are not passed to the new instance. To pass such parameters, do not use Reload. Instead, use Run in conjunction with A_AhkPath and A_ScriptFullPath (and A_IsCompiled if the script is ever used in compiled form). Also, include the string /restart
as the first parameter (i.e. after the name of the executable), which tells the program to use the same behavior as Reload. See also: command line switches and syntax.
When the script restarts, it is launched in its original working directory (the one that was in effect when it was first launched). In other words, SetWorkingDir will not change the working directory that will be used for the new instance.
23 |If the script cannot be reloaded -- perhaps because it has a syntax error -- the original instance of the script will continue running. Therefore, the reload function should be followed by whatever actions you want taken in the event of a failure (such as a return to exit the current subroutine). To have the original instance detect the failure, follow this example:
24 |Reload 25 | Sleep 1000 ; If successful, the reload will close this instance during the Sleep, so the line below will never be reached. 26 | Result := MsgBox("The script could not be reloaded. Would you like to open it for editing?",, 4) 27 | if Result = "Yes" 28 | Edit 29 | return30 |
Previous instances of the script are identified by the same mechanism as for #SingleInstance, with the same limitations.
31 |If the script allows multiple instances, Reload may fail to identify the correct instance. The simplest alternative is to Run a new instance and then exit. For example:
32 |if A_IsCompiled 33 | Run Format('"{1}" /force', A_ScriptFullPath) 34 | else 35 | Run Format('"{1}" /force "{2}"', A_AhkPath, A_ScriptFullPath) 36 | ExitApp37 | 38 |
Returns from a function to which execution had previously jumped via function-call, Hotkey activation, or other means.
16 | 17 |Return Expression18 |
This parameter can only be used within a function.
24 |If omitted, it defaults to an empty string.
25 |Since this parameter is an expression, all of the following lines are valid:
26 |return 3 27 | return "literal string" 28 | return MyVar 29 | return i + 1 30 | return true ; Returns the number 1 to mean "true". 31 | return ItemCount < MaxItems ; Returns a true or false value. 32 | return FindColor(TargetColor)33 |
The space or tab after Return is optional if the expression is enclosed in parentheses, as in return(expression)
.
If there is no caller to which to return, Return will do an Exit instead.
40 |There are various ways to return multiple values from function to caller described within Returning Values to Caller.
41 | 42 |Reports the value returned by the function.
48 |MsgBox returnTest() ; Shows 123 49 | 50 | returnTest() { 51 | return 123 52 | }53 |
The first Return ensures that the subsequent function call is skipped if the preceding condition is true. The second Return is redundant when used at the end of a function like this.
56 |#z:: ; Win-Z 57 | ^#z:: ; Ctrl-Win-Z 58 | { 59 | MsgBox "A Win-Z hotkey was pressed." 60 | if GetKeyState("Ctrl") 61 | return ; Finish early, skipping the function call below. 62 | MyFunction() 63 | } 64 | 65 | MyFunction() 66 | { 67 | Sleep 1000 68 | return ; Redundant when used at the end of the function like this. 69 | }70 |
Runs an external program. Unlike Run, RunWait will wait until the program finishes before continuing.
19 | 20 |21 | Run Target , WorkingDir, Options, &OutputVarPID 22 | ExitCode := RunWait(Target , WorkingDir, Options, &OutputVarPID) 23 |24 |
Type: String
30 |A document, URL, executable file (.exe, .com, .bat, etc.), shortcut (.lnk), CLSID, or system verb to launch (see remarks). If Target is a local file and no path was specified with it, how the file is located typically depends on the type of file and other conditions. See Interpretation of Target for details.
31 |To pass parameters, add them immediately after the program or document name as follows:
32 |Run 'MyProgram.exe Param1 Param2'33 |
If the program/document name or a parameter contains spaces, it is safest to enclose it in double quotes as follows (even though it may work without them in some cases):
34 |Run '"My Program.exe" "param with spaces"'35 |
Type: String
40 |If blank or omitted, the script's own working directory (A_WorkingDir) will be used. Otherwise, specify the initial working directory to be used by the new process. This typically also affects relative paths in Target, but interpretation of command-line parameters depends on the target program.
41 |Type: String
46 |If blank or omitted, Target will be launched normally. Otherwise, specify one or more of the following options:
47 |Max: launch maximized
48 |Min: launch minimized
49 |Hide: launch hidden (cannot be used in combination with either of the above)
50 |Note: Some applications (e.g. Calc.exe) do not obey the requested startup state and thus Max/Min/Hide will have no effect.
51 |Type: VarRef
56 |If omitted, the corresponding value will not be stored. Otherwise, specify a reference to the output variable in which to store the newly launched program's unique Process ID (PID). The variable will be made blank if the PID could not be determined, which usually happens if a system verb, document, or shortcut is launched rather than a direct executable file. RunWait also supports this parameter, though its OutputVarPID must be checked in another thread (otherwise, the PID will be invalid because the process will have terminated by the time the line following RunWait executes).
57 |After the Run function retrieves a PID, any windows to be created by the process might not exist yet. To wait for at least one window to be created, use WinWait "ahk_pid " OutputVarPID
.
Type: Integer
64 |Unlike Run, RunWait will wait until Target is closed or exits, at which time the return value will be the program's exit code (as a signed 32-bit integer). Some programs will appear to return immediately even though they are still running; these programs spawn another process.
65 | 66 |If Target cannot be launched, an exception is thrown (that is, an error window is displayed) and the current thread is exited, unless the error is caught by a Try/Catch statement. For example:
68 |try 69 | Run "NonExistingFile" 70 | catch 71 | MsgBox "File does not exist." 72 |73 |
The built-in variable A_LastError is set to the result of the operating system's GetLastError() function.
74 |Run/RunWait itself does not interpret command-line parameters or search for the target file. Instead, it attempts to execute the target as follows:
76 |If Target specifies a name but not a directory, the system will search for and launch the file if it is integrated ("known"), e.g. by being contained in one of the PATH folders. The exact search order depends on whether CreateProcess and/or ShellExecuteEx is called. If CreateProcess is called, the application directory (which contains the AutoHotkey interpreter or compiled script) takes precedence over the working directory specified by WorkingDir. To avoid this, specify the directory; e.g. .\program.exe
.
When ShellExecuteEx is being attempted, Target is interpreted as follows:
82 |When running a program via ComSpec (cmd.exe) -- perhaps because you need to redirect the program's input or output -- if the path or name of the executable contains spaces, the entire string should be enclosed in an outer pair of quotes. In the following example, the outer quotes are highlighted in yellow:
90 |Run A_ComSpec ' /c ""C:\My Utility.exe" "param 1" "second param" >"C:\My File.txt""'91 |
Performance may be slightly improved if Target is an exact path, e.g. Run 'C:\Windows\Notepad.exe "C:\My Documents\Test.txt"'
rather than Run "C:\My Documents\Test.txt"
.
Special CLSIDs may be opened via Run. Most of them can be opened by using the shell: prefix. Some can be opened without it. For example:
93 |Run "shell:::{D20EA4E1-3957-11D2-A40B-0C5020524153}" ; Windows Tools. 94 | Run "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}" ; This PC (formerly My Computer or Computer). 95 | Run "::{645FF040-5081-101B-9F08-00AA002F954E}" ; Recycle Bin.96 |
System verbs correspond to actions available in a file's right-click menu in the Explorer. If a file is launched without a verb, the default verb (usually "open") for that particular file type will be used. If specified, the verb should be followed by the name of the target file. The following verbs are currently supported:
97 |Verb | 100 |Description | 101 |
---|---|
*verb | 104 |Any system-defined or custom verb. For example: Run "*Compile " A_ScriptFullPath . The *RunAs verb may be used in place of the Run as administrator right-click menu item. |
105 |
properties | 108 |
109 | Displays the Explorer's properties window for the indicated file. For example: Note: The properties window will automatically close when the script terminates. To prevent this, use WinWait to wait for the window to appear, then use WinWaitClose to wait for the user to close it. 111 | |
112 |
find | 115 |Opens an instance of the Explorer's Search Companion or Find File window at the indicated folder. For example: Run "find D:\" |
116 |
explore | 119 |Opens an instance of Explorer at the indicated folder. For example: Run "explore " A_ProgramFiles . |
120 |
edit | 123 |Opens the indicated file for editing. It might not work if the indicated file's type does not have an "edit" action associated with it. For example: Run 'edit "C:\My File.txt"' |
124 |
open | 127 |Opens the indicated file (normally not needed because it is the default action for most file types). For example: Run 'open "My File.txt"' . |
128 |
Prints the indicated file with the associated application, if any. For example: Run 'print "My File.txt"' |
132 |
While RunWait is in a waiting state, new threads can be launched via hotkey, custom menu item, or timer.
135 | 136 |For an executable file, the *RunAs verb is equivalent to selecting Run as administrator from the right-click menu of the file. For example, the following code attempts to restart the current script as admin:
138 |full_command_line := DllCall("GetCommandLine", "str") 139 | 140 | if not (A_IsAdmin or RegExMatch(full_command_line, " /restart(?!\S)")) 141 | { 142 | try 143 | { 144 | if A_IsCompiled 145 | Run '*RunAs "' A_ScriptFullPath '" /restart' 146 | else 147 | Run '*RunAs "' A_AhkPath '" /restart "' A_ScriptFullPath '"' 148 | } 149 | ExitApp 150 | } 151 | 152 | MsgBox "A_IsAdmin: " A_IsAdmin "`nCommand line: " full_command_line153 |
If the user cancels the User Account Control (UAC) dialog or Run fails for some other reason, the script will simply exit.
154 |Using /restart ensures that a single instance prompt is not shown if the new instance of the script starts before ExitApp is called.
155 |If UAC is disabled, *RunAs will launch the process without elevating it. Checking for /restart
in the command line ensures that the script does not enter a runaway loop in that case. Note that /restart
is a built-in switch, so is not included in the array of command-line parameters.
The example can be modified to fit the script's needs:
157 |/restart
causes the new instance to terminate the old one. On failure, the new instance exits and RunWait returns.AutoHotkey's installer registers the RunAs verb for .ahk files, which allows Run "*RunAs script.ahk"
to launch a script as admin.
RunAs, Process functions, Exit, CLSID List, DllCall
166 | 167 |Run is able to launch Windows system programs from any directory. Note that executable file extensions such as .exe can be omitted.
170 |Run "notepad"171 |
The following opens an internet address in the user's default web browser.
176 |Run "https://www.google.com"177 |
The following opens the default e-mail application with the recipient filled in.
178 |Run "mailto:someone@somedomain.com"179 |
The following does the same as above, plus the subject and body.
180 |Run "mailto:someone@somedomain.com?subject=This is the subject line&body=This is the message body's text."181 |
Opens a document in a maximized application and displays a custom error message on failure.
185 |try Run("ReadMe.doc", , "Max") 186 | if A_LastError 187 | MsgBox "The document could not be launched."188 |
Runs the dir command in minimized state and stores the output in a text file. After that, the text file and its properties dialog will be opened.
192 |RunWait A_ComSpec " /c dir C:\ >>C:\DirTest.txt", , "Min" 193 | Run "C:\DirTest.txt" 194 | Run "properties C:\DirTest.txt" 195 | Persistent ; Keep the script from exiting, otherwise the properties dialog will close.196 |
Run is able to launch CLSIDs:
200 |The following opens the Recycle Bin.
201 |Run "::{645FF040-5081-101B-9F08-00AA002F954E}"202 |
The following opens This PC (formerly My Computer or Computer).
203 |Run "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"204 |
To run multiple commands consecutively, use "&&" between each.
208 |Run A_ComSpec "/c dir /b > C:\list.txt && type C:\list.txt && pause"209 |
The following custom functions can be used to run a command and retrieve its output or to run multiple commands in one go and retrieve their output. For the WshShell object, see Microsoft Docs.
213 |MsgBox RunWaitOne("dir " A_ScriptDir) 214 | 215 | MsgBox RunWaitMany(" 216 | ( 217 | echo Put your commands here, 218 | echo each one will be run, 219 | echo and you'll get the output. 220 | )") 221 | 222 | RunWaitOne(command) { 223 | shell := ComObject("WScript.Shell") 224 | ; Execute a single command via cmd.exe 225 | exec := shell.Exec(A_ComSpec " /C " command) 226 | ; Read and return the command's output 227 | return exec.StdOut.ReadAll() 228 | } 229 | 230 | RunWaitMany(commands) { 231 | shell := ComObject("WScript.Shell") 232 | ; Open cmd.exe with echoing of commands disabled 233 | exec := shell.Exec(A_ComSpec " /Q /K echo off") 234 | ; Send the commands to execute, separated by newline 235 | exec.StdIn.WriteLine(commands "`nexit") ; Always exit at the end! 236 | ; Read and return the output of all commands 237 | return exec.StdOut.ReadAll() 238 | } 239 |240 |
Executes the given code as a new AutoHotkey process.
244 |ExecScript(Script, Wait:=true) 245 | { 246 | shell := ComObject("WScript.Shell") 247 | exec := shell.Exec("AutoHotkey.exe /ErrorStdOut *") 248 | exec.StdIn.Write(Script) 249 | exec.StdIn.Close() 250 | if Wait 251 | return exec.StdOut.ReadAll() 252 | } 253 | 254 | ; Example: 255 | ib := InputBox("Enter an expression to evaluate as a new script.",,, 'Ord("*")') 256 | if ib.result = "Cancel" 257 | return 258 | result := ExecScript('FileAppend ' ib.value ', "*"') 259 | MsgBox "Result: " result 260 |261 |
Specifies a set of user credentials to use for all subsequent Run and RunWait functions.
16 | 17 |RunAs User, Password, Domain18 |
Type: String
24 |If this and the other parameters are all omitted, the RunAs feature will be turned off, which restores Run and RunWait to their default behavior. Otherwise, specify the username under which new processes will be created.
25 |Type: String
30 |If blank or omitted, it defaults to a blank password. Otherwise, specify the User's password. Note that passing blank passwords is not allowed by default, according to the OS policy "Accounts: Limit local account use of blank passwords to console logon only".
31 |Type: String
36 |If blank or omitted, a local account will be used. Otherwise, specify User's domain. If that fails to work, try using @YourComputerName.
37 |If the script is running with restricted privileges due to User Account Control (UAC), any programs it launches will typically also be restricted, even if RunAs is used. To elevate a process, use Run *RunAs instead.
42 |This function does nothing other than notify AutoHotkey to use (or not use) alternate user credentials for all subsequent Run and RunWait functions. The credentials are not validated by this function.
43 |If an invalid User, Password, and/or Domain is specified, Run and RunWait will display an error message explaining the problem (unless this error is caught by a Try/Catch statement).
44 |While the RunAs feature is in effect, Run and RunWait will not able to launch documents, URLs, or system verbs. In other words, the file to be launched must be an executable file.
45 |The "Secondary Logon" service must be set to manual or automatic for this function to work (the OS should automatically start it upon demand if set to manual).
46 |Opens the registry editor as administrator.
51 |RunAs "Administrator", "MyPassword" 52 | Run "RegEdit.exe" 53 | RunAs ; Reset to normal behavior.54 |
Sends simulated keystrokes and mouse clicks to the active window.
16 | 17 |Send Keys 18 | SendText Keys 19 | SendInput Keys 20 | SendPlay Keys 21 | SendEvent Keys22 | 23 |
Type: String
29 |The sequence of keys to send.
30 |By default (that is, if neither SendText nor the Raw mode or Text mode is used), the characters ^+!#{}
have a special meaning. The characters ^+!#
represent the modifier keys Ctrl, Shift, Alt and Win. They affect only the very next key. To send the corresponding modifier key on its own, enclose the key name in braces. To just press (hold down) or release the key, follow the key name with the word "down" or "up" as shown below.
Symbol | 40 |Key | 41 |Press | 42 |Release | 43 |Examples | 44 |
---|---|---|---|---|
^ | 47 |{Ctrl} | 48 |{Ctrl down} | 49 |{Ctrl up} | 50 |Send "^{Home}" presses Ctrl+Home |
51 |
+ | 54 |{Shift} | 55 |{Shift down} | 56 |{Shift up} | 57 |Send "+abC" sends the text "AbC"58 | Send "!+a" presses Alt+Shift+A |
59 |
! | 62 |{Alt} | 63 |{Alt down} | 64 |{Alt up} | 65 |Send "!a" presses Alt+A |
66 |
# | 69 |{LWin} {RWin} |
70 | {LWin down} {RWin down} |
71 | {LWin up} {RWin up} |
72 | Send "#e" holds down Win and presses E |
73 |
Note: As capital letters are produced by sending Shift, A
produces a different effect in some programs than a
. For example, !A
presses Alt+Shift+A and !a
presses Alt+A. If in doubt, use lowercase.
The characters {}
are used to enclose key names and other options, and to send special characters literally. For example, {Tab}
is Tab and {!}
is a literal exclamation mark.
Enclosing a plain ASCII letter (a-z or A-Z) in braces forces it to be sent as the corresponding virtual keycode, even if the character does not exist on the current keyboard layout. In other words, Send "a"
produces the letter "a" while Send "{a}"
may or may not produce "a", depending on the keyboard layout. For details, see the remarks below.
Send: By default, Send is synonymous with SendInput; but it can be made a synonym for SendEvent or SendPlay via SendMode.
84 |SendText: Similar to Send, except that all characters in Keys are interpreted and sent literally. See Text mode for details.
85 |SendInput: SendInput uses the same syntax as SendEvent but is generally faster and more reliable. In addition, it buffers any physical keyboard or mouse activity during the send, which prevents the user's keystrokes from being interspersed with those being sent. SendMode can be used to make Send synonymous with SendInput. See SendInput for details.
86 |SendPlay: Deprecated. Similar to SendInput, except that it may have no effect at all on Windows 11 and later, or if User Account Control (UAC) is enabled, even if the script is running as an administrator. See SendPlay for details.
87 |SendEvent: SendEvent sends keystrokes using the Windows keybd_event function (search Microsoft Docs for details). The rate at which keystrokes are sent is determined by SetKeyDelay. SendMode can be used to make Send synonymous with SendEvent.
88 | 89 |The following modes affect the interpretation of the characters in Keys or the behavior of key-sending functions such as Send, SendInput, SendPlay, SendEvent and ControlSend. These modes must be specified as {x}
in Keys, where x is either Raw, Text, or Blind. For example, {Raw}
.
The Raw mode can be enabled with {Raw}
, which causes all subsequent characters, including the special characters ^+!#{}
, to be interpreted literally rather than translating {Enter}
to Enter, ^c
to Ctrl+C, etc. For example, Send "{Raw}{Tab}"
sends {Tab}
instead of Tab.
The Raw mode does not affect the interpretation of escape sequences and expressions. For example, Send "{Raw}``100`%"
sends the string `100%
.
The Text mode can be either enabled with {Text}
, SendText or ControlSendText, which is similar to the Raw mode, except that no attempt is made to translate characters (other than `r
, `n
, `t
and `b
) to keycodes; instead, the fallback method is used for all of the remaining characters. For SendEvent, SendInput and ControlSend, this improves reliability because the characters are much less dependent on correct modifier state. This mode can be combined with the Blind mode to avoid releasing any modifier keys: Send "{Blind}{Text}your text"
. However, some applications require that the modifier keys be released.
`n
, `r
and `r`n
are all translated to a single Enter, unlike the default behavior and Raw mode, which translate `r`n
to two Enter. `t
is translated to Tab and `b
to Backspace, but all other characters are sent without translation.
Like the Blind mode, the Text mode ignores SetStoreCapsLockMode (that is, the state of CapsLock is not changed) and does not wait for Win to be released. This is because the Text mode typically does not depend on the state of CapsLock and cannot trigger the system Win+L hotkey. However, this only applies when Keys begins with {Text}
or {Blind}{Text}
.
The Blind mode can be enabled with {Blind}
, which gives the script more control by disabling a number of things that are normally done automatically to make things work as expected. {Blind}
must be the first item in the string to enable the Blind mode. It has the following effects:
+s::Send "{Blind}abc"
would send ABC rather than abc because the user is holding down Shift.^space::Send "{Ctrl up}"
automatically pushes Ctrl back down if the user is still physically holding Ctrl, whereas ^space::Send "{Blind}{Ctrl up}"
allows Ctrl to be logically up even though it is physically down.The word "Blind" may be followed by one or more modifier symbols (!#^+
) to allow those modifiers to be released automatically if needed. For example, *^a::Send "{Blind^}b"
would send Shift+B instead of Ctrl+Shift+B if Ctrl+Shift+A was pressed. {Blind!#^+}
allows all modifiers to be released if needed, but enables the other effects of the Blind mode.
The Blind mode is used internally when remapping a key. For example, the remapping a::b
would produce: 1) "b" when you type "a"; 2) uppercase "B" when you type uppercase "A"; and 3) Ctrl+B when you type Ctrl+A. If any modifiers are specified for the source key (including Shift if the source key is an uppercase letter), they are excluded as described above. For example ^a::b
produces normal B, not Ctrl+B.
{Blind}
is not supported by SendText or ControlSendText; use {Blind}{Text}
instead.
The Blind mode is not completely supported by SendPlay, especially when dealing with the modifier keys (Ctrl, Alt, Shift, and Win).
114 | 115 |The following table lists the special keys that can be sent (each key name must be enclosed in braces):
117 |Key name | 120 |Description | 121 |
---|---|
{F1} - {F24} | 124 |Function keys. For example: {F12} is F12. | 125 |
{!} | 128 |! | 129 |
{#} | 132 |# | 133 |
{+} | 136 |+ | 137 |
{^} | 140 |^ | 141 |
{{} | 144 |{ | 145 |
{}} | 148 |} | 149 |
{Enter} | 152 |Enter on the main keyboard | 153 |
{Escape} or {Esc} | 156 |Esc | 157 |
{Space} | 160 |Space (this is only needed for spaces that appear either at the beginning or the end of the string to be sent -- ones in the middle can be literal spaces) | 161 |
{Tab} | 164 |Tab | 165 |
{Backspace} or {BS} | 168 |Backspace | 169 |
{Delete} or {Del} | 172 |Del | 173 |
{Insert} or {Ins} | 176 |Ins | 177 |
{Up} | 180 |↑ (up arrow) on main keyboard | 181 |
{Down} | 184 |↓ (down arrow) on main keyboard | 185 |
{Left} | 188 |← (left arrow) on main keyboard | 189 |
{Right} | 192 |→ (right arrow) on main keyboard | 193 |
{Home} | 196 |Home on main keyboard | 197 |
{End} | 200 |End on main keyboard | 201 |
{PgUp} | 204 |PgUp on main keyboard | 205 |
{PgDn} | 208 |PgDn on main keyboard | 209 |
{CapsLock} | 212 |CapsLock (using SetCapsLockState is more reliable). Sending {CapsLock} might require SetStoreCapsLockMode False beforehand. |
213 |
{ScrollLock} | 216 |ScrollLock (see also: SetScrollLockState) | 217 |
{NumLock} | 220 |NumLock (see also: SetNumLockState) | 221 |
{Control} or {Ctrl} | 224 |Ctrl (technical info: sends the neutral virtual key but the left scan code) | 225 |
{LControl} or {LCtrl} | 228 |Left Ctrl (technical info: sends the left virtual key rather than the neutral one) | 229 |
{RControl} or {RCtrl} | 232 |Right Ctrl | 233 |
{Control down} or {Ctrl down} | 236 |Holds Ctrl down until {Ctrl up} is sent. To hold down the left or right key instead, replace Ctrl with LCtrl or RCtrl. | 237 |
{Alt} | 240 |Alt (technical info: sends the neutral virtual key but the left scan code) | 241 |
{LAlt} | 244 |Left Alt (technical info: sends the left virtual key rather than the neutral one) | 245 |
{RAlt} | 248 |Right Alt (or AltGr, depending on keyboard layout) | 249 |
{Alt down} | 252 |Holds Alt down until {Alt up} is sent. To hold down the left or right key instead, replace Alt with LAlt or RAlt. | 253 |
{Shift} | 256 |Shift (technical info: sends the neutral virtual key but the left scan code) | 257 |
{LShift} | 260 |Left Shift (technical info: sends the left virtual key rather than the neutral one) | 261 |
{RShift} | 264 |Right Shift | 265 |
{Shift down} | 268 |Holds Shift down until {Shift up} is sent. To hold down the left or right key instead, replace Shift with LShift or RShift. | 269 |
{LWin} | 272 |Left Win | 273 |
{RWin} | 276 |Right Win | 277 |
{LWin down} | 280 |Holds the left Win down until {LWin up} is sent | 281 |
{RWin down} | 284 |Holds the right Win down until {RWin up} is sent | 285 |
{AppsKey} | 288 |Menu (invokes the right-click or context menu) | 289 |
{Sleep} | 292 |Sleep | 293 |
{ASC nnnnn} | 296 |Sends an Alt+nnnnn keypad combination, which can be used to generate special characters that don't exist on the keyboard. To generate printable ASCII characters or other characters from code page 437, specify a number between 1 and 255. To generate ANSI characters (standard in most languages), specify a number between 128 and 255, but precede it with a leading zero, e.g. {Asc 0133}. 297 |Unicode characters may be generated by specifying a number between 256 and 65535 (without a leading zero). However, this is not supported by all applications. For alternatives, see the section below. |
298 |
{U+nnnn} | 301 |Sends a Unicode character where nnnn is the hexadecimal value of the character excluding the 0x prefix. This typically isn't needed, because Send and ControlSend automatically support Unicode text. 302 |SendInput() or WM_CHAR is used to send the character and the current Send mode has no effect. Characters sent this way usually do not trigger shortcut keys or hotkeys. |
303 |
{vkXX} |
308 | Sends a keystroke that has virtual key XX and scan code YYY. For example: The values for XX and YYY are hexadecimal and can usually be determined from the main window's View->Key history menu item. See also: Special Keys 310 |Warning: Combining vk and sc in this manner is valid only with Send. |
311 |
{Numpad0} - {Numpad9} | 314 |Numpad digit keys (as seen when NumLock is ON). For example: {Numpad5} is 5. | 315 |
{NumpadDot} | 318 |. (numpad period) (as seen when NumLock is ON). | 319 |
{NumpadEnter} | 322 |Enter on keypad | 323 |
{NumpadMult} | 326 |* (numpad multiplication) | 327 |
{NumpadDiv} | 330 |/ (numpad division) | 331 |
{NumpadAdd} | 334 |+ (numpad addition) | 335 |
{NumpadSub} | 338 |- (numpad subtraction) | 339 |
{NumpadDel} | 342 |Del on keypad (this key and the following Numpad keys are used when NumLock is OFF) | 343 |
{NumpadIns} | 346 |Ins on keypad | 347 |
{NumpadClear} | 350 |Clear key on keypad (usually 5 when NumLock is OFF). | 351 |
{NumpadUp} | 354 |↑ (up arrow) on keypad | 355 |
{NumpadDown} | 358 |↓ (down arrow) on keypad | 359 |
{NumpadLeft} | 362 |← (left arrow) on keypad | 363 |
{NumpadRight} | 366 |→ (right arrow) on keypad | 367 |
{NumpadHome} | 370 |Home on keypad | 371 |
{NumpadEnd} | 374 |End on keypad | 375 |
{NumpadPgUp} | 378 |PgUp on keypad | 379 |
{NumpadPgDn} | 382 |PgDn on keypad | 383 |
{Browser_Back} | 386 |Select the browser "back" button | 387 |
{Browser_Forward} | 390 |Select the browser "forward" button | 391 |
{Browser_Refresh} | 394 |Select the browser "refresh" button | 395 |
{Browser_Stop} | 398 |Select the browser "stop" button | 399 |
{Browser_Search} | 402 |Select the browser "search" button | 403 |
{Browser_Favorites} | 406 |Select the browser "favorites" button | 407 |
{Browser_Home} | 410 |Launch the browser and go to the home page | 411 |
{Volume_Mute} | 414 |Mute/unmute the master volume. Usually equivalent to SoundSetMute -1 . |
415 |
{Volume_Down} | 418 |Reduce the master volume. Usually equivalent to SoundSetVolume -5 . |
419 |
{Volume_Up} | 422 |Increase the master volume. Usually equivalent to SoundSetVolume "+5" . |
423 |
{Media_Next} | 426 |Select next track in media player | 427 |
{Media_Prev} | 430 |Select previous track in media player | 431 |
{Media_Stop} | 434 |Stop media player | 435 |
{Media_Play_Pause} | 438 |Play/pause media player | 439 |
{Launch_Mail} | 442 |Launch the email application | 443 |
{Launch_Media} | 446 |Launch media player | 447 |
{Launch_App1} | 450 |Launch user app1 | 451 |
{Launch_App2} | 454 |Launch user app2 | 455 |
{PrintScreen} | 458 |PrtSc | 459 |
{CtrlBreak} | 462 |Ctrl+Pause | 463 |
{Pause} | 466 |Pause | 467 |
{Click [Options]} | 470 |Sends a mouse click using the same options available in the Click function. For example, Send "{Click}" would click the left mouse button once at the mouse cursor's current position, and Send "{Click 100 200}" would click at coordinates 100, 200 (based on CoordMode). To move the mouse without clicking, specify 0 after the coordinates; for example: Send "{Click 100 200 0}" . The delay between mouse clicks is determined by SetMouseDelay (not SetKeyDelay). |
471 |
{WheelDown}, {WheelUp}, {WheelLeft}, {WheelRight}, {LButton}, {RButton}, {MButton}, {XButton1}, {XButton2} | 474 |
475 | Sends a mouse button event at the cursor's current position (to have control over position and other options, use {Click} above). The delay between mouse clicks is determined by SetMouseDelay. 476 |LButton and RButton correspond to the primary and secondary mouse buttons. Normally the primary mouse button (LButton) is on the left, but the user may swap the buttons via system settings. 477 | |
478 |
{Blind} | 481 |Enables the Blind mode, which gives the script more control by disabling a number of things that are normally done automatically to make things generally work as expected. {Blind} must occur at the beginning of the string. |
482 |
{Raw} | 485 |Enables the Raw mode, which causes the following characters to be interpreted literally: ^+!#{} . Although {Raw} need not occur at the beginning of the string, once specified, it stays in effect for the remainder of the string. |
486 |
{Text} | 489 |Enables the Text mode, which sends a stream of characters rather than keystrokes. Like the Raw mode, the Text mode causes the following characters to be interpreted literally: ^+!#{} . Although {Text} need not occur at the beginning of the string, once specified, it stays in effect for the remainder of the string. |
490 |
To repeat a keystroke: Enclose in braces the name of the key followed by the number of times to repeat it. For example:
495 |Send "{DEL 4}" ; Presses the Delete key 4 times. 496 | Send "{S 30}" ; Sends 30 uppercase S characters. 497 | Send "+{TAB 4}" ; Presses Shift-Tab 4 times.498 |
To hold down or release a key: Enclose in braces the name of the key followed by the word Down or Up. For example:
499 |Send "{b down}{b up}" 500 | Send "{TAB down}{TAB up}" 501 | Send "{Up down}" ; Presses down the up-arrow key. 502 | Sleep 1000 ; Keeps it down for one second. 503 | Send "{Up up}" ; Releases the up-arrow key.504 |
When a key is held down via the method above, it does not begin auto-repeating like it would if you were physically holding it down (this is because auto-repeat is a driver/hardware feature). However, a Loop can be used to simulate auto-repeat. The following example sends 20 tab keystrokes:
505 |Loop 20 506 | { 507 | Send "{Tab down}" ; Auto-repeat consists of consecutive down-events (with no up-events). 508 | Sleep 30 ; The number of milliseconds between keystrokes (or use SetKeyDelay). 509 | } 510 | Send "{Tab up}" ; Release the key.511 |
By default, Send will not automatically release a modifier key (Control, Shift, Alt, and Win) if that modifier key was "pressed down" by sending it. For example, Send "a"
may behave similar to Send "{Blind}{Ctrl up}a{Ctrl down}"
if the user is physically holding Ctrl, but Send "{Ctrl Down}"
followed by Send "a"
will produce Ctrl+A. DownTemp and DownR can be used to override this behavior. DownTemp and DownR have the same effect as Down except for the modifier keys (Control, Shift, Alt, and Win).
DownTemp tells subsequent sends that the key is not permanently down, and may be released whenever a keystroke calls for it. For example, Send "{Control DownTemp}"
followed later by Send "a"
would produce A, not Ctrl+A. Any use of Send may potentially release the modifier permanently, so DownTemp is not ideal for remapping modifier keys.
DownR (where "R" stands for remapping, which is its main use) tells subsequent sends that if the key is automatically released, it should be pressed down again when send is finished. For example, Send "{Control DownR}"
followed later by Send "a"
would produce A, not Ctrl+A, but will leave Ctrl in the pressed state for use with keyboard shortcuts. In other words, DownR has an effect similar to physically pressing the key.
If a character does not correspond to a virtual key on the current keyboard layout, it cannot be "pressed" or "released". For example, Send "{µ up}"
has no effect on most layouts, and Send "{µ down}"
is equivalent to Send "µ"
.
Characters vs. keys: By default, characters are sent by first translating them to keystrokes. If this translation is not possible (that is, if the current keyboard layout does not contain a key or key combination which produces that character), the character is sent by one of following fallback methods:
518 |Note: Characters sent using any of the above methods usually do not trigger keyboard shortcuts or hotkeys.
524 |For characters in the range a-z or A-Z (plain ASCII letters), each character which does not exist in the current keyboard layout may be sent either as a character or as the corresponding virtual keycode (vk41-vk5A):
525 |Send "{Raw}Regards"
sends the expected text, even though pressing R (vk52) produces some other character (such as К on the Russian layout). {Raw}
can be omitted in this case, unless a modifier key was put into effect by a prior Send.^c
and {Ctrl down}c{Ctrl up}
activate the standard Ctrl+C shortcut and {c}
is equivalent to {vk43}
.If the letter exists in the current keyboard layout, it is always sent as whichever keycode the layout associates with that letter (unless the Text mode is used, in which case the character is sent by other means). In other words, the section above is only relevant for non-Latin based layouts such as Russian.
530 |Modifier State: When Send is required to change the state of the Win or Alt modifier keys (such as if the user was holding one of those keys), it may inject additional keystrokes (Ctrl by default) to prevent the Start menu or window menu from appearing. For details, see A_MenuMaskKey.
531 |BlockInput Compared to SendInput/SendPlay: Although the BlockInput function can be used to prevent any keystrokes physically typed by the user from disrupting the flow of simulated keystrokes, it is often better to use SendInput or SendPlay so that keystrokes and mouse clicks become uninterruptible. This is because unlike BlockInput, SendInput/Play does not discard what the user types during the send; instead, such keystrokes are buffered and sent afterward.
532 |When sending a large number of keystrokes, a continuation section can be used to improve readability and maintainability.
533 |Since the operating system does not allow simulation of the Ctrl+Alt+Del combination, doing something like Send "^!{Delete}"
will have no effect.
Send may have no effect if the active window is running with administrative privileges and the script is not. This is due to a security mechanism called User Interface Privilege Isolation.
535 | 536 |SendInput is generally the preferred method to send keystrokes and mouse clicks because of its superior speed and reliability. Under most conditions, SendInput is nearly instantaneous, even when sending long strings. Since SendInput is so fast, it is also more reliable because there is less opportunity for some other window to pop up unexpectedly and intercept the keystrokes. Reliability is further improved by the fact that anything the user types during a SendInput is postponed until afterward.
538 |Unlike the other sending modes, the operating system limits SendInput to about 5000 characters (this may vary depending on the operating system's version and performance settings). Characters and events beyond this limit are not sent.
539 |Note: SendInput ignores SetKeyDelay because the operating system does not support a delay in this mode. However, when SendInput reverts to SendEvent under the conditions described below, it uses SetKeyDelay -1, 0
(unless SendEvent's KeyDelay is -1,-1
, in which case -1,-1
is used). When SendInput reverts to SendPlay, it uses SendPlay's KeyDelay.
If the script has a low-level keyboard hook installed, SendInput automatically uninstalls it prior to executing and reinstalls it afterward. As a consequence, SendInput generally cannot trigger the script's own hook hotkeys or InputHooks. The hook is temporarily uninstalled because its presence would otherwise disable all of SendInput's advantages, making it inferior to both SendPlay and SendEvent. However, this can only be done for the script's own hook, and is not done if an external hook is detected as described below.
541 | 542 |When SendInput sends mouse clicks by means such as {Click}, and CoordMode "Mouse", "Window"
or CoordMode "Mouse", "Client"
is in effect, every click will be relative to the window that was active at the start of the send. Therefore, if SendInput intentionally activates another window (by means such as alt-tab), the coordinates of subsequent clicks within the same function will be wrong if they were intended to be relative to the new window rather than the old one.
Deprecated: SendPlay may have no effect at all on Windows 11 and later, or if User Account Control (UAC) is enabled, even if the script is running as an administrator (for more information, refer to the FAQ).
546 |SendPlay's biggest advantage is its ability to "play back" keystrokes and mouse clicks in a broader variety of games than the other modes. For example, a particular game may accept hotstrings only when they have the SendPlay option.
547 |Of the three sending modes, SendPlay is the most unusual because it does not simulate keystrokes and mouse clicks per se. Instead, it creates a series of events (messages) that flow directly to the active window (similar to ControlSend, but at a lower level). Consequently, SendPlay does not trigger hotkeys or hotstrings.
548 |Like SendInput, SendPlay's keystrokes do not get interspersed with keystrokes typed by the user. Thus, if the user happens to type something during a SendPlay, those keystrokes are postponed until afterward.
549 |Although SendPlay is considerably slower than SendInput, it is usually faster than the traditional SendEvent mode (even when KeyDelay is -1).
550 |Both Win (LWin and RWin) are automatically blocked during a SendPlay if the keyboard hook is installed. This prevents the Start Menu from appearing if the user accidentally presses Win during the send. By contrast, keys other than LWin and RWin do not need to be blocked because the operating system automatically postpones them until after the SendPlay (via buffering).
551 |SendPlay does not use the standard settings of SetKeyDelay and SetMouseDelay. Instead, it defaults to no delay at all, which can be changed as shown in the following examples:
552 |SetKeyDelay 0, 10, "Play" ; Note that both 0 and -1 are the same in SendPlay mode. 553 | SetMouseDelay 10, "Play"554 |
SendPlay is unable to turn on or off CapsLock, NumLock, or ScrollLock. Similarly, it is unable to change a key's state as seen by GetKeyState unless the keystrokes are sent to one of the script's own windows. Even then, any changes to the left/right modifier keys (e.g. RControl) can be detected only via their neutral counterparts (e.g. Control). Also, SendPlay has other limitations described on the SendMode page.
555 |Unlike SendInput and SendEvent, the user may interrupt a SendPlay by pressing Ctrl+Alt+Del or Ctrl+Esc. When this happens, the remaining keystrokes are not sent but the script continues executing as though the SendPlay had completed normally.
556 |Although SendPlay can send LWin and RWin events, they are sent directly to the active window rather than performing their native operating system function. To work around this, use SendEvent. For example, SendEvent "#r"
would show the Start Menu's Run dialog.
SendMode, SetKeyDelay, SetStoreCapsLockMode, Escape sequences (e.g. `n), ControlSend, BlockInput, Hotstrings, WinActivate
560 | 561 |Jumps to the end of the text then send four shift+left-arrow keystrokes.
574 |Send "{End}+{Left 4}"575 |
Sends a long series of raw characters via the fastest method.
579 |SendInput "{Raw}A long series of raw characters sent via the fastest method."580 |
Holds down a key contained in a variable.
584 |MyKey := "Shift" 585 | Send "{" MyKey " down}" ; Holds down the Shift key. 586 |587 |
Controls which artificial keyboard and mouse events are ignored by hotkeys and hotstrings.
15 |SendLevel Level
16 |
17 | Type: Integer
23 |An integer between 0 and 100.
24 |Type: Integer
30 |This function returns the previous setting; an integer between 0 and 100.
31 | 32 |If SendLevel is not used, the default level is 0.
34 |By default, hook hotkeys and hotstrings ignore keyboard and mouse events generated by any AutoHotkey script. In some cases it can be useful to override this behaviour; for instance, to allow a remapped key to be used to trigger other hotkeys. SendLevel and #InputLevel provide the means to achieve this.
35 |SendLevel sets the level for events generated by the current script thread, while #InputLevel sets the level for any hotkeys or hotstrings beneath it. For any event generated by a script to trigger a hook hotkey or hotstring, the send level of the event must be higher than the input level of the hotkey or hotstring.
36 |Compatibility:
37 |::btw::
can be triggered regardless of #InputLevel by sending btw
at level 1 or higher and physically typing an ending character. This is because hotstring recognition works by collecting input from all levels except level 0 into a single global buffer.The built-in variable A_SendLevel contains the current setting.
47 |Every newly launched hotkey or hotstring thread starts off with a send level equal to the input level of the hotkey or hotstring. Every other newly launched thread (such as a custom menu item or timed subroutine) starts off fresh with the default setting, which is typically 0 but may be changed by using this function during script startup.
48 |If SendLevel is used during script startup, it also affects keyboard and mouse remapping.
49 |AutoHotkey versions older than v1.1.06 behave as though #InputLevel 0
and SendLevel 0
are in effect.
#InputLevel, Send, Click, MouseClick, MouseClickDrag
53 | 54 |SendLevel allows to trigger hotkeys and hotstrings of another script, which normally would not be the case.
57 |58 | SendLevel 1 59 | SendEvent "btw{Space}" ; Produces "by the way ". 60 | 61 | ; This may be defined in a separate script: 62 | ::btw::by the way 63 |64 |
Sends a message to a window or control and waits for acknowledgement.
17 | 18 |Result := SendMessage(MsgNumber , wParam, lParam, Control, WinTitle, WinText, ExcludeTitle, ExcludeText, Timeout)19 |
Type: Integer
25 |The message number to send. See the message list to determine the number.
26 |If either is omitted, 0 will be sent. Otherwise, specify the first and second component of the message.
32 |Each parameter must be an integer or an object with a Ptr property, such as a Buffer. For messages which require a pointer to a string, use a Buffer or the StrPtr function. If the string contained by a variable is changed by passing the variable's address to SendMessage, the variable's length must be updated afterward by calling VarSetStrCapacity(&MyVar, -1).
33 |If AutoHotkey or the target window is 32-bit, only the parameter's low 32 bits are used; that is, values are truncated if outside the range -2147483648 to 2147483647 (-0x80000000 to 0x7FFFFFFF) for signed values, or 0 to 4294967295 (0xFFFFFFFF) for unsigned values. If AutoHotkey and the target window are both 64-bit, any integer value supported by AutoHotkey can be used.
34 |Type: String, Integer or Object
39 |If omitted, the message will be sent directly to the target window rather than one of its controls. Otherwise, specify the control's ClassNN, text or HWND, or an object with a Hwnd
property. For details, see The Control Parameter.
If this parameter specifies a HWND (as an integer or object), it is not required to be the HWND of a control (child window). That is, it can also be the HWND of a top-level window.
41 |Type: String, Integer or Object
46 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
47 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
48 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
49 |Type: Integer
54 |If omitted, it defaults to 5000. Otherwise, specify the maximum number of milliseconds to wait for the target window to process the message. If the message is not processed within this time, a TimeoutError is thrown. Specify 0 to wait indefinitely. A negative number causes SendMessage to time out immediately.
55 |Type: Integer
61 |This function returns the result of the message, which might sometimes be a "reply" depending on the nature of the message and its target window.
62 |The range of possible values depends on the target window and the version of AutoHotkey that is running. When using a 32-bit version of AutoHotkey, or if the target window is 32-bit, the result is a 32-bit unsigned integer between 0 and 4294967295. When using the 64-bit version of AutoHotkey with a 64-bit window, the result is a 64-bit signed integer between -9223372036854775808 and 9223372036854775807.
63 |If the result is intended to be a 32-bit signed integer (a value from -2147483648 to 2147483648), it can be truncated to 32-bit and converted to a signed value as follows:
64 |MsgReply := MsgReply << 32 >> 3265 |
This conversion may be necessary even on AutoHotkey 64-bit, because results from 32-bit windows are zero-extended. For example, a result of -1 from a 32-bit window is seen as 0xFFFFFFFF on any version of AutoHotkey, whereas a result of -1 from a 64-bit window is seen as 0xFFFFFFFF on AutoHotkey 32-bit and -1 on AutoHotkey 64-bit.
66 | 67 |A TargetError is thrown if the window or control could not be found.
69 |A TimeoutError is thrown if the message timed out.
70 |An OSError is thrown if the message could not be sent. For example, if the target window is running at a higher integrity level than the script (i.e. it is running as admin while the script is not), messages may be blocked.
71 | 72 |This function should be used with caution because sending a message to the wrong window (or sending an invalid message) might cause unexpected behavior or even crash the target application. This is because most applications are not designed to expect certain types of messages from external sources.
74 |SendMessage waits for the target window to process the message, up until the timeout period expires. By contrast, PostMessage places the message in the message queue associated with the target window without waiting for acknowledgement or reply.
75 |String parameters must be passed by address. For example:
76 |ListVars 77 | WinWaitActive "ahk_class AutoHotkey" 78 | SendMessage 0x000C, 0, StrPtr("New Title") ; 0X000C is WM_SETTEXT79 |
To send a message to all windows in the system, including those that are hidden or disabled, specify 0xFFFF
for WinTitle (0xFFFF is HWND_BROADCAST). This technique should be used only for messages intended to be broadcast, such as the following example:
SendMessage 0x001A,,,, 0xFFFF ; 0x001A is WM_SETTINGCHANGE81 |
To have a script receive a message, use OnMessage.
82 |See the Message Tutorial for an introduction to using this function.
83 | 84 |PostMessage, Message List, Message Tutorial, OnMessage, Automating Winamp, DllCall, ControlSend, MenuSelect
86 | 87 |Turns off the monitor via hotkey. In the SendMessage line, replace the number 2 with -1 to turn on the monitor, or replace it with 1 to activate the monitor's low-power mode.
91 |#o:: ; Win+O hotkey 92 | { 93 | Sleep 1000 ; Give user a chance to release keys (in case their release would wake up the monitor again). 94 | ; Turn Monitor Off: 95 | SendMessage 0x0112, 0xF170, 2,, "Program Manager" ; 0x0112 is WM_SYSCOMMAND, 0xF170 is SC_MONITORPOWER. 96 | }97 |
Starts the user's chosen screen saver.
101 |SendMessage 0x0112, 0xF140, 0,, "Program Manager" ; 0x0112 is WM_SYSCOMMAND, and 0xF140 is SC_SCREENSAVE.102 |
Scrolls up by one line (for a control that has a vertical scroll bar).
106 |SendMessage 0x0115, 0, 0, ControlGetFocus("A")107 |
Scrolls down by one line (for a control that has a vertical scroll bar).
111 |SendMessage 0x0115, 1, 0, ControlGetFocus("A")112 |
Asks Winamp which track number is currently active (see Automating Winamp for more information).
116 |SetTitleMatchMode 2 117 | TrackNumber := SendMessage(0x0400, 0, 120,, "- Winamp") 118 | TrackNumber++ ; Winamp's count starts at 0, so adjust by 1. 119 | MsgBox "Track #" TrackNumber " is active or playing." 120 |121 |
Finds the process ID of an AHK script (an alternative to WinGetPID).
125 |SetTitleMatchMode 2 126 | DetectHiddenWindows true 127 | PID := SendMessage(0x0044, 0x405, 0, , "SomeOtherScript.ahk - AutoHotkey v") 128 | MsgBox PID " is the process id."129 |
Makes Send synonymous with SendEvent or SendPlay rather than the default (SendInput). Also makes Click and MouseMove/Click/Drag use the specified method.
16 | 17 |SendMode Mode
18 |
19 | Type: String
24 |Specify one of the following words:
25 |Event: Switches to the SendEvent method for Send, SendText, Click, MouseMove, MouseClick, and MouseClickDrag.
26 |Input: Uses the SendInput method for Send, SendText, Click, MouseMove, MouseClick, and MouseClickDrag. Known limitations:
27 |SendEvent "!{Left}"
or SendInput "{Backspace}"
.InputThenPlay: Same as above except that rather than falling back to Event mode when SendInput is unavailable, it reverts to Play mode (below). This also causes the SendInput function itself to revert to Play mode when SendInput is unavailable.
31 |Play: Switches to the SendPlay method for Send, SendText, Click, MouseMove, MouseClick, and MouseClickDrag. Known limitations:
32 |SendEvent "{Click 6 52 Down}{Click 45 52 Up}"
.SendEvent "{WheelDown 5}"
.SendMode "Play"
is called during script startup, all remapped keys are affected and might lose some of their functionality. See SendPlay remapping limitations for details.Type: String
44 |This function returns the previous setting; either Event, Input, InputThenPlay or Play.
45 | 46 |If SendMode is not used, the default mode is Input.
48 |Since SendMode also changes the mode of Click, MouseMove, MouseClick, and MouseClickDrag, there may be times when you wish to use a different mode for a particular mouse event. The easiest way to do this is via {Click}. For example:
49 |SendEvent "{Click 100 200}" ; SendEvent uses the older, traditional method of clicking.50 |
If SendMode is used during script startup, it also affects keyboard and mouse remapping. In particular, if you use SendMode "Play"
with remapping, see SendPlay remapping limitations.
The built-in variable A_SendMode contains the current setting.
52 |Every newly launched thread (such as a hotkey, custom menu item, or timed subroutine) starts off fresh with the default setting for this function. That default may be changed by using this function during script startup.
53 |Send, SetKeyDelay, SetMouseDelay, Click, MouseClick, MouseClickDrag, MouseMove
55 |Makes Send synonymous with SendInput, but falls back to SendPlay if SendInput is not available.
58 |SendMode "InputThenPlay"59 |
Sets the delay that will occur after each control-modifying function.
16 | 17 |SetControlDelay Delay
18 | Type: Integer
24 |Time in milliseconds. Specify -1 for no delay at all or 0 for the smallest possible delay.
25 |Type: Integer
31 |This function returns the previous setting.
32 | 33 |If SetControlDelay is not used, the default delay is 20.
35 |A short delay (sleep) is done automatically after every Control function that changes a control. This is done to improve the reliability of scripts because a control sometimes needs a period of "rest" after being changed by one of these functions, so that the control has a chance to update itself and respond to the next function that the script may attempt to send to it.
36 |Specifically, SetControlDelay affects the following functions: ControlAddItem, ControlChooseIndex, ControlChooseString, ControlClick, ControlDeleteItem, EditPaste, ControlFindItem, ControlFocus, ControlHide, ControlHideDropDown, ControlMove, ControlSetChecked, ControlSetEnabled, ControlSetText, ControlShow, ControlShowDropDown.
37 |ControlSend is not affected; it uses SetKeyDelay.
38 |Although a delay of -1 (no delay at all) is allowed, it is recommended that at least 0 be used, to increase confidence that the script will run correctly even when the CPU is under load.
39 |A delay of 0 internally executes a Sleep(0), which yields the remainder of the script's timeslice to any other process that may need it. If there is none, Sleep(0) will not sleep at all.
40 |If the CPU is slow or under load, or if window animation is enabled, higher delay values may be needed.
41 |The built-in variable A_ControlDelay contains the current setting and can also be assigned a new value instead of calling SetControlDelay.
42 |Every newly launched thread (such as a hotkey, custom menu item, or timed subroutine) starts off fresh with the default setting for this function. That default may be changed by using this function during script startup.
43 |Control functions, SetWinDelay, SetKeyDelay, SetMouseDelay
45 |Causes the smallest possible delay to occur after each control-modifying function.
48 |SetControlDelay 049 |
Sets the mouse speed that will be used if unspecified in Click, MouseMove, MouseClick, and MouseClickDrag.
16 | 17 |SetDefaultMouseSpeed Speed
18 | Type: Integer
24 |The speed to move the mouse in the range 0 (fastest) to 100 (slowest). A speed of 0 will move the mouse instantly.
25 |Type: Integer
31 |This function returns the previous setting.
32 | 33 |If SetDefaultMouseSpeed is not used, the default mouse speed is 2.
35 |SetDefaultMouseSpeed is ignored for the modes SendInput and SendPlay; they move the mouse instantaneously (except when SendInput reverts to SendEvent; also, SetMouseDelay has a mode that applies to SendPlay). To visually move the mouse more slowly -- such as a script that performs a demonstration for an audience -- use SendEvent "{Click 100 200}"
or SendMode "Event"
(optionally in conjuction with BlockInput).
The built-in variable A_DefaultMouseSpeed contains the current setting.
37 |The functions MouseClick, MouseMove, and MouseClickDrag all have a parameter to override the default mouse speed.
38 |Whenever Speed is greater than zero, SetMouseDelay also influences the speed by producing a delay after each incremental move the mouse makes toward its destination.
39 |Every newly launched thread (such as a hotkey, custom menu item, or timed subroutine) starts off fresh with the default setting for this function. That default may be changed by using this function during script startup.
40 |SetMouseDelay, SendMode, Click, MouseClick, MouseMove, MouseClickDrag, SetWinDelay, SetControlDelay, SetKeyDelay, SetKeyDelay
42 |Sets the delay that will occur after each keystroke sent by Send or ControlSend.
16 | 17 |SetKeyDelay Delay, PressDuration, "Play"18 |
Type: Integer
24 |If omitted, the current delay is retained. Otherwise, specify the time in milliseconds. Specify -1 for no delay at all or 0 for the smallest possible delay (however, if the Play parameter is present, both 0 and -1 produce no delay).
25 |Type: Integer
30 |Certain games and other specialized applications may require a delay inside each keystroke; that is, after the press of the key but before its release.
31 |If omitted, the current press duration is retained. Otherwise, specify the time in milliseconds. Specify -1 for no delay at all or 0 for the smallest possible delay (however, if the Play parameter is present, both 0 and -1 produce no delay).
32 |Note: PressDuration also produces a delay after any change to the modifier key state (Ctrl, Alt, Shift, and Win) needed to support the keys being sent.
33 |Type: String
38 |If blank or omitted, the delay and press duration are applied to the traditional SendEvent mode. Otherwise, specify the word Play to apply both to the SendPlay mode. If a script never uses this parameter, both are always -1 for SendPlay.
39 |If SetKeyDelay is not used, the default delay is 10 for the traditional SendEvent mode and -1 for SendPlay mode. The default press duration is -1 for both modes.
45 |SetKeyDelay is not obeyed by SendInput; there is no delay between keystrokes in that mode. This same is true for Send when SendMode Input is in effect.
46 |A short delay (sleep) is done automatically after every keystroke sent by Send or ControlSend. This is done to improve the reliability of scripts because a window sometimes can't keep up with a rapid flood of keystrokes.
47 |During the delay (sleep), the current thread is made uninterruptible.
48 |Due to the granularity of the OS's time-keeping system, delays might be rounded up to the nearest multiple of 10 or 15.
49 |For Send/SendEvent mode, a delay of 0 internally executes a Sleep(0), which yields the remainder of the script's timeslice to any other process that may need it. If there is none, Sleep(0) will not sleep at all. By contrast, a delay of -1 will never sleep. For better reliability, 0 is recommended as an alternative to -1.
50 |When the delay is set to -1, a script's process-priority becomes an important factor in how fast it can send keystrokes when using the traditional SendEvent mode. To raise a script's priority, use ProcessSetPriority "High"
. Although this typically causes keystrokes to be sent faster than the active window can process them, the system automatically buffers them. Buffered keystrokes continue to arrive in the target window after the Send function completes (even if the window is no longer active). This is usually harmless because any subsequent keystrokes sent to the same window get queued up behind the ones already in the buffer.
The built-in variable A_KeyDelay contains the current setting of Delay for Send/SendEvent mode. A_KeyDuration contains the setting for PressDuration, while A_KeyDelayPlay and A_KeyDurationPlay contain the settings for SendPlay.
52 |Every newly launched thread (such as a hotkey, custom menu item, or timed subroutine) starts off fresh with the default setting for this function. That default may be changed by using this function during script startup.
53 |Send, ControlSend, SendMode, SetMouseDelay, SetControlDelay, SetWinDelay, Click
55 |Causes the smallest possible delay to occur after each keystroke sent via Send or ControlSend.
58 |SetKeyDelay 059 |
Sets the delay that will occur after each mouse movement or click.
16 | 17 |SetMouseDelay Delay , "Play"18 |
Type: Integer
24 |Time in milliseconds. Specify -1 for no delay at all or 0 for the smallest possible delay (however, if the Play parameter is present, both 0 and -1 produce no delay).
25 |Type: String
30 |If blank or omitted, the delay is applied to the traditional SendEvent mode. Otherwise, specify the word Play to apply the delay to the SendPlay mode. If a script never uses this parameter, the delay is always -1 for SendPlay.
31 |Type: Integer
37 |This function returns the previous setting.
38 | 39 |If SetMouseDelay is not used, the default delay is 10 for the traditional SendEvent mode and -1 for SendPlay mode.
41 |A short delay (sleep) is done automatically after every mouse movement or click generated by Click, MouseMove, MouseClick, and MouseClickDrag (except for SendInput mode). This is done to improve the reliability of scripts because a window sometimes can't keep up with a rapid flood of mouse events.
42 |Due to the granularity of the OS's time-keeping system, delays might be rounded up to the nearest multiple of 10 or 15.
43 |A delay of 0 internally executes a Sleep(0), which yields the remainder of the script's timeslice to any other process that may need it. If there is none, Sleep(0) will not sleep at all. By contrast, a delay of -1 will never sleep.
44 |The built-in variable A_MouseDelay contains the current setting for Send/SendEvent mode. A_MouseDelayPlay contains the current setting for SendPlay mode.
45 |Every newly launched thread (such as a hotkey, custom menu item, or timed subroutine) starts off fresh with the default setting for this function. That default may be changed by using this function during script startup.
46 |SetDefaultMouseSpeed, Click, MouseMove, MouseClick, MouseClickDrag, SendMode, SetKeyDelay, SetControlDelay, SetWinDelay
48 |Causes the smallest possible delay to occur after each mouse movement or click.
51 |SetMouseDelay 052 |
Sets the state of CapsLock/NumLock/ScrollLock. Can also force the key to stay on or off.
16 | 17 |SetCapsLockState State 18 | SetNumLockState State 19 | SetScrollLockState State20 |
If blank or omitted, the AlwaysOn/Off attribute of the key is removed (if present). Otherwise, specify one of the following values:
27 |On or 1 (true): Turns on the key and removes the AlwaysOn/Off attribute of the key (if present).
28 |Off or 0 (false): Turns off the key and removes the AlwaysOn/Off attribute of the key (if present).
29 |AlwaysOn: Forces the key to stay on permanently.
30 |AlwaysOff: Forces the key to stay off permanently.
31 |Alternatively to example #3 below, a key can also be toggled to its opposite state via the Send function, e.g. Send "{CapsLock}"
. However, sending {CapsLock} might require SetStoreCapsLockMode False
beforehand.
Keeping a key AlwaysOn or AlwaysOff requires the keyboard hook, which will be automatically installed in such cases.
38 |SetStoreCapsLockMode, GetKeyState
40 |Turns on NumLock and removes the AlwaysOn/Off attribute of the key (if present).
44 |SetNumLockState True45 |
Toggles CapsLock to its opposite state.
54 |SetCapsLockState !GetKeyState("CapsLock", "T")55 |
Sets the registry view used by RegRead, RegWrite, RegDelete, RegDeleteKey and Loop Reg, allowing them in a 32-bit script to access the 64-bit registry view and vice versa.
15 |SetRegView RegView
16 |
17 | Specify 32 to view the registry as a 32-bit application would, or 64 to view the registry as a 64-bit application would.
24 |Specify the word Default to restore normal behaviour.
25 |Type: String
31 |This function returns the previous setting; either 32, 64 or Default.
32 | 33 |If SetRegView is not used, the default setting is Default.
35 |This function is only useful on Windows 64-bit. It has no effect on Windows 32-bit.
36 |On 64-bit systems, 32-bit applications run on a subsystem of Windows called WOW64. By default, the system redirects certain registry keys to prevent conflicts. For example, in a 32-bit script, HKLM\SOFTWARE\AutoHotkey
is redirected to HKLM\SOFTWARE\Wow6432Node\AutoHotkey
. SetRegView allows the registry functions in a 32-bit script to access redirected keys in the 64-bit registry view and vice versa.
The built-in variable A_RegView contains the current setting.
39 |Every newly launched thread (such as a hotkey, custom menu item, or timed subroutine) starts off fresh with the default setting for this function. That default may be changed by using this function during script startup.
40 | 41 |RegRead, RegWrite, RegCreateKey, RegDelete, RegDeleteKey, Loop Reg
43 | 44 |Shows how to set a specific registry view, and how registry redirection affects the script.
47 |48 | ; Access the registry as a 32-bit application would. 49 | SetRegView 32 50 | RegWrite "REG_SZ", "HKLM\SOFTWARE\Test.ahk", "Value", 123 51 | 52 | ; Access the registry as a 64-bit application would. 53 | SetRegView 64 54 | value := RegRead("HKLM\SOFTWARE\Wow6432Node\Test.ahk", "Value") 55 | RegDelete "HKLM\SOFTWARE\Wow6432Node\Test.ahk" 56 | 57 | MsgBox "Read value '" value "' via Wow6432Node." 58 | 59 | ; Restore the registry view to the default, which 60 | ; depends on whether the script is 32-bit or 64-bit. 61 | SetRegView "Default" 62 | ;... 63 |64 |
Shows how to detect the type of EXE and operating system on which the script is running.
68 |if (A_PtrSize = 8) 69 | script_is := "64-bit" 70 | else ; if (A_PtrSize = 4) 71 | script_is := "32-bit" 72 | 73 | if (A_Is64bitOS) 74 | OS_is := "64-bit" 75 | else 76 | OS_is := "32-bit, which has only a single registry view" 77 | 78 | MsgBox "This script is " script_is ", and the OS is " OS_is "."79 |
Whether to restore the state of CapsLock after a Send.
16 | 17 |SetStoreCapsLockMode Mode
18 | Type: Boolean
24 |If true, CapsLock will be restored to its former value if Send needed to change it temporarily for its operation.
25 |If false, the state of CapsLock is not changed at all. As a result, Send will invert the case of the characters if CapsLock happens to be ON during the operation.
26 |Type: Integer (boolean)
32 |This function returns the previous setting; either 0 (false) or 1 (true).
33 | 34 |If SetStoreCapsLockMode is not used, the default setting is 1 (true).
36 |This means that CapsLock will not always be turned off for Send and ControlSend. Even when it is successfully turned off, it might not get turned back on after the keys are sent.
37 |This function is rarely used because the default behavior is best in most cases.
38 |This setting is ignored by blind mode and text mode; that is, the state of CapsLock is not changed in those cases.
39 |The built-in variable A_StoreCapsLockMode contains the current setting (1 or 0).
40 |Every newly launched thread (such as a hotkey, custom menu item, or timed subroutine) starts off fresh with the default setting for this function. That default may be changed by using this function during script startup.
41 |SetCaps/Num/ScrollLockState, Send, ControlSend
43 | 44 |Causes a function to be called automatically and repeatedly at a specified time interval.
16 | 17 |SetTimer Function, Period, Priority18 |
Type: Function Object
24 |The function object to call.
25 |A reference to the function object is kept in the script's list of timers, and is not released unless the timer is deleted. This occurs automatically for run-once timers, but can also be done by calling SetTimer with a Period of 0.
26 |If Function is omitted, SetTimer will operate on the timer which launched the current thread, if any. For example, SetTimer , 0
can be used inside a timer function to mark the timer for deletion, while SetTimer , 1000
would update the current timer's Period.
Note: Passing an empty variable or an expression which results in an empty value is considered an error. This parameter must be either given a non-empty value or completely omitted.
28 |Type: Integer
33 |If omitted and the timer does not exist, it will be created with a period of 250. If omitted and the timer already exists, it will be reset at its former period unless Priority is specified. Otherwise, the absolute value of this parameter is used as the approximate number of milliseconds that must pass before the timer is executed. The timer will be automatically reset. It can be set to repeat automatically or run only once:
34 |SetTimer Function, 0
had been used.The absolute value of Period must be no larger than 4294967295 ms (49.7 days).
40 |Type: Integer
45 |If omitted, it defaults to 0. Otherwise, specify an integer between -2147483648 and 2147483647 (or an expression) to indicate this timer's thread priority. See Threads for details.
46 |To change the priority of an existing timer without affecting it in any other way, omit Period.
47 |Timers are useful because they run asynchronously, meaning that they will run at the specified frequency (interval) even when the script is waiting for a window, displaying a dialog, or busy with another task. Examples of their many uses include taking some action when the user becomes idle (as reflected by A_TimeIdle) or closing unwanted windows the moment they appear.
53 |Although timers may give the illusion that the script is performing more than one task simultaneously, this is not the case. Instead, timed functions are treated just like other threads: they can interrupt or be interrupted by another thread, such as a hotkey subroutine. See Threads for details.
54 |Whenever a timer is created or updated with a new period, its function will not be called right away; its time period must expire first. If you wish the timer's first execution to be immediate, call the timer's function directly (however, this will not start a new thread like the timer itself does; so settings such as SendMode will not start off at their defaults).
55 |Reset: If SetTimer is used on an existing timer, the timer is reset (unless Priority is specified and Period is omitted); in other words, the entirety of its period must elapse before its function will be called again.
56 |Timer precision: Due to the granularity of the OS's time-keeping system, Period is typically rounded up to the nearest multiple of 10 or 15.6 milliseconds (depending on the type of hardware and drivers installed). A shorter delay may be achieved via Loop+Sleep as demonstrated at DllCall+timeBeginPeriod+Sleep.
57 |Reliability: A timer might not be able to run at the expected time under the following conditions:
58 |Although timers will operate when the script is suspended, they will not run if the current thread has Thread NoTimers in effect or whenever any thread is paused. In addition, they do not operate when the user is navigating through one of the script's menus (such as the tray icon menu or a menu bar).
66 |Because timers operate by temporarily interrupting the script's current activity, their functions should be kept short (so that they finish quickly) whenever a long interruption would be undesirable.
67 |Other remarks: A temporary timer might often be disabled by its own function (see examples at the bottom of this page).
68 |Whenever a function is called by a timer, it starts off fresh with the default values for settings such as SendMode. These defaults can be changed during script startup.
69 |If hotkey response time is crucial (such as in games) and the script contains any timers whose functions take longer than about 5 ms to execute, use the following function to avoid any chance of a 15 ms delay. Such a delay would otherwise happen if a hotkey is pressed at the exact moment a timer thread is in its period of uninterruptibility:
70 |Thread "Interrupt", 0 ; Make all threads always-interruptible.71 |
If a timer is disabled while its function is currently running, that function will continue until it completes.
72 |The KeyHistory feature shows how many timers exist and how many are currently enabled.
73 | 74 |Threads, Thread (function), Critical, Function Objects
76 | 77 |Closes unwanted windows whenever they appear.
80 |SetTimer CloseMailWarnings, 250 81 | 82 | CloseMailWarnings() 83 | { 84 | WinClose "Microsoft Outlook", "A timeout occured while communicating" 85 | WinClose "Microsoft Outlook", "A connection to the server could not be established" 86 | }87 |
Waits for a certain window to appear and then alerts the user.
91 |SetTimer Alert1, 500 92 | 93 | Alert1() 94 | { 95 | if not WinExist("Video Conversion", "Process Complete") 96 | return 97 | ; Otherwise: 98 | SetTimer , 0 ; i.e. the timer turns itself off here. 99 | MsgBox "The video conversion is finished." 100 | }101 |
Detects single, double, and triple-presses of a hotkey. This allows a hotkey to perform a different operation depending on how many times you press it.
105 |#c:: 106 | KeyWinC(ThisHotkey) ; This is a named function hotkey. 107 | { 108 | static winc_presses := 0 109 | if winc_presses > 0 ; SetTimer already started, so we log the keypress instead. 110 | { 111 | winc_presses += 1 112 | return 113 | } 114 | ; Otherwise, this is the first press of a new series. Set count to 1 and start 115 | ; the timer: 116 | winc_presses := 1 117 | SetTimer After400, -400 ; Wait for more presses within a 400 millisecond window. 118 | 119 | After400() ; This is a nested function. 120 | { 121 | if winc_presses = 1 ; The key was pressed once. 122 | { 123 | Run "m:\" ; Open a folder. 124 | } 125 | else if winc_presses = 2 ; The key was pressed twice. 126 | { 127 | Run "m:\multimedia" ; Open a different folder. 128 | } 129 | else if winc_presses > 2 130 | { 131 | MsgBox "Three or more clicks detected." 132 | } 133 | ; Regardless of which action above was triggered, reset the count to 134 | ; prepare for the next series of presses: 135 | winc_presses := 0 136 | } 137 | } 138 |139 |
Uses a method as the timer function.
143 |counter := SecondCounter() 144 | counter.Start() 145 | Sleep 5000 146 | counter.Stop() 147 | Sleep 2000 148 | 149 | ; An example class for counting the seconds... 150 | class SecondCounter { 151 | __New() { 152 | this.interval := 1000 153 | this.count := 0 154 | ; Tick() has an implicit parameter "this" which is a reference to 155 | ; the object, so we need to create a function which encapsulates 156 | ; "this" and the method to call: 157 | this.timer := ObjBindMethod(this, "Tick") 158 | } 159 | Start() { 160 | SetTimer this.timer, this.interval 161 | ToolTip "Counter started" 162 | } 163 | Stop() { 164 | ; To turn off the timer, we must pass the same object as before: 165 | SetTimer this.timer, 0 166 | ToolTip "Counter stopped at " this.count 167 | } 168 | ; In this example, the timer calls this method: 169 | Tick() { 170 | ToolTip ++this.count 171 | } 172 | }173 |
Tips relating to the above example:
174 |this.timer := this.Tick.Bind(this)
. When this.timer
is called, it will effectively invoke tick_function.Call(this)
, where tick_function is the function object which implements that method. By contrast, ObjBindMethod produces an object which invokes this.Tick()
.this
directly instead of this.timer
. However, ObjBindMethod is useful when the object has multiple methods which should be called by different event sources, such as hotkeys, menu items, GUI controls, etc.Sets the matching behavior of the WinTitle parameter in built-in functions such as WinWait.
16 | 17 |18 | SetTitleMatchMode MatchMode 19 | SetTitleMatchMode Speed 20 |21 |
Specify one of the following values:
28 |1: A window's title must start with the specified WinTitle to be a match.
29 |2: Default behavior. A window's title can contain WinTitle anywhere inside it to be a match.
30 |3: A window's title must exactly match WinTitle to be a match.
31 |RegEx: Changes WinTitle, WinText, ExcludeTitle, and ExcludeText to accept regular expressions, e.g. WinActivate "Untitled.*Notepad"
. RegEx also applies to ahk_class and ahk_exe, e.g. "ahk_class IEFrame"
searches for any window whose class name contains IEFrame anywhere (this is because by default, regular expressions find a match anywhere in the target string). For WinTitle, each component is separate, e.g. in "i)^untitled ahk_class i)^notepad$ ahk_pid " mypid
, i)^untitled
and i)^notepad$
are separate regex patterns and mypid
is always compared numerically (it is not a regex pattern). For WinText, each text element (i.e. each control's text) is matched against the RegEx separately, so it is not possible to have a match span more than one text element.
The modes above also affect ExcludeTitle in the same way as WinTitle. For example, mode 3 requires that a window's title exactly match ExcludeTitle for that window to be excluded.
33 |Of the modes, only RegEx mode affects the non-title window matching criteria ahk_class and ahk_exe. Those matching criteria will operate identically in any of the numbered modes.
34 |Type: String
39 |Specify one of the following words to indicate how the WinText and ExcludeText parameters should be matched:
40 |Fast: Default behavior. Performance may be substantially better than the slow mode, but certain types of controls are not detected. For instance, text is typically detected within Static and Button controls, but not Edit controls, unless they are owned by the script.
41 |Slow: Can be much slower, but works with all controls which respond to the WM_GETTEXT message.
42 |This function returns the previous value of whichever setting was changed (either A_TitleMatchMode or A_TitleMatchModeSpeed).
49 | 50 |If SetTitleMatchMode is not used, the default match mode is 2 and the default speed is fast.
52 |This function affects the behavior of all windowing functions, e.g. WinExist and WinActivate. WinGetText and ControlGetText are affected in the same way as other functions, but they always use the slow mode to retrieve text.
53 |If a window group is used, the current title match mode applies to each individual rule in the group.
54 |Generally, the slow mode should be used only if the target window cannot be uniquely identified by its title and fast-mode text. This is because the slow mode can be extremely slow if there are any application windows that are busy or "not responding".
55 |Window Spy has an option for Slow TitleMatchMode so that its easy to determine whether the slow mode is needed.
56 |If you wish to change both attributes, run the function twice as in this example:
57 |SetTitleMatchMode 2 58 | SetTitleMatchMode "Slow"59 |
The built-in variables A_TitleMatchMode and A_TitleMatchModeSpeed contain the current settings.
60 |Regardless of the current match mode, WinTitle, WinText, ExcludeTitle and ExcludeText are case-sensitive. The only exception is the case-insensitive option of the RegEx mode, e.g. "i)untitled - notepad"
.
Every newly launched thread (such as a hotkey, custom menu item, or timed subroutine) starts off fresh with the default setting for this function. That default may be changed by using this function during script startup.
62 |The WinTitle Parameter, SetWinDelay, WinExist, WinActivate, RegExMatch
64 |Forces windowing functions to operate upon windows whose titles contain WinTitle at the beginning instead of anywhere.
67 |SetTitleMatchMode 168 |
Allows windowing functions to possibly detect more control types, but with lower performance. Note that Slow/Fast can be set independently of all the other modes.
72 |SetTitleMatchMode "Slow"73 |
Use RegEx mode to easily exclude multiple windows. Replace the following ExcludeTitles with actual window titles that you want to exclude from counting.
77 |SetTitleMatchMode "RegEx" 78 | CountAll := WinGetCount() 79 | CountExcluded := WinGetCount(,, "ExcludeTitle1|ExcludeTitle2") 80 | MsgBox CountExcluded " out of " CountAll " windows were counted"81 |
Sets the delay that will occur after each windowing function, such as WinActivate.
16 | 17 |SetWinDelay Delay
18 | Type: Integer
24 |Time in milliseconds. Specify -1 for no delay at all or 0 for the smallest possible delay.
25 |Type: Integer
31 |This function returns the previous setting.
32 | 33 |If SetWinDelay is not used, the default delay is 100.
35 |A short delay (sleep) is done automatically after every windowing function except WinActive and WinExist. This is done to improve the reliability of scripts because a window sometimes needs a period of "rest" after being created, activated, minimized, etc. so that it has a chance to update itself and respond to the next function that the script may attempt to send to it.
36 |Although a delay of -1 (no delay at all) is allowed, it is recommended that at least 0 be used, to increase confidence that the script will run correctly even when the CPU is under load.
37 |A delay of 0 internally executes a Sleep(0), which yields the remainder of the script's timeslice to any other process that may need it. If there is none, Sleep(0) will not sleep at all.
38 |If the CPU is slow or under load, or if window animation is enabled, higher delay values may be needed.
39 |The built-in variable A_WinDelay contains the current setting.
40 |Every newly launched thread (such as a hotkey, custom menu item, or timed subroutine) starts off fresh with the default setting for this function. That default may be changed by using this function during script startup.
41 |SetControlDelay, SetKeyDelay, SetMouseDelay, SendMode
43 |Changes the script's current working directory.
16 | 17 |SetWorkingDir DirName
18 | Type: String
24 |The name of the new working directory, which is assumed to be a subfolder of the current A_WorkingDir if an absolute path isn't specified.
25 |An OSError is thrown on failure.
31 | 32 |The script's working directory is the default directory that is used to access files and folders when an absolute path has not been specified. In the following example, the file My Filename.txt is assumed to be in A_WorkingDir: FileAppend "A Line of Text", "My Filename.txt"
.
The script's working directory defaults to A_ScriptDir, regardless of how the script was launched. By contrast, the value of A_InitialWorkingDir is determined by how the script was launched. For example, if it was run via shortcut -- such as on the Start Menu -- its initial working directory is determined by the "Start in" field within the shortcut's properties.
35 |Once changed, the new working directory is instantly and globally in effect throughout the script. All interrupted, paused, and newly launched threads are affected, including Timers.
36 |A_WorkingDir, A_InitialWorkingDir, A_ScriptDir, DirSelect
38 |Forces the script to use the folder it was initially launched from as its working directory.
46 |SetWorkingDir A_InitialWorkingDir47 |
Shuts down, restarts, or logs off the system.
16 | 17 |Shutdown Flag
18 | Type: Integer
24 |A combination (sum) of the following numbers:
25 |Add the required values together. For example, to shutdown and power down the flag would be 9 (shutdown + power down = 1 + 8 = 9).
33 |The "Force" value (4) forces all open applications to close. It should only be used in an emergency because it may cause any open applications to lose data.
34 |The "Power down" value (8) shuts down the system and turns off the power.
35 |To have the system suspend or hibernate, see example #2 at the bottom of this page.
41 |To turn off the monitor, see SendMessage example #1.
42 |On a related note, a script can detect when the system is shutting down or the user is logging off via OnExit.
43 |Calls the Windows API function "SetSuspendState" to have the system suspend or hibernate. Note that the second parameter may have no effect at all on newer systems.
53 |; Parameter #1: Pass 1 instead of 0 to hibernate rather than suspend. 54 | ; Parameter #2: Pass 1 instead of 0 to suspend immediately rather than asking each application for permission. 55 | ; Parameter #3: Pass 1 instead of 0 to disable all wake events. 56 | DllCall("PowrProf\SetSuspendState", "Int", 0, "Int", 0, "Int", 0)57 |
Waits the specified amount of time before continuing.
16 | 17 |Sleep Delay
18 | Type: Integer
24 |The amount of time to pause (in milliseconds) between 0 and 2147483647 (24 days).
25 |Due to the granularity of the OS's time-keeping system, Delay is typically rounded up to the nearest multiple of 10 or 15.6 milliseconds (depending on the type of hardware and drivers installed). To achieve a shorter delay, see Examples.
31 |The actual delay time might wind up being longer than what was requested if the CPU is under load. This is because the OS gives each needy process a slice of CPU time (typically 20 milliseconds) before giving another timeslice to the script.
32 |A delay of 0 yields the remainder of the script's current timeslice to any other processes that need it (as long as they are not significantly lower in priority than the script). Thus, a delay of 0 produces an actual delay between 0 and 20 ms (or more), depending on the number of needy processes (if there are no needy processes, there will be no delay at all). However, a Delay of 0 should always wind up being shorter than any longer Delay would have been.
33 |While sleeping, new threads can be launched via hotkey, custom menu item, or timer.
34 |Sleep -1: A delay of -1 does not sleep but instead makes the script immediately check its message queue. This can be used to force any pending interruptions to occur at a specific place rather than somewhere more random. See Critical for more details.
35 |SetKeyDelay, SetMouseDelay, SetControlDelay, SetWinDelay
37 |Waits 30 minutes before continuing execution.
45 |MyVar := 30 * 60000 ; 30 means minutes and times 60000 gives the time in milliseconds. 46 | Sleep MyVar ; Sleep for 30 minutes.47 |
Demonstrates how to sleep for less time than the normal 10 or 15.6 milliseconds. Note: While a script like this is running, the entire operating system and all applications are affected by timeBeginPeriod below.
51 |52 | SleepDuration := 1 ; This can sometimes be finely adjusted (e.g. 2 is different than 3) depending on the value below. 53 | TimePeriod := 3 ; Try 7 or 3. See comment below. 54 | ; On a PC whose sleep duration normally rounds up to 15.6 ms, try TimePeriod=7 to allow 55 | ; somewhat shorter sleeps, and try TimePeriod=3 or less to allow the shortest possible sleeps. 56 | 57 | DllCall("Winmm\timeBeginPeriod", "UInt", TimePeriod) ; Affects all applications, not just this script's DllCall("Sleep"...), but does not affect SetTimer. 58 | Iterations := 50 59 | StartTime := A_TickCount 60 | 61 | Loop Iterations 62 | DllCall("Sleep", "UInt", SleepDuration) ; Must use DllCall instead of the Sleep function. 63 | 64 | DllCall("Winmm\timeEndPeriod", "UInt", TimePeriod) ; Should be called to restore system to normal. 65 | MsgBox "Sleep duration = " . (A_TickCount - StartTime) / Iterations66 |
Arranges a variable's contents in alphabetical, numerical, or random order (optionally removing duplicates).
16 | 17 |SortedString := Sort(String , Options, Callback)18 |
Type: String
24 |The string to sort.
25 |Type: String
30 |If blank or omitted, String will be sorted in ascending alphabetical order (case-insensitive), using a linefeed (`n) as separator. Otherwise, specify a string of one or more options from the Options section below (in any order, with optional spaces in between).
31 |Type: Function Object
36 |If omitted, no custom sorting will be performed. Otherwise, specify the function to call that compares any two items in the list.
37 |The callback accepts three parameters and can be defined as follows:
38 |MyCallback(First, Second, Offset) { ...39 |
Although the names you give the parameters do not matter, the following values are sequentially assigned to them:
40 |You can omit one or more parameters from the end of the callback's parameter list if the corresponding information is not needed, but in this case an asterisk must be specified as the final parameter, e.g. MyCallback(Param1, *)
.
When the callback deems the first parameter to be greater than the second, it should return a positive integer; when it deems the two parameters to be equal, it should return 0, "", or nothing; otherwise, it should return a negative integer. If a decimal point is present in the returned value, that part is ignored (i.e. 0.8 is the same as 0).
47 |The callback uses the same global (or thread-specific) settings as the Sort function that called it.
48 |Note: All options except D, Z, and U are ignored when Callback is specified (though N, C, and CL still affect how duplicates are detected).
49 |Type: String
55 |This function returns the sorted version of the specified string.
56 | 57 |C, C1 or COn: Case-sensitive sort (ignored if the N option is also present).
59 |C0 or COff: Case-insensitive sort. The uppercase letters A-Z are considered identical to their lowercase counterparts for the purpose of the sort. This is the default mode if none of the other case sensitivity options are used.
60 |CL or CLocale: Case-insensitive sort based on the current user's locale. For example, most English and Western European locales treat the letters A-Z and ANSI letters like Ä and Ü as identical to their lowercase counterparts. This method also uses a "word sort", which treats hyphens and apostrophes in such a way that words like "coop" and "co-op" stay together. Depending on the content of the items being sorted, the performance will be 1 to 8 times worse than the default method of insensitivity.
61 |CLogical: Like CLocale, but digits in the strings are considered as numerical content rather than text. For example, "A2" is considered less than "A10". However, if two numbers differ only by the presence of a leading zero, the string with leading zero may be considered less than the other string. The exact behavior may differ between OS versions.
62 |Dx: Specifies x as the delimiter character, which determines where each item begins and ends. The delimiter is always case-sensitive. If this option is not present, x defaults to linefeed (`n). In most cases this will work even if lines end with CR+LF (`r`n), but the carriage return (`r) is included in comparisons and therefore affects the sort order. For example, "B`r`nA"
will sort as expected, but "A`r`nA`t`r`nB"
will place A`t`r
before A`r
.
N: Numeric sort. Each item is assumed to be a number rather than a string (for example, if this option is not present, the string 233 is considered to be less than the string 40 due to alphabetical ordering). Both decimal and hexadecimal strings (e.g. 0xF1) are considered to be numeric. Strings that do not start with a number are considered to be zero for the purpose of the sort. Numbers are treated as 64-bit floating point values so that the decimal portion of each number (if any) is taken into account.
64 |Pn: Sorts items based on character position n (do not use hexadecimal for n). If this option is not present, n defaults to 1, which is the position of the first character. The sort compares each string to the others starting at its nth character. If n is greater than the length of any string, that string is considered to be blank for the purpose of the sort. When used with option N (numeric sort), the string's character position is used, which is not necessarily the same as the number's digit position.
65 |R: Sorts in reverse order (alphabetically or numerically depending on the other options).
66 |Random: Sorts in random order. This option causes all other options except D, Z, and U to be ignored (though N, C, and CL still affect how duplicates are detected). Examples:
67 |MyVar := Sort(MyVar, "Random") 68 | MyVar := Sort(MyVar, "Random Z D|")69 |
U: Removes duplicate items from the list so that every item is unique. If the C option is in effect, the case of items must match for them to be considered identical. If the N option is in effect, an item such as 2 would be considered a duplicate of 2.0. If either the P or \ (backslash) option is in effect, the entire item must be a duplicate, not just the substring that is used for sorting. If the Random option or custom sorting is in effect, duplicates are removed only if they appear adjacent to each other as a result of the sort. For example, when "A|B|A"
is sorted randomly, the result could contain either one or two A's.
Z: To understand this option, consider a variable that contains "RED`nGREEN`nBLUE`n"
. If the Z option is not present, the last linefeed (`n) is considered to be part of the last item, and thus there are only 3 items. But by specifying Z, the last `n (if present) will be considered to delimit a blank item at the end of the list, and thus there are 4 items (the last being blank).
\: Sorts items based on the substring that follows the last backslash in each. If an item has no backslash, the entire item is used as the substring. This option is useful for sorting bare filenames (i.e. excluding their paths), such as the example below, in which the AAA.txt line is sorted above the BBB.txt line because their directories are ignored for the purpose of the sort:
72 |C:\BBB\AAA.txt 73 | C:\AAA\BBB.txt74 |
Note: Options N and P are ignored when the \ (backslash) option is present.
75 | 76 |This function is typically used to sort a variable that contains a list of lines, with each line ending in a linefeed character (`n). One way to get a list of lines into a variable is to load an entire file via FileRead.
78 |If a large variable was sorted and later its contents are no longer needed, you can free its memory by making it blank, e.g. MyVar := ""
.
FileRead, File-reading loop, Parsing loop, StrSplit, CallbackCreate, A_Clipboard
82 | 83 |Sorts a comma-separated list of numbers.
86 |MyVar := "5,3,7,9,1,13,999,-4" 87 | MyVar := Sort(MyVar, "N D,") ; Sort numerically, use comma as delimiter. 88 | MsgBox MyVar ; The result is -4,1,3,5,7,9,13,99989 |
Contents := FileRead("C:\Address List.txt") 94 | FileDelete "C:\Address List (alphabetical).txt" 95 | FileAppend Sort(Contents), "C:\Address List (alphabetical).txt" 96 | Contents := "" ; Free the memory.97 |
Makes a hotkey to copy files from an open Explorer window and put their sorted filenames onto the clipboard.
101 |#c:: ; Win+C 102 | { 103 | A_Clipboard := "" ; Must be blank for detection to work. 104 | Send "^c" 105 | if !ClipWait(2) 106 | return 107 | MsgBox "Ready to be pasted:`n" Sort(A_Clipboard) 108 | }109 |
Demonstrates custom sorting via a callback function.
113 |MyVar := "This`nis`nan`nexample`nstring`nto`nbe`nsorted" 114 | MsgBox Sort(MyVar,, LengthSort) 115 | LengthSort(a1, a2, *) 116 | { 117 | a1 := StrLen(a1), a2 := StrLen(a2) 118 | return a1 > a2 ? 1 : a1 < a2 ? -1 : 0 ; Sorts according to the lengths determined above. 119 | } 120 | 121 | MyVar := "5,3,7,9,1,13,999,-4" 122 | MsgBox Sort(MyVar, "D,", IntegerSort) 123 | IntegerSort(a1, a2, *) 124 | { 125 | return a1 - a2 ; Sorts in ascending numeric order. This method works only if the difference is never so large as to overflow a signed 64-bit integer. 126 | } 127 | 128 | MyVar := "1,2,3,4" 129 | MsgBox Sort(MyVar, "D,", ReverseDirection) ; Reverses the list so that it contains 4,3,2,1 130 | ReverseDirection(a1, a2, offset) 131 | { 132 | return offset ; Offset is positive if a2 came after a1 in the original list; negative otherwise. 133 | } 134 | 135 | MyVar := "a bbb cc" 136 | ; Sorts in ascending length order; uses a fat arrow function: 137 | MsgBox Sort(MyVar, "D ", (a,b,*) => StrLen(a) - StrLen(b)) 138 |139 |
Applies to:
17 |Other sound-related functions:
24 | 28 | 29 |The "devices" referenced by the SoundGet and SoundSet functions are audio endpoint devices. A single device driver or physical device often has multiple endpoints, such as for different types of output or input. For example:
31 |Name | Description |
---|---|
Speakers (Example HD Audio) | The main analog outputs of this device (uses multiple jacks in the case of surround sound). |
Digital Output (Example HD Audio) | An optical or coaxial digital output. |
Microphone (Example HD Audio) | Captures audio through a microphone jack. |
Stereo Mix (Example HD Audio) | Captures whatever audio is being output to the Speakers endpoint. |
Device names typically consist of an endpoint name such as "Speakers" followed by the name of the audio driver in parentheses. Scripts may use the full name or just the leading part of the name, such as "Mic" or "Microphone". An audio driver has a fixed name, but endpoint names may be changed by an administrator at any time via the Sound control panel.
39 |Devices are listed in the Sound control panel, which can be opened by running mmsys.cpl
from the command line, or via the Run dialog (Win+R) or the Run function. By default, the control panel only lists devices that are enabled and plugged in (if applicable), but this can be changed via the right-click menu. AutoHotkey detects devices which are not plugged in, but does not detect disabled devices.
Components are as shown on the Levels tab of the sound device's properties dialog.
43 | 44 |In this example, the master controls are at the top, followed by the first four components: Microphone, FrontMic, Line In, and Side. All have volume and mute controls, except the fourth component, which only has volume.
45 |A sound device's properties dialog can be opened via the Sound control panel.
46 |Audio drivers are capable of exposing other controls, such as bass and treble. However, common audio drivers tend to have only volume and mute controls, or no components at all. Volume and mute controls are supported directly through SoundGetVolume, SoundSetVolume, SoundGetMute and SoundSetMute. All other controls are supported only indirectly, through SoundGetInterface and ComCall.
47 | 48 |Components are discovered through the DeviceTopology API, which exposes a graph of Connectors and Subunits. Each component shown above has a Connector, and it is the Connector that defines the component's name. Each control (such as volume or mute) is represented by a Subunit which sits between the Connector and the endpoint. Data "flows" from or to the Connector and is altered as it flows through each Subunit, such as to adjust volume or suppress (mute) all sound.
50 |The SoundGet and SoundSet functions identify components by walking the device topology graph and counting Connectors with the given name (or all Connectors if no name is given). Once the matching Connector is found, a control interface (such as IAudioVolumeLevel or IAudioMute) is retrieved by querying each Subunit on that specific branch of the graph, starting nearest the Connector.
51 |Subunits which apply to multiple Connectors are excluded - such as Subunits which correspond to the master volume and mute controls. A Connector is counted if (and only if) it has at least one Subunit of its own, even if the Subunit is not of the requested type.
52 |In practice, the end result is that the available components are as listed on the Levels tab, and in the same order. However, this process is based on observation, trial and error, so might not be 100 % accurate.
53 | 54 |One of the following:
61 |"Line In:2"
uses the second component named "Line In". This is necessary only when Component would otherwise be ambiguous, such as when multiple components exist with the same name, or the display name is empty, an integer or contains a colon.If only an index is specified, the display names are ignored. For example, 1
, "1"
and ":1"
use the first component regardless of name, whereas ""
uses the master controls.
If the sound device lacks the specified Component, a TargetError is thrown.
69 |One of the following:
75 |"Speakers"
or "Speakers (Example HD Audio)"
."Speakers:2"
indicates the second device which has a name starting with "Speakers". This is necessary only when Device would otherwise be ambiguous, such as when multiple devices exist with the same name, or the display name contains a colon.The soundcard analysis script may help determine which name and/or number to use.
82 |Soundcard Analysis. Use the following script to discover the available audio device and component names and whether each device or component supports volume and/or mute controls. It displays the results in a simple ListView. The current volume and mute settings are shown if they can be retrieved, but are not updated in realtime.
89 |90 | scGui := Gui(, "Sound Components") 91 | scLV := scGui.Add('ListView', "w600 h400" 92 | , ["Component", "#", "Device", "Volume", "Mute"]) 93 | 94 | devMap := Map() 95 | 96 | loop 97 | { 98 | ; For each loop iteration, try to get the corresponding device. 99 | try 100 | devName := SoundGetName(, dev := A_Index) 101 | catch ; No more devices. 102 | break 103 | 104 | ; Qualify names with ":index" where needed. 105 | devName := Qualify(devName, devMap, dev) 106 | 107 | ; Retrieve master volume and mute setting, if possible. 108 | vol := mute := "" 109 | try vol := Round(SoundGetVolume( , dev), 2) 110 | try mute := SoundGetMute( , dev) 111 | 112 | ; Display the master settings only if at least one was retrieved. 113 | if vol != "" || mute != "" 114 | scLV.Add("", "", dev, devName, vol, mute) 115 | 116 | ; For each component, first query its name. 117 | cmpMap := Map() 118 | 119 | loop 120 | { 121 | try 122 | cmpName := SoundGetName(cmp := A_Index, dev) 123 | catch 124 | break 125 | ; Retrieve this component's volume and mute setting, if possible. 126 | vol := mute := "" 127 | try vol := Round(SoundGetVolume(cmp, dev), 2) 128 | try mute := SoundGetMute(cmp, dev) 129 | ; Display this component even if it does not support volume or mute, 130 | ; since it likely supports other controls via SoundGetInterface(). 131 | scLV.Add("", Qualify(cmpName, cmpMap, A_Index), dev, devName, vol, mute) 132 | } 133 | } 134 | 135 | loop 5 136 | scLV.ModifyCol(A_Index, 'AutoHdr Logical') 137 | scGui.Show() 138 | 139 | ; Qualifies full names with ":index" when needed. 140 | Qualify(name, names, overallIndex) 141 | { 142 | if name = '' 143 | return overallIndex 144 | key := StrLower(name) 145 | index := names.Has(key) ? ++names[key] : (names[key] := 1) 146 | return (index > 1 || InStr(name, ':') || IsInteger(name)) ? name ':' index : name 147 | }148 |
Emits a tone from the PC speaker.
16 | 17 |SoundBeep Frequency, Duration18 |
Type: Integer
24 |If omitted, it defaults to 523. Otherwise, specify the frequency of the sound, a number between 37 and 32767.
25 |Type: Integer
30 |If omitted, it defaults to 150. Otherwise, specify the duration of the sound, in milliseconds.
31 |The script waits for the sound to finish before continuing. In addition, system responsiveness might be reduced during sound production.
37 |If the computer lacks a sound card, a standard beep is played through the PC speaker.
38 |To produce the standard system sounds instead of beeping the PC Speaker, see the asterisk mode of SoundPlay.
39 |Retrieves a native COM interface of a sound device or component.
17 | 18 |InterfacePtr := SoundGetInterface(IID, Component, Device)19 |
Type: String
25 |An interface identifier (GUID) in the form "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}".
26 |If blank or omitted, an interface implemented by the device itself will be retrieved. Otherwise, specify the component's display name and/or index, e.g. 1
, "Line in"
or "Line in:2"
.
For further details, see Component (Sound Functions).
33 |If blank or omitted, it defaults to the system's default device for playback (which is not necessarily device 1). Otherwise, specify the device's display name and/or index, e.g. 1
, "Speakers"
, "Speakers:2"
or "Speakers (Example HD Audio)"
.
For further details, see Device (Sound Functions).
40 |Type: Integer
46 |On success, the return value is an interface pointer.
47 |If the interface is not supported, the return value is zero.
48 | 49 |A TargetError is thrown if the device or component could not be found. Otherwise, an OSError is thrown on failure.
51 | 52 |The interface is retrieved from one of the following sources:
54 |"{7FB7B48F-531D-44A2-BCB3-5AD5A134B3DC}"
to retrieve the IAudioVolumeLevel interface, which provides access to per-channel volume level controls.Once the interface pointer is retrieved, ComCall can be used to call its methods. Refer to the Windows SDK header files to identify the correct method index.
60 |The interface pointer must be released by passing it to ObjRelease when it is no longer needed. This can be done by "wrapping" it with ComValue. The wrapped value (an object) can be passed directly to ComCall.
61 |Interface := ComValue(13, InterfacePtr)62 | 63 |
Sound Functions, DeviceTopology API
65 | 66 |Peak meter. A tooltip is displayed with the current peak value, except when the peak value is zero (no sounds are playing).
69 |; IAudioMeterInformation 70 | audioMeter := SoundGetInterface("{C02216F6-8C67-4B5B-9D00-D008E73E0064}") 71 | if audioMeter 72 | { 73 | try loop ; Until the script exits or an error occurs. 74 | { 75 | ; audioMeter->GetPeakValue(&peak) 76 | ComCall 3, audioMeter, "float*", &peak:=0 77 | ToolTip peak > 0 ? peak : "" 78 | Sleep 15 79 | } 80 | ObjRelease audioMeter 81 | } 82 | else 83 | MsgBox "Unable to get audio meter" 84 |85 |
Retrieves a mute setting of a sound device.
17 | 18 |Setting := SoundGetMute(Component, Device)19 |
If blank or omitted, it defaults to the master mute setting. Otherwise, specify the component's display name and/or index, e.g. 1
, "Line in"
or "Line in:2"
.
For further details, see Component (Sound Functions).
27 |If blank or omitted, it defaults to the system's default device for playback (which is not necessarily device 1). Otherwise, specify the device's display name and/or index, e.g. 1
, "Speakers"
, "Speakers:2"
or "Speakers (Example HD Audio)"
.
For further details, see Device (Sound Functions).
34 |Type: Integer (boolean)
40 |This function returns 0 (false) for unmuted or 1 (true) for muted.
41 | 42 |A TargetError is thrown if the device or component could not be found or if the component does not support this control type. Otherwise, an OSError is thrown on failure.
44 | 45 |To discover the capabilities of the sound devices installed on the system -- such as the names and available components -- run the soundcard analysis script.
47 | 48 |Checks whether the default playback device is muted.
54 |master_mute := SoundGetMute() 55 | if master_mute 56 | MsgBox "The default playback device is muted." 57 | else 58 | MsgBox "The default playback device is not muted."59 |
Checks whether "Line In pass-through" is muted.
63 |if SoundGetMute("Line In") = 0 64 | MsgBox "Line In pass-through is not muted."65 |
Checks whether the microphone (recording) is muted.
69 |if SoundGetMute( , "Microphone") = 0 70 | MsgBox "The microphone (recording) is not muted."71 |
Retrieves the name of a sound device or component.
17 | 18 |Name := SoundGetName(Component, Device)19 |
If blank or omitted, the name of the device itself will be retrieved. Otherwise, specify the component's display name and/or index, e.g. 1
, "Line in"
or "Line in:2"
.
For further details, see Component (Sound Functions).
27 |If blank or omitted, it defaults to the system's default device for playback (which is not necessarily device 1). Otherwise, specify the device's display name and/or index, e.g. 1
, "Speakers"
, "Speakers:2"
or "Speakers (Example HD Audio)"
.
For further details, see Device (Sound Functions).
34 |Type: String
40 |This function returns the name of the device or component, which can be empty.
41 | 42 |A TargetError is thrown if the device or component could not be found. Otherwise, an OSError is thrown on failure.
44 | 45 |Retrieves and reports the name of the default playback device.
51 |default_device := SoundGetName() 52 | MsgBox "The default playback device is " default_device53 |
Retrieves and reports the name of the first device.
57 |device1 := SoundGetName( , 1) 58 | MsgBox "Device 1 is " device159 |
Retrieves and reports the name of the first component.
63 |component1 := SoundGetName(1) 64 | MsgBox "Component 1 is " component165 |
For a more complex example, see the soundcard analysis script.
68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /docs/lib/SoundGetVolume.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Retrieves a volume setting of a sound device.
17 | 18 |Setting := SoundGetVolume(Component, Device)19 |
If blank or omitted, it defaults to the master volume setting. Otherwise, specify the component's display name and/or index, e.g. 1
, "Line in"
or "Line in:2"
.
For further details, see Component (Sound Functions).
27 |If blank or omitted, it defaults to the system's default device for playback (which is not necessarily device 1). Otherwise, specify the device's display name and/or index, e.g. 1
, "Speakers"
, "Speakers:2"
or "Speakers (Example HD Audio)"
.
For further details, see Device (Sound Functions).
34 |Type: Float
40 |This function returns a floating point number between 0.0 and 100.0.
41 | 42 |A TargetError is thrown if the device or component could not be found or if the component does not support this control type. Otherwise, an OSError is thrown on failure.
44 | 45 |To discover the capabilities of the sound devices installed on the system -- such as the names and available components -- run the soundcard analysis script.
47 | 48 |Retrieves and reports the master volume.
54 |master_volume := SoundGetVolume() 55 | MsgBox "Master volume is " master_volume " percent."56 |
Retrieves and reports the microphone listening volume.
60 |mic_volume := SoundGetVolume("Microphone") 61 | MsgBox "Microphone listening volume is " mic_volume " percent."62 |
Retrieves and reports the microphone recording volume.
66 |mic_volume := SoundGetVolume( , "Microphone") 67 | MsgBox "Microphone recording volume is " mic_volume " percent."68 |
Plays a sound, video, or other supported file type.
16 | 17 |SoundPlay Filename , Wait18 |
Type: String
24 |The name of the file to be played, which is assumed to be in A_WorkingDir if an absolute path isn't specified.
25 |To produce standard system sounds, specify an asterisk followed by a number as shown below (note that the Wait parameter has no effect in this mode):
26 |Type: Integer (boolean) or String
38 |If blank or omitted, it defaults to 0 (false). Otherwise, specify one of the following values:
39 |0 (false): The current thread will move on to the next statement(s) while the file is playing.
40 |1 (true) or Wait: The current thread waits until the file is finished playing before continuing. Even while waiting, new threads can be launched via hotkey, custom menu item, or timer.
41 |Known limitation: If the Wait parameter is not used, the system might consider the playing file to be "in use" until the script closes or until another file is played (even a nonexistent file).
42 |An exception is thrown on failure.
48 | 49 |All Windows systems should be able to play .wav files. However, other file types (.mp3, .avi, etc.) might not be playable if the right codecs or features aren't installed on the system.
51 |Due to a quirk in Windows, .wav files with a path longer than 127 characters will not be played. To work around this, use other file types such as .mp3 (with a path length of up to 255 characters) or use 8.3 short paths (see A_LoopFileShortPath how to retrieve such paths).
52 |If a file is playing and the current script plays a second file, the first file will be stopped so that the second one can play. On some systems, certain file types might stop playing even when an entirely separate script plays a new file.
53 |To stop a file that is currently playing, use SoundPlay on a nonexistent filename as in this example: try SoundPlay "Nonexistent.avi"
.
If the script is exited, any currently-playing file that it started will stop.
55 |SoundBeep, Sound Functions, MsgBox, Threads
57 |Plays a .wav file located in the Windows directory.
60 |SoundPlay A_WinDir "\Media\ding.wav"61 |
Changes a mute setting of a sound device.
17 | 18 |SoundSetMute NewSetting , Component, Device19 |
Type: Integer
25 |One of the following values:
26 |1
or True
turns on the setting0
or False
turns off the setting-1
toggles the setting (sets it to the opposite of its current state)If blank or omitted, it defaults to the master mute setting. Otherwise, specify the component's display name and/or index, e.g. 1
, "Line in"
or "Line in:2"
.
For further details, see Component (Sound Functions).
38 |If blank or omitted, it defaults to the system's default device for playback (which is not necessarily device 1). Otherwise, specify the device's display name and/or index, e.g. 1
, "Speakers"
, "Speakers:2"
or "Speakers (Example HD Audio)"
.
For further details, see Device (Sound Functions).
45 |A TargetError is thrown if the device or component could not be found or if the component does not support this control type. Otherwise, an OSError is thrown on failure.
51 | 52 |An alternative way to toggle the master mute setting of the default playback device is to have the script send a keystroke, such as in the example below:
54 |Send "{Volume_Mute}" ; Mute/unmute the master volume.55 |
To discover the capabilities of the sound devices installed on the system -- such as the names and available components -- run the soundcard analysis script.
56 |Use SoundGetMute to retrieve the current mute setting.
57 | 58 |Toggles the master mute (sets it to the opposite of its current state).
74 |SoundSetMute -175 |
Changes a volume setting of a sound device.
17 | 18 |SoundSetVolume NewSetting , Component, Device19 |
Type: String, Integer or Float
25 |A string containing a percentage number between -100 and 100 inclusive. If the number begins with a plus or minus sign, the current setting will be adjusted up or down by the indicated amount. Otherwise, the setting will be set explicitly to the level indicated by NewSetting.
26 |If the percentage number begins with a minus sign or is unsigned, it does not need to be enclosed in quotation marks.
27 |If blank or omitted, it defaults to the master volume setting. Otherwise, specify the component's display name and/or index, e.g. 1
, "Line in"
or "Line in:2"
.
For further details, see Component (Sound Functions).
34 |If blank or omitted, it defaults to the system's default device for playback (which is not necessarily device 1). Otherwise, specify the device's display name and/or index, e.g. 1
, "Speakers"
, "Speakers:2"
or "Speakers (Example HD Audio)"
.
For further details, see Device (Sound Functions).
41 |A TargetError is thrown if the device or component could not be found or if the component does not support this control type. Otherwise, an OSError is thrown on failure.
47 | 48 |An alternative way to adjust the volume is to have the script send volume-control keystrokes to change the master volume for the entire system, such as in the example below:
50 |Send "{Volume_Up}" ; Raise the master volume by 1 interval (typically 5%). 51 | Send "{Volume_Down 3}" ; Lower the master volume by 3 intervals. 52 |53 |
To discover the capabilities of the sound devices installed on the system -- such as the names and available components -- run the soundcard analysis script.
54 |SoundSetVolume attempts to preserve the existing balance when changing the volume level.
55 |Use SoundGetVolume to retrieve the current volume setting.
56 | 57 |Sets the master volume to 50 percent. Quotation marks can be omitted.
63 |SoundSetVolume "50"64 |
SoundSetVolume 5065 |
Increases the master volume by 10 percent. Quotation marks cannot be omitted.
69 |SoundSetVolume "+10"70 |
Decreases the master volume by 10 percent. Quotation marks can be omitted.
74 |SoundSetVolume "-10"75 |
SoundSetVolume -1076 |
Increases microphone recording volume by 20 percent.
80 |SoundSetVolume "+20", , "Microphone"81 |
Separates a file name or URL into its name, directory, extension, and drive.
16 | 17 |SplitPath Path , &OutFileName, &OutDir, &OutExtension, &OutNameNoExt, &OutDrive18 |
Type: String
24 |The file name or URL to be analyzed.
25 |Note that this function expects filename paths to contain backslashes (\) only and URLs to contain forward slashes (/) only.
26 |Type: VarRef
31 |If omitted, the corresponding value will not be stored. Otherwise, specify a reference to the output variable in which to store the file name without its path. The file's extension is included.
32 |Type: VarRef
37 |If omitted, the corresponding value will not be stored. Otherwise, specify a reference to the output variable in which to store the directory of the file, including drive letter or share name (if present). The final backslash is not included even if the file is located in a drive's root directory.
38 |Type: VarRef
43 |If omitted, the corresponding value will not be stored. Otherwise, specify a reference to the output variable in which to store the file's extension (e.g. TXT, DOC, or EXE). The dot is not included.
44 |Type: VarRef
49 |If omitted, the corresponding value will not be stored. Otherwise, specify a reference to the output variable in which to store the file name without its path, dot and extension.
50 |Type: VarRef
55 |If omitted, the corresponding value will not be stored. Otherwise, specify a reference to the output variable in which to store the drive letter or server name of the file. If the file is on a local or mapped drive, the variable will be set to the drive letter followed by a colon (no backslash). If the file is on a network path (UNC), the variable will be set to the share name, e.g. \\Workstation01
56 |Any of the output variables may be omitted if the corresponding information is not needed.
62 |If Path contains a filename that lacks a drive letter (that is, it has no path or merely a relative path), OutDrive will be made blank but all the other output variables will be set correctly. Similarly, if there is no path present, OutDir will be made blank; and if there is a path but no file name present, OutFileName and OutNameNoExt will be made blank.
63 |Actual files and directories in the file system are not checked by this function. It simply analyzes the provided string.
64 |Wildcards (* and ?) and other characters illegal in filenames are treated the same as legal characters, with the exception of colon, backslash, and period (dot), which are processed according to their nature in delimiting the drive letter, directory, and extension of the file.
65 |Support for URLs: If Path contains a colon-double-slash, such as in "https://domain.com"
or "ftp://domain.com"
, OutDir is set to the protocol prefix + domain name + directory (e.g. https://domain.com/images) and OutDrive is set to the protocol prefix + domain name (e.g. https://domain.com). All other variables are set according to their definitions above.
A_LoopFileExt, StrSplit, InStr, SubStr, FileSelect, DirSelect
68 |Demonstrates different usages.
71 |FullFileName := "C:\My Documents\Address List.txt" 72 | 73 | ; To fetch only the bare filename from the above: 74 | SplitPath FullFileName, &name 75 | 76 | ; To fetch only its directory: 77 | SplitPath FullFileName,, &dir 78 | 79 | ; To fetch all info: 80 | SplitPath FullFileName, &name, &dir, &ext, &name_no_ext, &drive 81 | 82 | ; The above will set the variables as follows: 83 | ; name = Address List.txt 84 | ; dir = C:\My Documents 85 | ; ext = txt 86 | ; name_no_ext = Address List 87 | ; drive = C:88 |
Retrieves the text from a standard status bar control.
16 | 17 |Text := StatusBarGetText(Part#, WinTitle, WinText, ExcludeTitle, ExcludeText)18 |
Type: Integer
24 |If omitted, it defaults to 1, which is usually the part that contains the text of interest. Otherwise, specify the part number of the bar to retrieve.
25 |Type: String, Integer or Object
30 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
33 |Type: String
39 |This function returns the text from a single part of the status bar control.
40 | 41 |A TargetError is thrown if the target window could not be found or does not contain a standard status bar.
43 |An OSError is thrown if there was a problem sending the SB_GETPARTS message or no reply was received within 2000 ms, or if memory could not be allocated within the process which owns the status bar.
44 | 45 |This function attempts to read the first standard status bar on a window (Microsoft common control: msctls_statusbar32). Some programs use their own status bars or special versions of the MS common control, in which case the text cannot be retrieved.
47 |Rather than using StatusBarGetText in a loop, it is usually more efficient to use StatusBarWait, which contains optimizations that avoid the overhead of repeated calls to StatusBarGetText.
48 | 49 |StatusBarWait, WinGetTitle, WinGetText, ControlGetText
51 |Retrieves and analyzes the text from the first part of a status bar.
54 |RetrievedText := StatusBarGetText(1, "Search Results") 55 | if InStr(RetrievedText, "found") 56 | MsgBox "Search results have been found."57 |
Waits until a window's status bar contains the specified string.
16 | 17 |StatusBarWait BarText, Timeout, Part#, WinTitle, WinText, Interval, ExcludeTitle, ExcludeText18 |
Type: String
24 |If blank or omitted, the function waits for the status bar to become blank. Otherwise, specify the text or partial text for which the function will wait to appear. The text is case-sensitive and the matching behavior is determined by SetTitleMatchMode, similar to WinTitle below.
25 |To instead wait for the bar's text to change, either use StatusBarGetText in a loop, or use the RegEx example at the bottom of this page.
26 |If omitted, the function will wait indefinitely. Otherwise, it will wait no longer than this many seconds. To wait for a fraction of a second, specify a floating-point number, for example, 0.25 to wait for a maximum of 250 milliseconds.
32 |Type: Integer
37 |If omitted, it defaults to 1, which is usually the part that contains the text of interest. Otherwise, specify the part number of the bar to retrieve.
38 |Type: String, Integer or Object
43 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
44 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
45 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
46 |Type: Integer
51 |If omitted, it defaults to 50. Otherwise, specify how often the status bar should be checked while the function is waiting (in milliseconds).
52 |Type: Integer (boolean)
58 |This function returns 1 (true) if a match was found or 0 (false) if the function timed out.
59 | 60 |A TargetError is thrown if the target window could not be found or does not contain a standard status bar.
62 |An OSError is thrown if there was a problem sending the SB_GETPARTS message or no reply was received within 2000 ms, or if memory could not be allocated within the process which owns the status bar.
63 | 64 |This function attempts to read the first standard status bar on a window (Microsoft common control: msctls_statusbar32). Some programs use their own status bars or special versions of the MS common control, in which case such bars are not supported.
66 |Rather than using StatusBarGetText in a loop, it is usually more efficient to use StatusBarWait, which contains optimizations that avoid the overhead of repeated calls to StatusBarGetText.
67 |StatusBarWait determines its target window before it begins waiting for a match. If that target window is closed, the function will stop waiting even if there is another window matching the specified WinTitle and WinText.
68 |While the function is in a waiting state, new threads can be launched via hotkey, custom menu item, or timer.
69 | 70 |StatusBarGetText, WinGetTitle, WinGetText, ControlGetText
72 |Enters a new search pattern into an existing Explorer/Search window.
75 |if WinExist("Search Results") ; Sets the Last Found window to simplify the below. 76 | { 77 | WinActivate 78 | Send "{tab 2}!o*.txt{enter}" ; In the Search window, enter the pattern to search for. 79 | Sleep 400 ; Give the status bar time to change to "Searching". 80 | if StatusBarWait("found", 30) 81 | MsgBox "The search successfully completed." 82 | else 83 | MsgBox "The function timed out." 84 | }85 |
Waits for the status bar of the active window to change.
89 |SetTitleMatchMode "RegEx" ; Accept regular expressions for use below. 90 | if WinExist("A") ; Set the last-found window to be the active window (for use below). 91 | { 92 | OrigText := StatusBarGetText() 93 | StatusBarWait "^(?!^\Q" OrigText "\E$)" ; This regular expression waits for any change to the text. 94 | }95 |
Compares two strings alphabetically.
16 |Result := StrCompare(String1, String2 , CaseSense)17 | 18 |
Type: String
23 |The strings to be compared.
24 |Type: String or Integer (boolean)
28 |If omitted, it defaults to Off. Otherwise, specify one of the following values:
29 |On or 1 (true): The comparison is case-sensitive.
30 |Off or 0 (false): The comparison is not case-sensitive, i.e. the letters A-Z are considered identical to their lowercase counterparts.
31 |Locale: The comparison is not case-sensitive according to the rules of the current user's locale. For example, most English and Western European locales treat not only the letters A-Z as identical to their lowercase counterparts, but also non-ASCII letters like Ä and Ü as identical to theirs. Locale is 1 to 8 times slower than Off depending on the nature of the strings being compared.
32 |Logical: Like Locale, but digits in the strings are considered as numerical content rather than text. For example, "A2"
is considered less than "A10"
. However, if two numbers differ only by the presence of a leading zero, the string with leading zero may be considered less than the other string. The exact behavior may differ between OS versions.
Type: Integer
38 |To indicate the relationship between String1 and String2, this function returns one of the following:
39 |To check for a specific relationship between the two strings, compare the result to 0. For example:
45 |a_less_than_b := StrCompare(a, b) < 0 46 | a_greater_than_or_equal_to_b := StrCompare(a, b) >= 047 | 48 |
This function is commonly used for sort callbacks.
50 | 51 |Demonstrates the difference between a case-insensitive and case-sensitive comparison.
57 |MsgBox StrCompare("Abc", "abc") ; Returns 0 58 | MsgBox StrCompare("Abc", "abc", true) ; Returns -159 |
Copies a string from a memory address or buffer, optionally converting it from a given code page.
16 | 17 |String := StrGet(Source , Length, Encoding) 18 | String := StrGet(Source , Encoding)19 |
A Buffer-like object containing the string, or the memory address of the string.
26 |Any object which implements Ptr and Size properties may be used, but this function is optimized for the native Buffer object. Passing an object with these properties ensures that the function does not read memory from an invalid location; doing so could cause crashes or other unpredictable behaviour.
27 |The string is not required to be null-terminated if a Buffer-like object is provided, or if Length is specified.
28 |Type: Integer
33 |If omitted (or when using 2-parameter mode), it defaults to the current length of the string, provided the string is null-terminated. Otherwise, specify the maximum number of characters to read.
34 |By default, StrGet only copies up to the first binary zero. If Length is negative, its absolute value indicates the exact number of characters to convert, including any binary zeros that the string might contain - in other words, the result is always a string of exactly that length.
35 |Note: Omitting Length when the string is not null-terminated may cause an access violation which terminates the program, or some other undesired result. Specifying an incorrect length may produce unexpected behaviour.
36 |If omitted, the string is simply copied without any conversion taking place. Otherwise, specify the source encoding; for example, "UTF-8"
, "UTF-16"
or "CP936"
. For numeric identifiers, the prefix "CP" can be omitted only in 3-parameter mode. Specify an empty string or "CP0"
to use the system default ANSI code page.
Type: String
48 |This function returns the copied or converted string. If the source encoding was specified correctly, the return value always uses the native encoding. The value is always null-terminated, but the null-terminator is not included in its length except when Length is negative, as described above.
49 | 50 |A ValueError is thrown if invalid parameters are detected.
52 |An OSError is thrown if the conversion could not be performed.
53 | 54 |Note that the return value is always in the native encoding of the current executable, whereas Encoding specifies how to interpret the string read from the given Source. If no Encoding is specified, the string is simply copied without any conversion taking place.
56 |In other words, StrGet is used to retrieve text from a memory address or buffer, or convert it to a format the script can understand.
57 |If conversion between code pages is necessary, the length of the return value may differ from the length of the source string.
58 | 59 |String Encoding, StrPut, Binary Compatibility, FileEncoding, DllCall, Buffer object, VarSetStrCapacity
61 | 62 |Either Length or Encoding may be specified directly after Source, but in those cases Encoding must be non-numeric.
65 |66 | str := StrGet(address, "cp0") ; Code page 0, unspecified length 67 | str := StrGet(address, n, 0) ; Maximum n chars, code page 0 68 | str := StrGet(address, 0) ; Maximum 0 chars (always blank) 69 |70 |
Retrieves the count of how many characters are in a string.
15 |Length := StrLen(String)
16 |
17 | Type: String
22 |The string whose contents will be measured.
23 |Type: Integer
28 |This function returns the length of the specified string.
29 | 30 |InStr, SubStr, Trim, StrLower, StrUpper, StrPut, StrGet, StrReplace, StrSplit
32 | 33 |Retrieves and reports the count of how many characters are in a string.
36 |StrValue := "The quick brown fox jumps over the lazy dog" 37 | MsgBox "The length of the string is " StrLen(StrValue) ; Result: 4338 |
Converts a string to lowercase, uppercase or title case.
17 | 18 |NewString := StrLower(String) 19 | NewString := StrUpper(String) 20 | NewString := StrTitle(String)21 |
Type: String
27 |The string to convert.
28 |Type: String
34 |These functions return the newly converted version of the specified string.
35 | 36 |To detect whether a character or string is entirely uppercase or lowercase, use the IsUpper, IsLower or RegExMatch function. For example:
38 |var := "abc" 39 | if isUpper(var) 40 | MsgBox "var is empty or contains only uppercase characters." 41 | if isLower(var) 42 | MsgBox "var is empty or contains only lowercase characters." 43 | if RegExMatch(var, "^[a-z]+$") 44 | MsgBox "var is not empty and contains only lowercase ASCII characters." 45 | if !RegExMatch(var, "[A-Z]") 46 | MsgBox "var does not contain any uppercase ASCII characters."47 | 48 |
Format can also be used for case conversions, as shown below:
49 |MsgBox Format("{:U}, {:L} and {:T}", "upper", "LOWER", "title")50 | 51 |
InStr, SubStr, StrLen, StrReplace
53 |Converts the string to lowercase and stores "this is a test." in String1.
56 |String1 := "This is a test." 57 | String1 := StrLower(String1) ; i.e. output can be the same as input.58 |
Converts the string to uppercase and stores "THIS IS A TEST." in String2.
62 |String2 := "This is a test." 63 | String2 := StrUpper(String2)64 |
Converts the string to title case and stores "This Is A Test." in String3.
68 |String3 := "This is a test." 69 | String3 := StrTitle(String3)70 |
Returns the current memory address of a string.
16 |Address := StrPtr(Value)
17 |
18 | Type: String
24 |Type: Integer
30 |This function returns the current memory address of Value.
31 | 32 |The lifetime of an address and which operations are valid to perform on it depend on how Value was passed to this function. There are three distinct cases, shown as example code below. In all cases, if the string will not be modified, the return value can be passed directly to a DllCall function or SendMessage.
34 |Ptr := StrPtr(MyVar)35 |
If Value is a variable reference such as MyVar
(and not a built-in variable), the return value is the memory address of the variable's internal string buffer. VarSetStrCapacity(&MyVar)
returns the size of the buffer in characters, excluding the terminating null character.
The address should be considered valid only until the variable is freed or has been reassigned by means of any of the assignment operators or by passing it to a built-in function. The address of the contents of a function's local variable is not valid after the function returns, as local variables are freed automatically.
37 |The address can be stored in a structure or another variable, and passed indirectly to DllCall or SendMessage or used in other ways, for as long as it remains valid as described above.
38 |The script may change the value of the string indirectly by passing the address to NumPut, DllCall or SendMessage. If the length of the string is changed this way, the variable's internal length property must be updated by calling VarSetStrCapacity(&MyVar, -1)
.
Ptr := StrPtr("literal string")40 |
The address of a literal string is valid until the program exits. The script should not attempt to modify the string. The address can be stored in a structure or another variable, and passed indirectly to DllCall or SendMessage or used in other ways.
41 |SendMessage 0x000C, 0, StrPtr(A_ScriptName " changed this title"),, "A"42 |
The address of a temporary string is valid only until evaluation of the overall expression or function call statement is completed, after which time it must not be used. For the example above, the address is valid until SendMessage returns. All of the following yield temporary strings:
43 |If not explicitly covered above, it is safe to assume the string is temporary.
50 | 51 |VarSetStrCapacity, DllCall, SendMessage, Buffer object, NumPut, NumGet
53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /docs/lib/StrPut.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Copies a string to a memory address or buffer, optionally converting it to a given code page.
16 | 17 |18 | BytesWritten := StrPut(String, Target , Length, Encoding) 19 | BytesWritten := StrPut(String, Target , Encoding) 20 | ReqBufSize := StrPut(String , Encoding) 21 |22 |
Type: String
28 |Any string. If a number is given, it is automatically converted to a string.
29 |String is assumed to be in the native encoding.
30 |A Buffer-like object or memory address to which the string will be written.
36 |Any object which implements Ptr and Size properties may be used, but this function is optimized for the native Buffer object. Passing an object with these properties ensures that the function does not write memory to an invalid location; doing so could cause crashes or other unpredictable behaviour.
37 |Note: If conversion between code pages is necessary, the required buffer size may differ from the size of the source string. For such cases, call StrPut with two parameters to calculate the required size.
38 |Type: Integer
43 |The maximum number of characters to write, including the null-terminator if required.
44 |If Length is zero or less than the projected length after conversion (or the length of the source string if conversion is not required), an exception is thrown.
45 |Length must not be omitted when Target is a plain memory address, unless the buffer size is known to be sufficient, such as if the buffer was allocated based on a previous call to StrPut with the same String and Encoding.
46 |If Target is an object, specifying a Length that exceeds the buffer size calculated from Target.Size
is considered an error, even if the converted string would fit within the buffer.
Note: When Encoding is specified, Length should be the size of the buffer (in characters), not the length of String or a substring, as conversion may increase its length.
48 |Note: Length is measured in characters, whereas buffer sizes are usually measured in bytes, as is StrPut's return value. To specify the buffer size in bytes, use a Buffer-like object in the Target parameter.
49 |If omitted, the string is simply copied or measured without any conversion taking place. Otherwise, specify the target encoding; for example, "UTF-8"
, "UTF-16"
or "CP936"
. For numeric identifiers, the prefix "CP" can be omitted only in 4-parameter mode. Specify an empty string or "CP0"
to use the system default ANSI code page.
Type: Integer
61 |In 4- or 3-parameter mode, this function returns the number of bytes written. A null-terminator is written and included in the return value only when there is sufficient space; that is, it is omitted when Length or Target.Size
(multiplied by the size of a character) exactly equals the length of the converted string.
In 2-parameter mode, this function returns the required buffer size in bytes, including space for the null-terminator.
63 | 64 |A ValueError is thrown if invalid parameters are detected, such as if the converted string would be longer than allowed by Length or Target.Size
.
An OSError is thrown if the conversion could not be performed.
67 | 68 |Note that the String parameter is always assumed to use the native encoding of the current executable, whereas Encoding specifies the encoding of the string written to the given Target. If no Encoding is specified, the string is simply copied or measured without any conversion taking place.
70 | 71 |String Encoding, StrGet, Binary Compatibility, FileEncoding, DllCall, Buffer object, VarSetStrCapacity
73 | 74 |Either Length or Encoding may be specified directly after Target, but in those cases Encoding must be non-numeric.
77 |78 | StrPut(str, address, "cp0") ; Code page 0, unspecified buffer size 79 | StrPut(str, address, n, 0) ; Maximum n chars, code page 0 80 | StrPut(str, address, 0) ; Unsupported (maximum 0 chars) 81 |82 |
StrPut may be called once to calculate the required buffer size for a string in a particular encoding, then again to encode and write the string into the buffer. The process can be simplified by utilizing this function.
85 |; Returns a Buffer object containing the string. 86 | StrBuf(str, encoding) 87 | { 88 | ; Calculate required size and allocate a buffer. 89 | buf := Buffer(StrPut(str, encoding)) 90 | ; Copy or convert the string. 91 | StrPut(str, buf, encoding) 92 | return buf 93 | }94 |
Replaces the specified substring with a new string.
15 |ReplacedStr := StrReplace(Haystack, Needle , ReplaceText, CaseSense, &OutputVarCount, Limit)16 | 17 |
Type: String
23 |The string whose content is searched and replaced.
24 |Type: String
29 |The string to search for.
30 |Type: String
35 |If blank or omitted, Needle will be replaced with blank (empty), meaning it will be omitted from the return value. Otherwise, specify the string to replace Needle with.
36 |Type: String or Integer (boolean)
41 |If omitted, it defaults to Off. Otherwise, specify one of the following values:
42 |On or 1 (true): The search is case-sensitive.
43 |Off or 0 (false): The search is not case-sensitive, i.e. the letters A-Z are considered identical to their lowercase counterparts.
44 |Locale: The search is not case-sensitive according to the rules of the current user's locale. For example, most English and Western European locales treat not only the letters A-Z as identical to their lowercase counterparts, but also non-ASCII letters like Ä and Ü as identical to theirs. Locale is 1 to 8 times slower than Off depending on the nature of the strings being compared.
45 |Type: VarRef
50 |If omitted, the corresponding value will not be stored. Otherwise, specify a reference to the output variable in which to store the number of replacements that occurred (0 if none).
51 |Type: Integer
56 |If omitted, it defaults to -1, which replaces all occurrences of the pattern found in Haystack. Otherwise, specify the maximum number of replacements to allow. The part of Haystack to the right of the last replacement is left unchanged.
57 |Type: String
63 |This function returns the replaced version of the specified string.
64 | 65 |The built-in variables A_Space and A_Tab contain a single space and a single tab character, respectively. They are useful when searching for spaces and tabs alone or at the beginning or end of Needle.
67 | 68 |RegExReplace, InStr, SubStr, StrLen, StrLower, StrUpper
70 | 71 |Removes all CR-LF pairs from the clipboard contents.
74 |A_Clipboard := StrReplace(A_Clipboard, "`r`n")75 |
Removes all blank lines from the text in a variable.
84 |Loop 85 | { 86 | MyString := StrReplace(MyString, "`r`n`r`n", "`r`n",, &Count) 87 | if (Count = 0) ; No more replacements needed. 88 | break 89 | }90 |
Separates a string into an array of substrings using the specified delimiters.
15 |Array := StrSplit(String , Delimiters, OmitChars, MaxParts)16 | 17 |
Type: String
23 |A string to split.
24 |If blank or omitted, each character of the input string will be treated as a separate substring.
30 |Otherwise, specify either a single string or an array of strings (case-sensitive), each of which is used to determine where the boundaries between substrings occur. Since the delimiters are not considered to be part of the substrings themselves, they are never included in the returned array. Also, if there is nothing between a pair of delimiters within the input string, the corresponding array element will be blank.
31 |For example: ","
would divide the string based on every occurrence of a comma. Similarly, [A_Space, A_Tab]
would create a new array element every time a space or tab is encountered in the input string.
Type: String
37 |If blank or omitted, no characters will be excluded. Otherwise, specify a list of characters (case-sensitive) to exclude from the beginning and end of each array element. For example, if OmitChars is " `t"
, spaces and tabs will be removed from the beginning and end (but not the middle) of every element.
If Delimiters is blank, OmitChars indicates which characters should be excluded from the array.
39 |Type: Integer
44 |If omitted, it defaults to -1, which means "no limit". Otherwise, specify the maximum number of substrings to return. If non-zero, the string is split a maximum of MaxParts-1 times and the remainder of the string is returned in the last substring (excluding any leading or trailing OmitChars).
45 |Type: Array
51 |This function returns an array containing the substrings of the specified string.
52 | 53 |Whitespace characters such as spaces and tabs will be preserved unless those characters are included in the Delimiters or OmitChars parameters. Spaces and tabs can be trimmed from both ends of any variable by using Trim. For example: Var := Trim(Var)
To split a string that is in standard CSV (comma separated value) format, use a parsing loop since it has built-in CSV handling.
56 |To arrange the fields in a different order prior to splitting them, use the Sort function.
57 |If you do not need the substrings to be permanently stored in memory, consider using a parsing loop -- especially if String is very large, in which case a large amount of memory would be saved. For example:
58 |Colors := "red,green,blue" 59 | Loop Parse, Colors, "," 60 | MsgBox "Color number " A_Index " is " A_LoopField61 | 62 |
Parsing loop, Sort, SplitPath, InStr, SubStr, StrLen, StrLower, StrUpper, StrReplace
64 | 65 |Separates a sentence into an array of words and reports the fourth word.
68 |TestString := "This is a test." 69 | word_array := StrSplit(TestString, A_Space, ".") ; Omits periods. 70 | MsgBox "The 4th word is " word_array[4]71 |
Separates a comma-separated list of colors into an array of substrings and traverses them, one by one.
75 |colors := "red,green,blue" 76 | For index, color in StrSplit(colors, ",") 77 | MsgBox "Color number " index " is " color78 |
Converts a value to a string.
16 |StrValue := String(Value)
17 |
18 | Type: String
20 |This function returns the result of converting Value to a string, or Value itself if it is a string.
21 |If Value is a number, the default decimal formatting is used.
22 |If Value is an object, the return value is the result of calling Value.ToString()
. If the object has no such method, a MethodError is thrown. This method is not implemented by default, so must be defined by the script.
Type, Integer, Float, Values, Expressions, Is functions
26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /docs/lib/SubStr.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Retrieves one or more characters from the specified position in a string.
16 | 17 |NewStr := SubStr(String, StartingPos , Length)18 |
Type: String
24 |The string whose content is copied. This may contain binary zero.
25 |Type: Integer
30 |Specify 1 to start at the first character, 2 to start at the second, and so on. If StartingPos is 0 or beyond String's length, an empty string is returned.
31 |Specify a negative StartingPos to start at that position from the right. For example, -1 extracts the last character and -2 extracts the two last characters. If StartingPos tries to go beyond the left end of the string, the extraction starts at the first character.
32 |Type: Integer
37 |If omitted, it defaults to "all characters". Otherwise, specify the maximum number of characters to retrieve (fewer than the maximum are retrieved whenever the remaining part of the string is too short).
38 |You can also specify a negative Length to omit that many characters from the end of the returned string (an empty string is returned if all or too many characters are omitted).
39 |Type: String
45 |This function returns the requested substring of the specified string.
46 | 47 |Retrieves a substring with a length of 3 characters at position 4.
53 |MsgBox SubStr("123abc789", 4, 3) ; Returns abc54 |
Retrieves a substring from the beginning and end of a string.
58 |Str := "The Quick Brown Fox Jumps Over the Lazy Dog" 59 | MsgBox SubStr(Str, 1, 19) ; Returns "The Quick Brown Fox" 60 | MsgBox SubStr(Str, -8) ; Returns "Lazy Dog" 61 |62 |
Disables or enables all or selected hotkeys and hotstrings.
16 | 17 |Suspend NewState18 |
Type: Integer
24 |If omitted, it defaults to -1. Otherwise, specify one of the following values:
25 |1
or True
: Suspends all hotkeys and hotstrings except those explained the Remarks section.
0
or False
: Re-enables the hotkeys and hotstrings that were disable above.
-1
: Changes to the opposite of its previous state (On or Off).
By default, the script can also be suspended via its tray icon or main window.
34 |A hotkey/hotstring can be made exempt from suspension by preceding it with the #SuspendExempt directive. An exempt hotkey/hotstring will remain enabled even while suspension is ON. This allows suspension to be turned off via a hotkey, which would otherwise be impossible since the hotkey would be suspended.
35 |The keyboard and/or mouse hooks will be installed or removed if justified by the changes made by this function.
36 |To disable selected hotkeys or hotstrings automatically based on any condition, such as the type of window that is active, use #HotIf.
37 |Suspending a script's hotkeys does not stop the script's already-running threads (if any); use Pause to do that.
38 |When a script's hotkeys are suspended, its tray icon changes to (or to if the script is also paused). This icon change can be avoided by freezing the icon, which is achieved by using TraySetIcon(,, true)
.
The built-in variable A_IsSuspended contains 1 if the script is suspended and 0 otherwise.
40 | 41 |#SuspendExempt, Hotkeys, Hotstrings, #HotIf, Pause, ExitApp
43 | 44 |Press a hotkey once to suspend all hotkeys and hotstrings. Press it again to unsuspend.
47 |#SuspendExempt 48 | ^!s::Suspend ; Ctrl+Alt+S 49 | #SuspendExempt False50 |
Sends a Suspend command to another script.
54 |DetectHiddenWindows True 55 | WM_COMMAND := 0x0111 56 | ID_FILE_SUSPEND := 65404 57 | PostMessage WM_COMMAND, ID_FILE_SUSPEND,,, "C:\YourScript.ahk ahk_class AutoHotkey"58 |
Compares a value with multiple cases and executes the statements of the first match.
16 | 17 |Switch SwitchValue, CaseSense 18 | { 19 | Case CaseValue1: 20 | Statements1 21 | Case CaseValue2a, CaseValue2b: 22 | Statements2 23 | Default: 24 | Statements3 25 | }26 | 27 |
If this and CaseSense are omitted, the first case which evaluates to true (non-zero and non-empty) is executed. Otherwise, SwitchValue is evaluated once and compared to each case value until a match is found, and then that case is executed.
33 |If there is no matching case and Default is present, it is executed.
34 |Type: String or Integer (boolean)
39 |If omitted, it defaults to On. Otherwise, specify one of the following values, which forces all values to be compared as strings:
40 |On or 1 (true): Each comparison is case-sensitive.
41 |Off or 0 (false): Each comparison is not case-sensitive, i.e. the letters A-Z are considered identical to their lowercase counterparts.
42 |Locale: Each comparison is not case-sensitive according to the rules of the current user's locale. For example, most English and Western European locales treat not only the letters A-Z as identical to their lowercase counterparts, but also non-ASCII letters like Ä and Ü as identical to theirs. Locale is 1 to 8 times slower than Off depending on the nature of the strings being compared.
43 |The value to check or compare depending on whether SwitchValue is present.
47 |As with the =
and ==
operators, when CaseSense is omitted, numeric comparison is performed if SwitchValue and the case value are both pure numbers, or if one is a pure number and the other is a numeric string. Each case value is considered separately and does not affect the type of comparison used for other case values.
If the CaseSense parameter is present, all values are compared as strings, not as numbers, and a TypeError is thrown if SwitchValue or a CaseValue evaluates to an object.
54 |If the CaseSense parameter is omitted, string comparisons are case-sensitive by default.
55 |Each case may list up to 20 values. Each value must be an expression, but can be a simple one such as a literal number, quoted string or variable. Case and Default must be terminated with a colon.
56 |The first statement of each case may be below Case or on the same line, following the colon. Each case implicitly ends at the next Case/Default or the closing brace. Unlike the switch statement found in some other languages, there is no implicit fall-through and Break is not used (except to break out of an enclosing loop).
57 |As all cases are enclosed in the same block, a label defined in one case can be the target of Goto from another case. However, if a label is placed immediately above Case or Default, it targets the end of the previous case, not the beginning of the next one.
58 |Default is not required to be listed last.
59 | 60 |Compares a number with multiple cases and shows the message box of the first match.
66 |switch 2 67 | { 68 | case 1: MsgBox "no match" 69 | case 2: MsgBox "match" 70 | case 3: MsgBox "no match" 71 | }72 |
The SwitchValue parameter can be omitted to execute the first case which evaluates to true.
76 |str := "The quick brown fox jumps over the lazy dog" 77 | switch 78 | { 79 | case InStr(str, "blue"): MsgBox "false" 80 | case InStr(str, "brown"): MsgBox "true" 81 | case InStr(str, "green"): MsgBox "false" 82 | }83 |
To test this example, type [ followed by one of the abbreviations listed below, any other 5 characters, or Enter/Esc/Tab/.; or wait for 4 seconds.
87 |~[:: 88 | { 89 | ih := InputHook("V T5 L4 C", "{enter}.{esc}{tab}", "btw,otoh,fl,ahk,ca") 90 | ih.Start() 91 | ih.Wait() 92 | switch ih.EndReason 93 | { 94 | case "Max": 95 | MsgBox 'You entered "' ih.Input '", which is the maximum length of text' 96 | case "Timeout": 97 | MsgBox 'You entered "' ih.Input '" at which time the input timed out' 98 | case "EndKey": 99 | MsgBox 'You entered "' ih.Input '" and terminated it with ' ih.EndKey 100 | default: ; Match 101 | switch ih.Input 102 | { 103 | case "btw": Send "{backspace 3}by the way" 104 | case "otoh": Send "{backspace 4}on the other hand" 105 | case "fl": Send "{backspace 2}Florida" 106 | case "ca": Send "{backspace 2}California" 107 | case "ahk": 108 | Send "{backspace 3}" 109 | Run "https://www.autohotkey.com" 110 | } 111 | } 112 | }113 |
Retrieves dimensions of system objects, and other system properties.
16 | 17 |Value := SysGet(Property)
18 | Type: Integer
24 |Specify one of the numbers from the tables below to retrieve the corresponding value.
25 |Type: Integer
31 |This function returns the value of the specified system property.
32 | 33 |Number | 37 |Description | 38 |
---|---|
80 | 41 |SM_CMONITORS: Number of display monitors on the desktop (not including "non-display pseudo-monitors"). | 42 |
43 | 45 |SM_CMOUSEBUTTONS: Number of buttons on mouse (0 if no mouse is installed). | 46 |
16, 17 | 49 |SM_CXFULLSCREEN, SM_CYFULLSCREEN: Width and height of the client area for a full-screen window on the primary display monitor, in pixels. | 50 |
61, 62 | 53 |SM_CXMAXIMIZED, SM_CYMAXIMIZED: Default dimensions, in pixels, of a maximized top-level window on the primary display monitor. | 54 |
59, 60 | 57 |SM_CXMAXTRACK, SM_CYMAXTRACK: Default maximum dimensions of a window that has a caption and sizing borders, in pixels. This metric refers to the entire desktop. The user cannot drag the window frame to a size larger than these dimensions. | 58 |
28, 29 | 61 |SM_CXMIN, SM_CYMIN: Minimum width and height of a window, in pixels. | 62 |
57, 58 | 65 |SM_CXMINIMIZED, SM_CYMINIMIZED: Dimensions of a minimized window, in pixels. | 66 |
34, 35 | 69 |SM_CXMINTRACK, SM_CYMINTRACK: Minimum tracking width and height of a window, in pixels. The user cannot drag the window frame to a size smaller than these dimensions. A window can override these values by processing the WM_GETMINMAXINFO message. | 70 |
0, 1 | 73 |SM_CXSCREEN, SM_CYSCREEN: Width and height of the screen of the primary display monitor, in pixels. These are the same as the built-in variables A_ScreenWidth and A_ScreenHeight. | 74 |
78, 79 | 77 |SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN: Width and height of the virtual screen, in pixels. The virtual screen is the bounding rectangle of all display monitors. The SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN metrics are the coordinates of the top-left corner of the virtual screen. | 78 |
19 | 81 |SM_MOUSEPRESENT: Nonzero if a mouse is installed; zero otherwise. | 82 |
75 | 85 |SM_MOUSEWHEELPRESENT: Nonzero if a mouse with a wheel is installed; zero otherwise. | 86 |
63 | 89 |SM_NETWORK: Least significant bit is set if a network is present; otherwise, it is cleared. The other bits are reserved for future use. | 90 |
8193 | 93 |SM_REMOTECONTROL: This system metric is used in a Terminal Services environment. Its value is nonzero if the current session is remotely controlled; zero otherwise. | 94 |
4096 | 97 |SM_REMOTESESSION: This system metric is used in a Terminal Services environment. If the calling process is associated with a Terminal Services client session, the return value is nonzero. If the calling process is associated with the Terminal Server console session, the return value is zero. The console session is not necessarily the physical console. | 98 |
70 | 101 |SM_SHOWSOUNDS: Nonzero if the user requires an application to present information visually in situations where it would otherwise present the information only in audible form; zero otherwise. | 102 |
8192 | 105 |SM_SHUTTINGDOWN: Nonzero if the current session is shutting down; zero otherwise. Windows 2000: The retrieved value is always 0. | 106 |
23 | 109 |SM_SWAPBUTTON: Nonzero if the meanings of the left and right mouse buttons are swapped; zero otherwise. | 110 |
76, 77 | 113 |SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN: Coordinates for the left side and the top of the virtual screen. The virtual screen is the bounding rectangle of all display monitors. By contrast, the SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN metrics (further above) are the width and height of the virtual screen. | 114 |
Number | 121 |Description | 122 |
---|---|
56 | 125 |SM_ARRANGE: Flags specifying how the system arranged minimized windows. See Microsoft Docs for more information. | 126 |
67 | 129 |SM_CLEANBOOT: Specifies how the system was started: 130 |
|
136 |
5, 6 | 139 |SM_CXBORDER, SM_CYBORDER: Width and height of a window border, in pixels. This is equivalent to the SM_CXEDGE value for windows with the 3-D look. | 140 |
13, 14 | 143 |SM_CXCURSOR, SM_CYCURSOR: Width and height of a cursor, in pixels. The system cannot create cursors of other sizes. | 144 |
36, 37 | 147 |SM_CXDOUBLECLK, SM_CYDOUBLECLK: Width and height of the rectangle around the location of a first click in a double-click sequence, in pixels. The second click must occur within this rectangle for the system to consider the two clicks a double-click. (The two clicks must also occur within a specified time.) | 148 |
68, 69 | 151 |SM_CXDRAG, SM_CYDRAG: Width and height of a rectangle centered on a drag point to allow for limited movement of the mouse pointer before a drag operation begins. These values are in pixels. It allows the user to click and release the mouse button easily without unintentionally starting a drag operation. | 152 |
45, 46 | 155 |SM_CXEDGE, SM_CYEDGE: Dimensions of a 3-D border, in pixels. These are the 3-D counterparts of SM_CXBORDER and SM_CYBORDER. | 156 |
7, 8 | 159 |SM_CXFIXEDFRAME, SM_CYFIXEDFRAME (synonymous with SM_CXDLGFRAME, SM_CYDLGFRAME): Thickness of the frame around the perimeter of a window that has a caption but is not sizable, in pixels. SM_CXFIXEDFRAME is the height of the horizontal border and SM_CYFIXEDFRAME is the width of the vertical border. | 160 |
83, 84 | 163 |SM_CXFOCUSBORDER, SM_CYFOCUSBORDER: Width (in pixels) of the left and right edges and the height of the top and bottom edges of a control's focus rectangle. Windows 2000: The retrieved value is always 0. | 164 |
21, 3 | 167 |SM_CXHSCROLL, SM_CYHSCROLL: Width of the arrow bitmap on a horizontal scroll bar, in pixels; and height of a horizontal scroll bar, in pixels. | 168 |
10 | 171 |SM_CXHTHUMB: Width of the thumb box in a horizontal scroll bar, in pixels. | 172 |
11, 12 | 175 |SM_CXICON, SM_CYICON: Default width and height of an icon, in pixels. | 176 |
38, 39 | 179 |SM_CXICONSPACING, SM_CYICONSPACING: Dimensions of a grid cell for items in large icon view, in pixels. Each item fits into a rectangle of this size when arranged. These values are always greater than or equal to SM_CXICON and SM_CYICON. | 180 |
71, 72 | 183 |SM_CXMENUCHECK, SM_CYMENUCHECK: Dimensions of the default menu check-mark bitmap, in pixels. | 184 |
54, 55 | 187 |SM_CXMENUSIZE, SM_CYMENUSIZE: Dimensions of menu bar buttons, such as the child window close button used in the multiple document interface, in pixels. | 188 |
47, 48 | 191 |SM_CXMINSPACING, SM_CYMINSPACING: Dimensions of a grid cell for a minimized window, in pixels. Each minimized window fits into a rectangle this size when arranged. These values are always greater than or equal to SM_CXMINIMIZED and SM_CYMINIMIZED. | 192 |
30, 31 | 195 |SM_CXSIZE, SM_CYSIZE: Width and height of a button in a window's caption or title bar, in pixels. | 196 |
32, 33 | 199 |SM_CXSIZEFRAME, SM_CYSIZEFRAME: Thickness of the sizing border around the perimeter of a window that can be resized, in pixels. SM_CXSIZEFRAME is the width of the horizontal border, and SM_CYSIZEFRAME is the height of the vertical border. Synonymous with SM_CXFRAME and SM_CYFRAME. | 200 |
49, 50 | 203 |SM_CXSMICON, SM_CYSMICON: Recommended dimensions of a small icon, in pixels. Small icons typically appear in window captions and in small icon view. | 204 |
52, 53 | 207 |SM_CXSMSIZE SM_CYSMSIZE: Dimensions of small caption buttons, in pixels. | 208 |
2, 20 | 211 |SM_CXVSCROLL, SM_CYVSCROLL: Width of a vertical scroll bar, in pixels; and height of the arrow bitmap on a vertical scroll bar, in pixels. | 212 |
4 | 215 |SM_CYCAPTION: Height of a caption area, in pixels. | 216 |
18 | 219 |SM_CYKANJIWINDOW: For double byte character set versions of the system, this is the height of the Kanji window at the bottom of the screen, in pixels. | 220 |
15 | 223 |SM_CYMENU: Height of a single-line menu bar, in pixels. | 224 |
51 | 227 |SM_CYSMCAPTION: Height of a small caption, in pixels. | 228 |
9 | 231 |SM_CYVTHUMB: Height of the thumb box in a vertical scroll bar, in pixels. | 232 |
42 | 235 |SM_DBCSENABLED: Nonzero if User32.dll supports DBCS; zero otherwise. | 236 |
22 | 239 |SM_DEBUG: Nonzero if the debug version of User.exe is installed; zero otherwise. | 240 |
82 | 243 |SM_IMMENABLED: Nonzero if Input Method Manager/Input Method Editor features are enabled; zero otherwise. 244 |SM_IMMENABLED indicates whether the system is ready to use a Unicode-based IME on a Unicode application. To ensure that a language-dependent IME works, check SM_DBCSENABLED and the system ANSI code page. Otherwise the ANSI-to-Unicode conversion may not be performed correctly, or some components like fonts or registry setting may not be present. |
245 |
40 | 248 |SM_MENUDROPALIGNMENT: Nonzero if drop-down menus are right-aligned with the corresponding menu-bar item; zero if the menus are left-aligned. | 249 |
74 | 252 |SM_MIDEASTENABLED: Nonzero if the system is enabled for Hebrew and Arabic languages, zero if not. | 253 |
41 | 256 |SM_PENWINDOWS: Nonzero if the Microsoft Windows for Pen computing extensions are installed; zero otherwise. | 257 |
44 | 260 |SM_SECURE: Nonzero if security is present; zero otherwise. | 261 |
81 | 264 |SM_SAMEDISPLAYFORMAT: Nonzero if all the display monitors have the same color format, zero otherwise. Note that two displays can have the same bit depth, but different color formats. For example, the red, green, and blue pixels can be encoded with different numbers of bits, or those bits can be located in different places in a pixel's color value. | 265 |
SysGet simply calls the GetSystemMetrics function, which may support more system properties than are documented here.
269 | 270 |DllCall, Win functions, Monitor functions
272 | 273 |Retrieves the number of mouse buttons and stores it in MouseButtonCount.
276 |MouseButtonCount := SysGet(43)277 |
Retrieves the width and height of the virtual screen and stores them in VirtualScreenWidth and VirtualScreenHeight.
281 |VirtualScreenWidth := SysGet(78) 282 | VirtualScreenHeight := SysGet(79)283 |
Returns an array of the system's IPv4 addresses.
17 | 18 |Addresses := SysGetIPAddresses()
19 |
20 | This function has no parameters.
22 | 23 |Type: Array
25 |This function returns an array, where each element is an IPv4 address string such as "192.168.0.1".
26 | 27 |Currently only IPv4 is supported.
29 |This function returns only the IP addresses of the computer's network adapters. If the computer is connected to the Internet through a router, this will not include the computer's public (Internet) IP address. To determine the computer's public IP address, use an external web API. For example:
30 |whr := ComObject("WinHttp.WinHttpRequest.5.1") 31 | whr.Open("GET", "https://api.ipify.org") 32 | whr.Send() 33 | MsgBox "Public IP address: " whr.ResponseText34 | 35 |
Retrieves and reports the system's IPv4 addresses.
41 |addresses := SysGetIPAddresses() 42 | msg := "IP addresses:`n" 43 | for n, address in addresses 44 | msg .= address "`n" 45 | MsgBox msg46 |
Sets the priority or interruptibility of threads. It can also temporarily disable all timers.
16 |Thread SubFunction , Value1, Value217 |
The SubFunction, Value1, and Value2 parameters are dependent upon each other and their usage is described below.
18 | 19 |For SubFunction, specify one of the following:
21 |Prevents interruptions from any timers.
29 |Thread "NoTimers" , False30 |
This sub-function prevents interruptions from any timers until the current thread either ends, executes Thread "NoTimers", false
, or is interrupted by another thread that allows timers (in which case timers can interrupt the interrupting thread until it finishes).
If this setting is not changed by the auto-execute thread, all threads start off as interruptible by timers (though the settings of the Interrupt sub-function described below will still apply). By contrast, if the auto-execute thread turns on this setting but never turns it off, every newly launched thread (such as a hotkey, custom menu item, or timer) starts off immune to interruptions by timers.
32 |Regardless of the default setting, timers will always operate when the script has no threads (unless Pause has been turned on).
33 |Thread "NoTimers"
is equivalent to Thread "NoTimers", true
. In addition, since the False parameter is an expression, true resolves to 1, and false to 0. See Boolean Values for details.
Changes the priority level of the current thread.
37 |Thread "Priority", Level
38 | Specify for Level an integer between -2147483648 and 2147483647 (or an expression) to indicate the current thread's new priority. This has no effect on other threads. See Threads for details.
39 |Due to its ability to buffer events, the function Critical is generally superior to this sub-function.
40 |On a related note, the OS's priority level for the entire script can be changed via ProcessSetPriority. For example:
41 |ProcessSetPriority "High"42 | 43 |
Changes the duration of interruptibility for newly launched threads.
45 |Thread "Interrupt" , Duration, LineCount46 |
Note: This sub-function should be used sparingly because most scripts perform more consistently with settings close to the defaults.
47 |By default, every newly launched thread is uninterruptible for a Duration of 15 milliseconds or a LineCount of 1000 script lines, whichever comes first. This gives the thread a chance to finish rather than being immediately interrupted by another thread that is waiting to launch (such as a buffered hotkey or a series of timed subroutines that are all due to be run).
48 |Note: Any Duration less than 17 might result in a shorter actual duration or immediate interruption, since the system tick count has a minimum resolution of 10 to 16 milliseconds. However, at least one line will execute before the thread becomes interruptible, allowing the script to enable Critical, if needed.
49 |If either parameter is 0, each newly launched thread is immediately interruptible. If either parameter is -1, the thread cannot be interrupted as a result of that parameter. The maximum for both parameters is 2147483647.
50 |This setting is global, meaning that it affects all subsequent threads, even if this function was not called by the auto-execute thread. However, interrupted threads are unaffected because their period of uninterruptibility has already expired. Similarly, the current thread is unaffected except if it is uninterruptible at the time the LineCount parameter is changed, in which case the new LineCount will be in effect for it.
51 |If a hotkey is pressed or a custom menu item is selected while the current thread is uninterruptible, that event will be buffered. In other words, it will launch when the current thread finishes or becomes interruptible, whichever comes first. The exception to this is when the current thread becomes interruptible before it finishes, and it is of higher priority than the buffered event; in this case the buffered event is unbuffered and discarded.
52 |Regardless of this sub-function, a thread will become interruptible the moment it displays a MsgBox, InputBox, FileSelect, or DirSelect dialog.
53 |Either parameter can be left blank to avoid changing it.
54 | 55 |Due to its greater flexibility and its ability to buffer events, the function Critical is generally more useful than Thread "Interrupt"
and Thread "Priority"
.
Critical, Threads, Hotkey, Menu object, SetTimer, Process functions
59 |Makes the priority of the current thread slightly above average.
62 |Thread "Priority", 163 |
Makes each thread interruptible after 50 ms or 2000 lines, whichever comes first.
72 |Thread "Interrupt", 50, 200073 |
Signals the occurrence of an error. This signal can be caught by a Try-Catch statement.
16 | 17 |Throw Value18 |
A value to throw; typically an Error object. For example:
24 |throw ValueError("Parameter #1 invalid", -1, theBadParam)25 |
Values of all kinds can be thrown, but if Catch is used without specifying a class (or Try is used without Catch or Finally), it will only catch instances of the Error class.
26 |While execution is within a Catch, Value can be omitted to re-throw the caught value (avoiding the need to specify an output variable just for that purpose). This is supported even within a nested Try-Finally, but not within a nested Try-Catch. The line with throw
does not need to be physically contained by the Catch statement's body; it can be used by a called function.
The space or tab after throw
is optional if the expression is enclosed in parentheses, as in throw(Error())
.
A thrown value or runtime error can be caught by Try-Catch. In such cases, execution is transferred into the catch statement or to the next statement after the try. If a thrown value is not caught, the following occurs:
34 |Error Object, Try, Catch, Finally, OnError
42 | 43 |See Try.
45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/lib/ToolTip.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Shows an always-on-top window anywhere on the screen.
16 | 17 |ToolTip Text, X, Y, WhichToolTip18 |
Type: String
24 |If blank or omitted, the existing tooltip (if any) will be hidden. Otherwise, specify the text to display in the tooltip. To create a multi-line tooltip, use the linefeed character (`n) in between each line, e.g. "Line1`nLine2"
.
If Text is long, it can be broken up into several shorter lines by means of a continuation section, which might improve readability and maintainability.
26 |Type: Integer
31 |If omitted, the tooltip will be shown near the mouse cursor. Otherwise, specify the X and Y position of the tooltip relative to the active window's client area (use CoordMode "ToolTip"
to change to screen coordinates).
Type: Integer
37 |If omitted, it defaults to 1 (the first tooltip). Otherwise, specify a number between 1 and 20 to indicate which tooltip to operate upon when using multiple tooltips simultaneously.
38 |Type: Integer
44 |If a tooltip is being shown or updated, this function returns the tooltip window's unique ID (HWND), which can be used to move the tooltip or send Tooltip Control Messages.
45 |If Text is blank or omitted, the return value is zero.
46 | 47 |A tooltip usually looks like this:
49 |If the X and Y coordinates caused the tooltip to run off-screen, or outside the monitor's working area on Windows 8 or later, it is repositioned to be entirely visible.
50 |The tooltip is displayed until one of the following occurs:
51 |A GUI window may be made the owner of a tooltip by means of the OwnDialogs option. Such a tooltip is automatically destroyed when its owner is destroyed.
57 |CoordMode, TrayTip, GUI, MsgBox, InputBox, FileSelect, DirSelect
59 |Shows a multiline tooltip at a specific position in the active window.
62 |ToolTip "Multiline`nTooltip", 100, 15063 |
Hides a tooltip after a certain amount of time without having to use Sleep (which would stop the current thread).
67 |ToolTip "Timed ToolTip`nThis will be displayed for 5 seconds." 68 | SetTimer () => ToolTip(), -500069 |
Changes the script's tray icon (which is also used by GUI and dialog windows).
17 | 18 |TraySetIcon FileName, IconNumber, Freeze19 |
Type: String
25 |If omitted, the current tray icon is used, which is only meaningful for Freeze. Otherwise, specify the path to an icon or image file, a bitmap or icon handle such as "HICON:" handle
, or an asterisk (*) to restore the script's default icon.
For a list of supported formats, see the Picture control.
27 |Type: Integer
32 |If omitted, it defaults to 1 (the first icon group in the file). Otherwise, specify the number of the icon group to use. For example, 2
would load the default icon from the second icon group. If negative, the absolute value is assumed to be the resource ID of an icon within an executable file. If FileName is omitted, IconNumber is ignored.
Type: Boolean
38 |If omitted, the icon's frozen/unfrozen state remains unchanged.
39 |If true, the icon is frozen, i.e. Pause and Suspend will not change it.
40 |If false, the icon is unfrozen.
41 |To freeze (or unfreeze) the current icon, use the function as follows: TraySetIcon(,, true)
.
Changing the tray icon also changes the icon displayed by InputBox and subsequently-created GUI windows. Compiled scripts are also affected even if a custom icon was specified at the time of compiling. Note: Changing the icon will not unhide the tray icon if it was previously hidden by means such as #NoTrayIcon; to do that, use A_IconHidden := false
.
Slight distortion may occur when loading tray icons from file types other than .ICO. This is especially true for 16x16 icons. To prevent this, store the desired tray icon inside a .ICO file.
49 |There are some icons built into the operating system's DLLs and CPLs that might be useful. For example: TraySetIcon "Shell32.dll", 174
.
The built-in variables A_IconNumber and A_IconFile contain the number and name (with full path) of the current icon (both are blank if the icon is the default).
51 |The tray icon's tooltip can be changed by assigning a value to A_IconTip.
52 | 53 |#NoTrayIcon, TrayTip, Menu object
55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /docs/lib/TrayTip.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Shows a balloon message window or, on Windows 10 and later, a toast notification near the tray icon.
24 | 25 |TrayTip Text, Title, Options26 |
Type: String
32 |If blank or omitted, the text will be entirely omitted from the traytip, making it vertically shorter. Otherwise, specify the message to display. Only the first 255 characters will be displayed.
33 |Carriage return (`r) or linefeed (`n) may be used to create multiple lines of text. For example: Line1`nLine2
.
If Text is long, it can be broken up into several shorter lines by means of a continuation section, which might improve readability and maintainability.
35 |Type: String
40 |If blank or omitted, the title line will be entirely omitted from the traytip, making it vertically shorter. Otherwise, specify the title of the traytip. Only the first 63 characters will be displayed.
41 |If blank or omitted, it defaults to 0. Otherwise, specify either an integer value (a combination by addition or bitwise-OR) or a string of zero or more case-insensitive options separated by at least one space or tab. One or more numeric options may also be included in the string.
47 |Function | 50 |Dec | 51 |Hex | 52 |String | 53 |
---|---|---|---|
No icon | 56 |0 | 57 |0x0 | 58 |N/A | 59 |
Info icon | 62 |1 | 63 |0x1 | 64 |Iconi |
65 |
Warning icon | 68 |2 | 69 |0x2 | 70 |Icon! |
71 |
Error icon | 74 |3 | 75 |0x3 | 76 |Iconx |
77 |
Tray icon | 80 |4 | 81 |0x4 | 82 |N/A | 83 |
Do not play the notification sound. | 86 |16 | 87 |0x10 | 88 |Mute |
89 |
Use the large version of the icon. | 92 |32 | 93 |0x20 | 94 |N/A | 95 |
The icon is also not shown by the traytip if it lacks a title (this does not apply to the toast notifications on Windows 10 and later).
98 |On Windows 10 and later, the small tray icon is generally displayed even if the "tray icon" option (4) is omitted, and specifying this option may cause the program's name to be shown in the notification.
99 |To hide the traytip, omit all parameters (or at least the Text and Title parameters). For example:
105 |TrayTip106 |
To hide the traytip on Windows 10, temporarily remove the tray icon (which not always work, according to at least one report). For example:
107 |TrayTip "#1", "This is TrayTip #1" 108 | Sleep 3000 ; Let it display for 3 seconds. 109 | HideTrayTip 110 | TrayTip "#2", "This is the second notification." 111 | Sleep 3000 112 | 113 | ; Copy this function into your script to use it. 114 | HideTrayTip() { 115 | TrayTip ; Attempt to hide it the normal way. 116 | if SubStr(A_OSVersion,1,3) = "10." { 117 | A_IconHidden := true 118 | Sleep 200 ; It may be necessary to adjust this sleep. 119 | A_IconHidden := false 120 | } 121 | } 122 |123 | 124 |
On Windows 10, a traytip window usually looks like this:
126 | 127 |Windows 10 and later replace all balloon windows with toast notifications by default (this can be overridden via group policy). Calling TrayTip multiple times will usually cause multiple notifications to be placed in a "queue" instead of each notification replacing the last.
128 |TrayTip has no effect if the script lacks a tray icon (via #NoTrayIcon or A_IconHidden := true
). TrayTip also has no effect if the following REG_DWORD value exists and has been set to 0:
HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced >> EnableBalloonTips130 |
On a related note, there is a tooltip displayed whenever the user hovers the mouse over the script's tray icon. The contents of this tooltip can be changed via: A_IconTip := "My New Text"
.
ToolTip, SetTimer, Menu object, MsgBox, InputBox, FileSelect, DirSelect
134 | 135 |Shows a multiline balloon message or toast notification for 20 seconds near the tray icon without playing the notification sound. It also has a title and contains an info icon.
138 |TrayTip "Multiline`nText", "My Title", "Iconi Mute"139 |
Provides a more precise control over the display time without having to use Sleep (which would stop the current thread).
143 |TrayTip "This will be displayed for 5 seconds.", "Timed traytip" 144 | SetTimer () => TrayTip(), -5000145 |
The following does the same, but allows you to replace the HideTrayTip function definition with the one defined above for Windows 10.
146 |TrayTip "This will be displayed for 5 seconds.", "Timed traytip" 147 | SetTimer HideTrayTip, -5000 148 | 149 | HideTrayTip() { 150 | TrayTip 151 | } 152 |153 |
Permanently displays a traytip by refreshing it periodically via timer. Note that this probably won't work well on Windows 10 and later for reasons described above.
157 |SetTimer RefreshTrayTip, 1000 158 | RefreshTrayTip ; Call it once to get it started right away. 159 | 160 | RefreshTrayTip() 161 | { 162 | TrayTip "This is a more permanent traytip.", "Refreshed traytip", "Mute" 163 | }164 |
A TreeView displays a hierarchy of items by indenting child items beneath their parents. The most common example is Explorer's tree of drives and folders.
26 |A TreeView usually looks like this:
27 | 28 |The syntax for creating a TreeView is:
29 |TV := GuiObj.Add("TreeView", Options)
30 | Or:
31 |TV := GuiObj.AddTreeView(Options)
32 | Here is a working script that creates and displays a simple hierarchy of items:
33 |MyGui := Gui() 34 | TV := MyGui.Add("TreeView") 35 | P1 := TV.Add("First parent") 36 | P1C1 := TV.Add("Parent 1's first child", P1) ; Specify P1 to be this item's parent. 37 | P2 := TV.Add("Second parent") 38 | P2C1 := TV.Add("Parent 2's first child", P2) 39 | P2C2 := TV.Add("Parent 2's second child", P2) 40 | P2C2C1 := TV.Add("Child 2's first child", P2C2) 41 | 42 | MyGui.Show() ; Show the window and its TreeView.43 |
Background: Specify the word Background followed immediately by a color name (see color chart) or RGB value (the 0x prefix is optional). Examples: BackgroundSilver
, BackgroundFFDD99
. If this option is not present, the TreeView initially defaults to the system's default background color. Specifying BackgroundDefault
or -Background
applies the system's default background color (usually white). For example, a TreeView can be restored to the default color via TV.Opt("+BackgroundDefault")
.
Buttons: Specify -Buttons
(minus Buttons) to avoid displaying a plus or minus button to the left of each item that has children.
C: Text color. Specify the letter C followed immediately by a color name (see color chart) or RGB value (the 0x prefix is optional). Examples: cRed
, cFF2211
, c0xFF2211
, cDefault
.
Checked: Provides a checkbox at the left side of each item. When adding an item, specify the word Check in its options to have the box to start off checked instead of unchecked. The user may either click the checkbox or press the spacebar to check or uncheck an item. To discover which items in a TreeView are currently checked, call the GetNext method or Get method.
48 |HScroll: Specify -HScroll
(minus HScroll) to disable horizontal scrolling in the control (in addition, the control will not display any horizontal scroll bar).
ImageList: This is the means by which icons are added to a TreeView. Specify the word ImageList followed immediately by the ImageListID returned from a previous call to IL_Create. This option has an effect only when creating a TreeView (however, the SetImageList method does not have this limitation). Here is a working example:
50 |MyGui := Gui() 51 | ImageListID := IL_Create(10) ; Create an ImageList with initial capacity for 10 icons. 52 | Loop 10 ; Load the ImageList with some standard system icons. 53 | IL_Add(ImageListID, "shell32.dll", A_Index) 54 | TV := MyGui.Add("TreeView", "ImageList" . ImageListID) 55 | TV.Add("Name of Item", 0, "Icon4") ; Add an item to the TreeView and give it a folder icon. 56 | MyGui.Show()57 |
Lines: Specify -Lines
(minus Lines) to avoid displaying a network of lines connecting parent items to their children. However, removing these lines also prevents the plus/minus buttons from being shown for top-level items.
ReadOnly: Specify -ReadOnly
(minus ReadOnly) to allow editing of the text/name of each item. To edit an item, select it then press F2 (see the WantF2 option below). Alternatively, you can click an item once to select it, wait at least half a second, then click the same item again to edit it. After being edited, an item can be alphabetically repositioned among its siblings via the following example:
TV := MyGui.Add("TreeView", "-ReadOnly") 60 | TV.OnEvent("ItemEdit", TV_Edit) ; Call TV_Edit whenever a user has finished editing an item. 61 | ; ... 62 | TV_Edit(TV, Item) 63 | { 64 | TV.Modify(TV.GetParent(Item), "Sort") ; This works even if the item has no parent. 65 | }66 |
R: Rows of height (upon creation). Specify the letter R followed immediately by the number of rows for which to make room inside the control. For example, R10
would make the control 10 items tall.
WantF2: Specify -WantF2
(minus WantF2) to prevent F2 from editing the currently selected item. This setting is ignored unless -ReadOnly is also in effect.
(Unnamed numeric styles): Since styles other than the above are rarely used, they do not have names. See the TreeView styles table for a list.
69 |In addition to the default methods/properties of a GUI control, TreeView controls have the following methods (defined in the Gui.TreeView class).
71 |Item methods:
72 |Retrieval methods:
78 |Other methods:
89 |Adds a new item to the TreeView.
96 |ItemID := TV.Add(Name, ParentItemID, Options)97 |
Type: String
102 |The displayed text of the item, which can be text or numeric (including numeric expression results).
103 |Type: Integer
107 |If omitted, it defaults to 0, meaning the item will be added at the top level. Otherwise, specify the ID number of the new item's parent.
108 |Type: String
112 |If blank or omitted, it defaults to no options. Otherwise, specify one or more options from the list below (not case-sensitive). Separate each option from the next with a space or tab. To remove an option, precede it with a minus sign. To add an option, a plus sign is permitted but not required.
113 |Bold: Displays the item's name in a bold font. To later un-bold the item, use TV.Modify(ItemID, "-Bold")
. The word Bold may optionally be followed immediately by a 0 or 1 to indicate the starting state.
Check: Shows a checkmark to the left of the item (if the TreeView has checkboxes). To later uncheck it, use TV.Modify(ItemID, "-Check")
. The word Check may optionally be followed immediately by a 0 or 1 to indicate the starting state. In other words, both "Check"
and "Check" . VarContainingOne
are the same (the period used here is the concatenation operator).
Expand: Expands the item to reveal its children (if any). To later collapse the item, use TV.Modify(ItemID, "-Expand")
. If there are no children, the Modify method returns 0 instead of the item's ID. By contrast, the Add method marks the item as expanded in case children are added to it later. Unlike the Select option below, expanding an item does not automatically expand its parent. Finally, the word Expand may optionally be followed immediately by a 0 or 1 to indicate the starting state. In other words, both "Expand"
and "Expand" . VarContainingOne
are the same.
First | Sort | N: These options apply only to the Add method. They specify the new item's position relative to its siblings (a sibling is any other item on the same level). If none of these options is present, the new item is added as the last/bottom sibling. Otherwise, specify the word First to add the item as the first/top sibling, or specify the word Sort to insert it among its siblings in alphabetical order. If a plain integer N is specified, it is assumed to be ID number of the sibling after which to insert the new item (if N is the only option present, it does not have to be enclosed in quotes).
117 |Icon: Specify the word Icon followed immediately by the number of this item's icon, which is displayed to the left of the item's name. If this option is absent, the first icon in the ImageList is used. To display a blank icon, specify a number that is larger than the number of icons in the ImageList. If the control lacks an ImageList, no icon is displayed nor is any space reserved for one.
118 |Select: Selects the item. Since only one item at a time can be selected, any previously selected item is automatically de-selected. In addition, this option reveals the newly selected item by expanding its parent(s), if necessary. To find out the current selection, call the GetSelection method.
119 |Sort: For the Modify method, this option alphabetically sorts the children of the specified item. To instead sort all top-level items, use TV.Modify(0, "Sort")
. If there are no children, 0 is returned instead of the ID of the modified item.
Vis: Ensures that the item is completely visible by scrolling the TreeView and/or expanding its parent, if necessary.
121 |VisFirst: Same as above except that the TreeView is also scrolled so that the item appears at the top, if possible. This option is typically more effective when used with the Modify method than with the Add method.
122 |Type: Integer
126 |On success, this method returns the unique ID number of the newly added item. On failure, it returns 0.
127 |When adding a large number of items, performance can be improved by using TV.Opt("-Redraw")
before adding the items and TV.Opt("+Redraw")
afterward. See Redraw for more details.
Modifies the attributes and/or name of an item.
134 |ItemID := TV.Modify(ItemID , Options, NewName)135 |
Type: Integer
140 |The ID number of the item to modify.
141 |Type: String
145 |If this and the NewName parameter is omitted, the item will be selected. Otherwise, specify one or more options from the list above.
146 |Type: String
150 |If omitted, the current name is left unchanged. Otherwise, specify the new name of the item.
151 |Type: Integer
155 |This method returns the item's own ID.
156 |Deletes the specified item or all items.
161 |TV.Delete(ItemID)162 |
Type: Integer
167 |If omitted, all items in the TreeView are deleted. Otherwise, specify the ID number of the item to delete.
168 |Returns the selected item's ID number.
175 |ItemID := TV.GetSelection()
176 | Type: Integer
178 |This method returns the selected item's ID number.
179 |Returns the total number of items in the control.
184 |Count := TV.GetCount()
185 | Type: Integer
187 |This method returns the total number of items in the control. The value is always returned immediately because the control keeps track of the count.
188 |Returns the ID number of the specified item's parent.
193 |ParentItemID := TV.GetParent(ItemID)
194 | Type: Integer
199 |The ID number of the item to check.
200 |Type: Integer
204 |This method returns the ID number of the specified item's parent. If the item has no parent, it returns 0, which applies to all top-level items.
205 |Returns the ID number of the specified item's first/top child.
210 |ChildItemID := TV.GetChild(ItemID)
211 | Type: Integer
216 |The ID number of the item to check. If 0, the ID number of the first/top item in the TreeView is returned.
217 |Type: Integer
221 |This method returns the ID number of the specified item's first/top child. If there is no child, it returns 0.
222 |Returns the ID number of the sibling above the specified item.
227 |PrevItemID := TV.GetPrev(ItemID)
228 | Type: Integer
232 |The ID number of the item to check.
233 |Type: Integer
237 |This method returns the ID number of the sibling above the specified item. If there is no sibling, it returns 0.
238 |Returns the ID number of the next item below the specified item.
243 |NextItemID := TV.GetNext(ItemID, ItemType)244 |
Type: Integer
249 |If omitted, it defaults to 0, meaning the ID number of the first/top item in the TreeView is returned. Otherwise, specify the ID number of the item to check.
250 |Type: String
254 |If omitted, the ID number of the sibling below the specified item will be retrieved. Otherwise, specify one of the following strings:
255 |Full or F: Retrieves the next item regardless of its relationship to the specified item. This allows the script to easily traverse the entire tree, item by item. See the example below.
256 |Check, Checked or C: Gets only the next item with a checkmark.
257 |Type: Integer
261 |This method returns the ID number of the next item below the specified item. If there is no next item, it returns 0.
262 |The following example traverses the entire tree, item by item:
264 |ItemID := 0 ; Causes the loop's first iteration to start the search at the top of the tree. 265 | Loop 266 | { 267 | ItemID := TV.GetNext(ItemID, "Full") ; Replace "Full" with "Checked" to find all checkmarked items. 268 | if not ItemID ; No more items in tree. 269 | break 270 | ItemText := TV.GetText(ItemID) 271 | MsgBox('The next Item is ' ItemID ', whose text is "' ItemText '".') 272 | }273 |
Retrieves the text/name of the specified item.
278 |Text := TV.GetText(ItemID)
279 | Type: Integer
284 |The ID number of the item whose text to be retrieved.
285 |Type: String
289 |This method returns the retrieved text. Only up to 8191 characters are retrieved.
290 |Returns the ID number of the specified item if it has the specified attribute.
295 |ItemID := TV.Get(ItemID, Attribute)
296 | Type: Integer
301 |The ID number of the item to check.
302 |Type: String
306 |Specify one of the following strings:
307 |E, Expand or Expanded: The item is currently expanded (i.e. its children are being displayed).
308 |C, Check or Checked: The item has a checkmark.
309 |B or Bold: The item is currently bold in font.
310 |Type: Integer
314 |If the specified item has the specified attribute, its own ID is returned. Otherwise, 0 is returned.
315 |Since an IF-statement sees any non-zero value as "true", the following two lines are functionally identical: if TV.Get(ItemID, "Checked") = ItemID
and if TV.Get(ItemID, "Checked")
.
Sets or replaces an ImageList for displaying icons.
322 |PrevImageListID := TV.SetImageList(ImageListID , IconType)323 |
Type: Integer
328 |The ID number returned from a previous call to IL_Create.
329 |Type: Integer
333 |If omitted, it defaults to 0. Otherwise, specify 2 for state icons (which are not yet directly supported, but could be used via SendMessage).
334 |Type: Integer
338 |On success, this method returns the ImageList ID that was previously associated with the TreeView. On failure, it returns 0. Any such detached ImageList should normally be destroyed via IL_Destroy.
339 |The following events can be detected by calling OnEvent to register a callback function or method:
343 |Event | Raised when... |
---|---|
Click | The control is clicked. |
DoubleClick | The control is double-clicked. |
ContextMenu | The user right-clicks the control or presses Menu or Shift+F10 while the control has the keyboard focus. |
Focus | The control gains the keyboard focus. |
LoseFocus | The control loses the keyboard focus. |
ItemCheck | An item is checked or unchecked. |
ItemEdit | An item's label is edited by the user. |
ItemExpand | An item is expanded or collapsed. |
ItemSelect | An item is selected. |
Additional (rarely-used) notifications can be detected by using OnNotify. These notifications are documented at Microsoft Docs. Microsoft Docs does not show the numeric value of each notification code; those can be found in the Windows SDK or by searching the Internet.
356 | 357 |To detect when the user has pressed Enter while a TreeView has focus, use a default button (which can be hidden if desired). For example:
359 |MyGui.Add("Button", "Hidden Default", "OK").OnEvent("Click", ButtonOK) 360 | ... 361 | ButtonOK(*) { 362 | global 363 | if MyGui.FocusedCtrl != TV 364 | return 365 | MsgBox("Enter was pressed. The selected item ID is " TV.GetSelection()) 366 | }367 |
In addition to navigating from item to item with the keyboard, the user may also perform incremental search by typing the first few characters of an item's name. This causes the selection to jump to the nearest matching item.
368 |Although any length of text can be stored in each item of a TreeView, only the first 260 characters are displayed.
369 |Although the theoretical maximum number of items in a TreeView is 65536, item-adding performance will noticeably decrease long before then. This can be alleviated somewhat by using the redraw tip described in the Add method.
370 |Unlike ListViews, a TreeView's ImageList is not automatically destroyed when the TreeView is destroyed. Therefore, 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.
371 |A script may create more than one TreeView per window.
372 |To perform actions such as resizing, hiding, or changing the font of a TreeView, see GuiControl object.
373 |Tree View eXtension (TVX) extends TreeViews to support moving, inserting and deleting. It is demonstrated at this archived forum thread.
374 |ListView, Other Control Types, Gui(), ContextMenu event, Gui object, GuiControl object, TreeView styles table
376 | 377 |The following is a working script that is more elaborate than the one near the top of this page. It creates and displays a TreeView containing all folders in the all-users Start Menu. When the user selects a folder, its contents are shown in a ListView to the right (like Windows Explorer). In addition, a StatusBar control shows information about the currently selected folder.
381 |; The following folder will be the root folder for the TreeView. Note that loading might take a long 382 | ; time if an entire drive such as C:\ is specified: 383 | TreeRoot := A_MyDocuments 384 | TreeViewWidth := 280 385 | ListViewWidth := A_ScreenWidth/2 - TreeViewWidth - 30 386 | 387 | ; Create the Gui window and display the source directory (TreeRoot) in the title bar: 388 | MyGui := Gui("+Resize", TreeRoot) ; Allow the user to maximize or drag-resize the window. 389 | 390 | ; Create an ImageList and put some standard system icons into it: 391 | ImageListID := IL_Create(5) 392 | Loop 5 393 | IL_Add(ImageListID, "shell32.dll", A_Index) 394 | ; Create a TreeView and a ListView side-by-side to behave like Windows Explorer: 395 | TV := MyGui.Add("TreeView", "r20 w" TreeViewWidth " ImageList" ImageListID) 396 | LV := MyGui.Add("ListView", "r20 w" ListViewWidth " x+10", ["Name", "Modified"]) 397 | 398 | ; Create a Status Bar to give info about the number of files and their total size: 399 | SB := MyGui.Add("StatusBar") 400 | SB.SetParts(60, 85) ; Create three parts in the bar (the third part fills all the remaining width). 401 | 402 | ; Add folders and their subfolders to the tree. Display the status in case loading takes a long time: 403 | M := Gui("ToolWindow -SysMenu Disabled AlwaysOnTop", "Loading the tree..."), M.Show("w200 h0") 404 | DirList := AddSubFoldersToTree(TreeRoot, Map()) 405 | M.Hide() 406 | 407 | ; Call TV_ItemSelect whenever a new item is selected: 408 | TV.OnEvent("ItemSelect", TV_ItemSelect) 409 | 410 | ; Call Gui_Size whenever the window is resized: 411 | MyGui.OnEvent("Size", Gui_Size) 412 | 413 | ; Set the ListView's column widths (this is optional): 414 | Col2Width := 70 ; Narrow to reveal only the YYYYMMDD part. 415 | LV.ModifyCol(1, ListViewWidth - Col2Width - 30) ; Allows room for vertical scrollbar. 416 | LV.ModifyCol(2, Col2Width) 417 | 418 | ; Display the window. The OS will notify the script whenever the user performs an eligible action: 419 | MyGui.Show() 420 | 421 | AddSubFoldersToTree(Folder, DirList, ParentItemID := 0) 422 | { 423 | ; This function adds to the TreeView all subfolders in the specified folder 424 | ; and saves their paths associated with an ID into an object for later use. 425 | ; It also calls itself recursively to gather nested folders to any depth. 426 | Loop Files, Folder "\*.*", "D" ; Retrieve all of Folder's sub-folders. 427 | { 428 | ItemID := TV.Add(A_LoopFileName, ParentItemID, "Icon4") 429 | DirList[ItemID] := A_LoopFilePath 430 | DirList := AddSubFoldersToTree(A_LoopFilePath, DirList, ItemID) 431 | } 432 | return DirList 433 | } 434 | 435 | TV_ItemSelect(thisCtrl, Item) ; This function is called when a new item is selected. 436 | { 437 | ; Put the files into the ListView: 438 | LV.Delete() ; Clear all rows. 439 | LV.Opt("-Redraw") ; Improve performance by disabling redrawing during load. 440 | TotalSize := 0 ; Init prior to loop below. 441 | Loop Files, DirList[Item] "\*.*" ; For simplicity, omit folders so that only files are shown in the ListView. 442 | { 443 | LV.Add(, A_LoopFileName, A_LoopFileTimeModified) 444 | TotalSize += A_LoopFileSize 445 | } 446 | LV.Opt("+Redraw") 447 | 448 | ; Update the three parts of the status bar to show info about the currently selected folder: 449 | SB.SetText(LV.GetCount() " files", 1) 450 | SB.SetText(Round(TotalSize / 1024, 1) " KB", 2) 451 | SB.SetText(DirList[Item], 3) 452 | } 453 | 454 | Gui_Size(thisGui, MinMax, Width, Height) ; Expand/Shrink ListView and TreeView in response to the user's resizing. 455 | { 456 | if MinMax = -1 ; The window has been minimized. No action needed. 457 | return 458 | ; Otherwise, the window has been resized or maximized. Resize the controls to match. 459 | TV.GetPos(,, &TV_W) 460 | TV.Move(,,, Height - 30) ; -30 for StatusBar and margins. 461 | LV.Move(,, Width - TV_W - 30, Height - 30) 462 | }463 | 464 |
Trims characters from the beginning and/or end of a string.
16 | 17 |NewString := Trim(String , OmitChars) 18 | NewString := LTrim(String , OmitChars) 19 | NewString := RTrim(String , OmitChars)20 |
Type: String
26 |Any string value or variable. Numbers are not supported.
27 |Type: String
32 |If omitted, spaces and tabs will be removed. Otherwise, specify a list of characters (case-sensitive) to exclude from the beginning and/or end of String.
33 |Type: String
39 |These functions return the trimmed version of the specified string.
40 | 41 |Trims all spaces from the left and right side of a string.
44 |text := " text " 45 | MsgBox 46 | ( 47 | "No trim:`t'" text "' 48 | Trim:`t'" Trim(text) "' 49 | LTrim:`t'" LTrim(text) "' 50 | RTrim:`t'" RTrim(text) "'" 51 | )52 |
Guards one or more statements against runtime errors and values thrown by the Throw statement.
16 | 17 |Try Statement
18 | Try
19 | {
20 | Statements
21 | }
22 | The Try statement is usually followed by a block (one or more statements enclosed in braces). If only a single statement is to be executed, it can be placed on the same line as Try or on the next line, and the braces can be omitted. To specify code that executes only when Try catches an error, use one or more Catch statements.
24 |If Try is used without Catch or Finally, it is equivalent to having catch Error
with an empty block.
A value can be thrown by the Throw statement or by the program when a runtime error occurs. When a value is thrown from within a Try block or a function called by one, the following occurs:
26 |The last Catch can optionally be followed by Else. If the Try statement completes without an exception being thrown (and without control being transferred elsewhere by Return, Break or similar), the Else statement is executed. Exceptions thrown by the Else statement are not handled by its associated Try statement, but may be handled by an enclosing Try statement. Finally can also be present, but must be placed after Else, and is always executed last.
32 |The One True Brace (OTB) style may optionally be used with the Try statement. For example:
33 |try { 34 | ... 35 | } catch Error as err { 36 | ... 37 | } else { 38 | ... 39 | } finally { 40 | ... 41 | }42 | 43 |
Throw, Catch, Else, Finally, Blocks, OnError
45 | 46 |Demonstrates the basic concept of Try-Catch and Throw.
49 |try ; Attempts to execute code. 50 | { 51 | HelloWorld 52 | MakeToast 53 | } 54 | catch as e ; Handles the first error thrown by the block above. 55 | { 56 | MsgBox "An error was thrown!`nSpecifically: " e.Message 57 | Exit 58 | } 59 | 60 | HelloWorld() ; Always succeeds. 61 | { 62 | MsgBox "Hello, world!" 63 | } 64 | 65 | MakeToast() ; Always fails. 66 | { 67 | ; Jump immediately to the try block's error handler: 68 | throw Error(A_ThisFunc " is not implemented, sorry") 69 | } 70 |71 |
Demonstrates basic error handling of built-in functions.
75 |try 76 | { 77 | ; The following tries to back up certain types of files: 78 | FileCopy A_MyDocuments "\*.txt", "D:\Backup\Text documents" 79 | FileCopy A_MyDocuments "\*.doc", "D:\Backup\Text documents" 80 | FileCopy A_MyDocuments "\*.jpg", "D:\Backup\Photos" 81 | } 82 | catch 83 | { 84 | MsgBox "There was a problem while backing the files up!",, "IconX" 85 | ExitApp 1 86 | } 87 | else 88 | { 89 | MsgBox "Backup successful." 90 | ExitApp 0 91 | } 92 |93 |
Demonstrates the use of Try-Catch dealing with COM errors. For details about the COM object used below, see Using the ScriptControl (Microsoft Docs).
97 |try 98 | { 99 | obj := ComObject("ScriptControl") 100 | obj.ExecuteStatement('MsgBox "This is embedded VBScript"') ; This line produces an Error. 101 | obj.InvalidMethod() ; This line would produce a MethodError. 102 | } 103 | catch MemberError ; Covers MethodError and PropertyError. 104 | { 105 | MsgBox "We tried to invoke a member that doesn't exist." 106 | } 107 | catch as e 108 | { 109 | ; For more detail about the object that e contains, see Error Object. 110 | MsgBox("Exception thrown!`n`nwhat: " e.what "`nfile: " e.file 111 | . "`nline: " e.line "`nmessage: " e.message "`nextra: " e.extra,, 16) 112 | } 113 |114 |
Demonstrates nesting Try-Catch statements.
118 |try Example1 ; Any single statement can be on the same line with Try. 119 | catch Number as e 120 | MsgBox "Example1() threw " e 121 | 122 | Example1() 123 | { 124 | try Example2 125 | catch Number as e 126 | { 127 | if (e = 1) 128 | throw ; Rethrow the caught value to our caller. 129 | else 130 | MsgBox "Example2() threw " e 131 | } 132 | } 133 | 134 | Example2() 135 | { 136 | throw Random(1, 2) 137 | }138 |
Returns the class name of a value.
16 |ClassName := Type(Value)
17 |
18 | Type: String
20 |This function returns the class name of Value.
21 |The algorithm for determining a value's class name can be approximated as shown below:
22 |23 | TypeOf(Value) 24 | { 25 | if (comClass := ComObjType(Value, "Class")) != "" 26 | return comClass 27 | try ; `Value is Object` is not checked because it can be false for prototypes. 28 | if ObjHasOwnProp(Value, "__Class") 29 | return "Prototype" 30 | while Value := ObjGetBase(Value) 31 | if ObjHasOwnProp(Value, "__Class") 32 | return Value.__Class 33 | return "Object" 34 | } 35 |36 |
For COM wrapper objects, the class name can also be determined based on the variant type, as follows:
37 |38 | ComObject_Type(obj) 39 | { 40 | if ComObjType(obj) & 0x2000 ; VT_ARRAY 41 | return "ComObjArray" ; ComObjArray.Prototype.__Class 42 | if ComObjType(obj) & 0x4000 ; VT_BYREF 43 | return "ComValueRef" ; ComValueRef.Prototype.__Class 44 | if (ComObjType(obj) = 9 || ComObjType(obj) = 13) ; VT_DISPATCH || VT_UNKNOWN 45 | && ComObjValue(obj) != 0 46 | { 47 | if (comClass := ComObjType(obj, "Class")) != "" 48 | return comClass 49 | if ComObjType(obj) = 9 ; VT_DISPATCH 50 | return "ComObject" ; ComObject.Prototype.__Class 51 | } 52 | return "ComValue" ; ComValue.Prototype.__Class 53 | } 54 |55 | 56 |
This function typically shouldn't be used to determine if a value is numeric, since numeric strings are valid in math expressions and with most built-in functions. However, in some cases the exact type of a value is more important. In such cases, consider using Value is Number
or similar instead of Type.
To check if a value can be used as a number, use the IsNumber, IsInteger or IsFloat function.
59 |To check for any type of object (that is, anything which is not a primitive value), use the IsObject function.
60 |To check if a value is an instance of a specific class, use the is
operator. This can be used even with primitive values or to identify COM wrapper objects.
Values, Expressions, Is functions, Integer, Float, String
64 | 65 |Retrieves and reports the exact type of the values stored in a, b and c.
68 |69 | a := 1, b := 2.0, c := "3" 70 | MsgBox Type(a) ; Integer 71 | MsgBox Type(b) ; Float 72 | MsgBox Type(c) ; String 73 |74 |
Applies a condition to the continuation of a Loop or For-loop.
16 | 17 |Loop { 18 | ... 19 | } Until Expression20 |
Any valid expression.
The space or tab after Until
is optional if the expression is enclosed in parentheses, as in until(expression)
.
The expression is evaluated once after each iteration, and is evaluated even if Continue was used. If the expression evaluates to false (which is an empty string or the number 0), the loop continues; otherwise, the loop is broken and execution continues at the line following Until.
31 |Loop Until is shorthand for the following:
32 |Loop { 33 | ... 34 | if (Expression) 35 | break 36 | }37 |
However, Loop Until is often easier to understand and unlike the above, can be used with a single-line action. For example:
38 |Loop 39 | x *= 2 40 | Until x > y41 |
Until can be used with any Loop or For. For example:
42 |Loop Read, A_ScriptFullPath 43 | lines .= A_LoopReadLine . "`n" 44 | Until A_Index=5 ; Read the first five lines. 45 | MsgBox lines 46 |47 |
If A_Index is used in Expression, it contains the index of the iteration which has just finished.
48 | 49 |Loop, While-loop, For-loop, Break, Continue, Blocks, Files-and-folders loop, Registry loop, File-reading loop, Parsing loop, If
51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /docs/lib/VarSetStrCapacity.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Enlarges a variable's holding capacity or frees its memory. This is not normally needed, but may be used with DllCall or SendMessage or to optimize repeated concatenation.
17 |GrantedCapacity := VarSetStrCapacity(&TargetVar , RequestedCapacity)18 | 19 |
Type: VarRef
25 |A reference to a variable. For example: VarSetStrCapacity(&MyVar, 1000)
. This can also be a dynamic variable such as Array%i%
or a function's ByRef parameter.
Type: Integer
31 |If omitted, the variable's current capacity will be returned and its contents will not be altered. Otherwise, anything currently in the variable is lost (the variable becomes blank).
32 |Specify for RequestedCapacity the number of characters that the variable should be able to hold after the adjustment. RequestedCapacity does not include the internal zero terminator. For example, specifying 1 would allow the variable to hold up to one character in addition to its internal terminator. Note: the variable will auto-expand if the script assigns it a larger value later.
33 |Since this function is often called simply to ensure the variable has a certain minimum capacity, for performance reasons, it shrinks the variable only when RequestedCapacity is 0. In other words, if the variable's capacity is already greater than RequestedCapacity, it will not be reduced (but the variable will still made blank for consistency).
34 |Therefore, to explicitly shrink a variable, first free its memory with VarSetStrCapacity(&Var, 0)
and then use VarSetStrCapacity(&Var, NewCapacity)
-- or simply let it auto-expand from zero as needed.
For performance reasons, freeing a variable whose previous capacity was less than 64 characters might have no effect because its memory is of a permanent type. In this case, the current capacity will be returned rather than 0.
36 |For performance reasons, the memory of a variable whose capacity is less than 4096 bytes is not freed by storing an empty string in it (e.g. Var := ""
). However, VarSetStrCapacity(&Var, 0)
does free it.
Specify -1 for RequestedCapacity to update the variable's internally-stored string length to the length of its current contents. This is useful in cases where the string has been altered indirectly, such as by passing its address via DllCall or SendMessage. In this mode, VarSetStrCapacity returns the length rather than the capacity.
38 |Type: Integer
44 |This function returns the number of characters that TargetVar can now hold, which will be greater than or equal to RequestedCapacity.
45 | 46 |An exception is thrown under any of the following conditions:
48 |The Buffer object offers superior clarity and flexibility when dealing with binary data, structures, DllCall and similar. For instance, a Buffer object can be assigned to a property or array element or be passed to or returned from a function without copying its contents.
56 |This function can be used to enhance performance when building a string by means of gradual concatenation. This is because multiple automatic resizings can be avoided when you have some idea of what the string's final length will be. In such a case, RequestedCapacity need not be accurate: if the capacity is too small, performance is still improved and the variable will begin auto-expanding when the capacity has been exhausted. If the capacity is too large, some of the memory is wasted, but only temporarily because all the memory can be freed after the operation by means of VarSetStrCapacity(&Var, 0)
or Var := ""
.
Buffer object, DllCall, NumPut, NumGet
60 |Optimize by ensuring MyVar has plenty of space to work with.
63 |VarSetStrCapacity(&MyVar, 5120000) ; ~10 MB 64 | Loop 65 | { 66 | ; ... 67 | MyVar .= StringToConcatenate 68 | ; ... 69 | }70 |
Use a variable to receive a string from an external function via DllCall. (Note that the use of a Buffer object may be preferred; in particular, when dealing with non-Unicode strings.)
74 |max_chars := 10 75 | 76 | Loop 2 77 | { 78 | ; Allocate space for use with DllCall. 79 | VarSetStrCapacity(&buf, max_chars) 80 | 81 | if (A_Index = 1) 82 | ; Alter the variable indirectly via DllCall. 83 | DllCall("wsprintf", "Ptr", StrPtr(buf), "Str", "0x%08x", "UInt", 4919, "CDecl") 84 | else 85 | ; Use "str" to update the length automatically: 86 | DllCall("wsprintf", "Str", buf, "Str", "0x%08x", "UInt", 4919, "CDecl") 87 | 88 | ; Concatenate a string to demonstrate why the length needs to be updated: 89 | wrong_str := buf . "<end>" 90 | wrong_len := StrLen(buf) 91 | 92 | ; Update the variable's length. 93 | VarSetStrCapacity(&buf, -1) 94 | 95 | right_str := buf . "<end>" 96 | right_len := StrLen(buf) 97 | 98 | MsgBox 99 | ( 100 | "Before updating 101 | String: " wrong_str " 102 | Length: " wrong_len " 103 | 104 | After updating 105 | String: " right_str " 106 | Length: " right_len 107 | ) 108 | } 109 |110 |
Compares two version strings.
15 |Result := VerCompare(VersionA, VersionB)
16 |
17 | Type: String
22 |The first version string to be compared.
23 |Type: String
27 |The second version string to be compared, optionally prefixed with one of the following operators: <
, <=
, >
, >=
or =
.
Type: Integer (boolean) or Integer
33 |If VersionB begins with an operator symbol, this function returns 1 (true) or 0 (false).
34 |Otherwise, this function returns one of the following to indicate the relationship between VersionA and VersionB:
35 |To check for a specific relationship between the two strings, compare the result to 0. For example:
41 |a_less_than_b := VerCompare(a, b) < 0 42 | a_greater_than_or_equal_to_b := VerCompare(a, b) >= 043 | 44 |
Version strings are compared according to the same rules as #Requires.
46 |This function should correctly compare Semantic Versioning 2.0.0 version strings, but the parameters are not required to be valid SemVer strings.
47 |This function can be used in a sort callback.
48 |Known limitation: Any numeric component greater than 2147483647 (231-1) is considered equal to 2147483647.
49 | 50 |Checks the version of AutoHotkey in use.
56 |57 | if VerCompare(A_AhkVersion, "2.0") < 0 58 | MsgBox "This version < 2.0; possibly a pre-release version." 59 | else 60 | MsgBox "This version is 2.0 or later." 61 |62 |
Shows one difference between VerCompare and StrCompare.
66 |67 | MsgBox VerCompare("1.20.0", "1.3") ; Returns 1 68 | MsgBox StrCompare("1.20.0", "1.3") ; Returns -1 69 |70 |
Demonstrates comparison with pre-release versions.
74 |75 | MsgBox VerCompare("2.0-a137", "2.0-a136") ; Returns 1 76 | MsgBox VerCompare("2.0-a137", "2.0") ; Returns -1 77 | MsgBox VerCompare("10.2-beta.3", "10.2.0") ; Returns -1 78 |79 |
84 | MsgBox VerCompare("2.0.1", ">=2.0") && VerCompare("2.0.1", "<2.1") ; Returns 1 85 |86 |
Performs one or more statements repeatedly until the specified expression evaluates to false.
16 | 17 |While Expression
18 | Any valid expression. For example: while x < y
.
The space or tab after While
is optional if the expression is enclosed in parentheses, as in While(expression)
.
The expression is evaluated once before each iteration. If the expression evaluates to true (which is any result other than an empty string or the number 0), the body of the loop is executed; otherwise, execution jumps to the line following the loop's body.
29 |A while-loop is usually followed by a block, which is a collection of statements that form the body of the loop. However, a loop with only a single statement does not require a block (an "if" and its "else" count as a single statement for this purpose).
30 |The One True Brace (OTB) style may optionally be used, which allows the open-brace to appear on the same line rather than underneath. For example: while x < y {
.
The built-in variable A_Index contains the number of the current loop iteration. It contains 1 the first time the loop's expression and body are executed. For the second time, it contains 2; and so on. If an inner loop is enclosed by an outer loop, the inner loop takes precedence. A_Index works inside all types of loops, but contains 0 outside of a loop.
32 |As with all loops, Break may be used to exit the loop prematurely. Also, Continue may be used to skip the rest of the current iteration, at which time A_Index is increased by 1 and the while-loop's expression is re-evaluated. If it is still true, a new iteration begins; otherwise, the loop ends.
33 |The loop may optionally be followed by an Else statement, which is executed if the loop had zero iterations.
34 |Specialized loops: Loops can be used to automatically retrieve files, folders, or registry items (one at a time). See file loop and registry loop for details. In addition, file-reading loops can operate on the entire contents of a file, one line at a time. Finally, parsing loops can operate on the individual fields contained inside a delimited string.
35 | 36 |Until, Break, Continue, Blocks, Loop, For-loop, Files-and-folders loop, Registry loop, File-reading loop, Parsing loop, If
38 | 39 |As the user drags the left mouse button, a tooltip displays the size of the region inside the drag-area.
42 |CoordMode "Mouse", "Screen" 43 | 44 | ~LButton:: 45 | { 46 | MouseGetPos &begin_x, &begin_y 47 | while GetKeyState("LButton") 48 | { 49 | MouseGetPos &x, &y 50 | ToolTip begin_x ", " begin_y "`n" Abs(begin_x-x) " x " Abs(begin_y-y) 51 | Sleep 10 52 | } 53 | ToolTip 54 | }55 |
Functions for retrieving information about one or more windows or for performing various operations on a window. Click on a function name for details.
17 |Function | 20 |Description | 21 |
---|---|
WinActivate | 24 |Activates the specified window. | 25 |
WinActivateBottom | 28 |Same as WinActivate except that it activates the bottommost matching window rather than the topmost. | 29 |
WinActive | 32 |Checks if the specified window exists and is currently active (foremost). | 33 |
WinClose | 36 |Closes the specified window. | 37 |
WinExist | 40 |Checks if the specified window exists. | 41 |
WinGetClass | 44 |Retrieves the specified window's class name. | 45 |
WinGetClientPos | 48 |Retrieves the position and size of the specified window's client area. | 49 |
WinGetControls | 52 |Returns an array of names (ClassNNs) for all controls in the specified window. | 53 |
WinGetControlsHwnd | 56 |Returns an array of unique ID numbers (HWNDs) for all controls in the specified window. | 57 |
WinGetCount | 60 |Returns the number of existing windows that match the specified criteria. | 61 |
WinGetID | 64 |Returns the unique ID number (HWND) of the specified window. | 65 |
WinGetIDLast | 68 |Returns the unique ID number (HWND) of the last/bottommost window if there is more than one match. | 69 |
WinGetList | 72 |Returns an array of unique ID numbers (HWNDs) for all existing windows that match the specified criteria. | 73 |
WinGetMinMax | 76 |Returns a non-zero number if the specified window is maximized or minimized. | 77 |
WinGetPID | 80 |Returns the Process ID number (PID) of the specified window. | 81 |
WinGetPos | 84 |Retrieves the position and size of the specified window. | 85 |
WinGetProcessName | 88 |Returns the name of the process that owns the specified window. | 89 |
WinGetProcessPath | 92 |Returns the full path and name of the process that owns the specified window. | 93 |
WinGetStyle WinGetExStyle |
96 | Returns the style or extended style (respectively) of the specified window. | 97 |
WinGetText | 100 |Retrieves the text from the specified window. | 101 |
WinGetTitle | 104 |Retrieves the title of the specified window. | 105 |
WinGetTransColor | 108 |Returns the color that is marked transparent in the specified window. | 109 |
WinGetTransparent | 112 |Returns the degree of transparency of the specified window. | 113 |
WinHide | 116 |Hides the specified window. | 117 |
WinKill | 120 |Forces the specified window to close. | 121 |
WinMaximize | 124 |Enlarges the specified window to its maximum size. | 125 |
WinMinimize | 128 |Collapses the specified window into a button on the task bar. | 129 |
WinMinimizeAll WinMinimizeAllUndo |
132 | Minimizes or unminimizes all windows. | 133 |
WinMove | 136 |Changes the position and/or size of the specified window. | 137 |
WinMoveBottom | 140 |Sends the specified window to the bottom of stack; that is, beneath all other windows. | 141 |
WinMoveTop | 144 |Brings the specified window to the top of the stack without explicitly activating it. | 145 |
WinRedraw | 148 |Redraws the specified window. | 149 |
WinRestore | 152 |Unminimizes or unmaximizes the specified window if it is minimized or maximized. | 153 |
WinSetAlwaysOnTop | 156 |Makes the specified window stay on top of all other windows (except other always-on-top windows). | 157 |
WinSetEnabled | 160 |Enables or disables the specified window. | 161 |
WinSetRegion | 164 |Changes the shape of the specified window to be the specified rectangle, ellipse, or polygon. | 165 |
WinSetStyle WinSetExStyle |
168 | Changes the style or extended style of the specified window, respectively. | 169 |
WinSetTitle | 172 |Changes the title of the specified window. | 173 |
WinSetTransColor | 176 |Makes all pixels of the chosen color invisible inside the specified window. | 177 |
WinSetTransparent | 180 |Makes the specified window semi-transparent. | 181 |
WinShow | 184 |Unhides the specified window. | 185 |
WinWait | 188 |Waits until the specified window exists. | 189 |
WinWaitActive WinWaitNotActive |
192 | Waits until the specified window is active or not active. | 193 |
WinWaitClose | 196 |Waits until no matching windows can be found. | 197 |
To discover the unique ID number of the window that the mouse is currently hovering over, use MouseGetPos.
202 | 203 |SetWinDelay, Control functions, Gui object (for windows created by the script)
205 | 206 | 207 | 208 | -------------------------------------------------------------------------------- /docs/lib/WinActivate.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Activates the specified window.
16 | 17 |WinActivate WinTitle, WinText, ExcludeTitle, ExcludeText18 |
Type: String, Integer or Object
24 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
25 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
26 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
27 |A TargetError is thrown if the window could not be found.
33 | 34 |When an inactive window becomes active, the operating system also makes it foremost (brings it to the top of the stack). This does not occur if the window is already active.
36 |If the window is minimized and inactive, it is automatically restored prior to being activated. If WinTitle is the letter "A" and the other parameters are omitted, the active window is restored. The window is restored even if it was already active.
37 |Six attempts will be made to activate the target window over the course of 60 ms. If all six attempts fail, WinActivate automatically sends {Alt 2}
as a workaround for possible restrictions enforced by the operating system, and then makes a seventh attempt. Thus, it is usually unnecessary to follow WinActivate with WinWaitActive or if not WinActive(...)
.
After WinActivate's first failed attempt, it automatically sends {Alt up}
. Testing has shown that this may improve the reliability of all subsequent attempts, reducing the number of instances where the first attempt fails and causes the taskbar button to flash. No more than one {Alt up}
is sent for this purpose for the lifetime of each script. If this or any other (AutoHotkey v1.1.27+) script has a keyboard hook installed, the {Alt up}
is blocked from the active window, minimizing the already small risk of side-effects.
In general, if more than one window matches, the topmost matching window (typically the one most recently used) will be activated. If the window is already active, it will be kept active rather than activating any other matching window beneath it. However, if the active window is moved to the bottom of the stack with WinMoveBottom, some other window may be activated even if the active window is a match.
40 |WinActivateBottom activates the bottommost matching window (typically the one least recently used).
41 |GroupActivate activates the next window that matches criteria specified by a window group.
42 |If the active window is hidden and DetectHiddenWindows is turned off, it is never considered a match. Instead, a visible matching window is activated if one exists.
43 |When a window is activated immediately after the activation of some other window, task bar buttons might start flashing on some systems (depending on OS and settings). To prevent this, use #WinActivateForce.
44 |Known issue: If the script is running on a computer or server being accessed via remote desktop, WinActivate may hang if the remote desktop client is minimized. One workaround is to use built-in functions which don't require window activation, such as ControlSend and ControlClick. Another possible workaround is to apply the following registry setting on the local/client computer:
45 |; Change HKCU to HKLM to affect all users on this system. 46 | RegWrite "REG_DWORD", "HKCU\Software\Microsoft\Terminal Server Client" 47 | , "RemoteDesktop_SuppressWhenMinimized", 248 | 49 |
WinActivateBottom, #WinActivateForce, SetTitleMatchMode, DetectHiddenWindows, Last Found Window, WinExist, WinActive, WinWaitActive, WinWait, WinWaitClose, WinClose, GroupActivate, Win functions
51 |If Notepad does exist, activate it, otherwise activate the calculator.
54 |if WinExist("Untitled - Notepad") 55 | WinActivate ; Use the window found by WinExist. 56 | else 57 | WinActivate "Calculator"58 |
Same as WinActivate except that it activates the bottommost matching window rather than the topmost.
16 | 17 |WinActivateBottom WinTitle, WinText, ExcludeTitle, ExcludeText18 |
Type: String, Integer or Object
24 |At least one of these is required. Specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
25 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
26 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
27 |A TargetError is thrown if the window could not be found.
33 | 34 |The bottommost window is typically the one least recently used, except when windows have been reordered, such as with WinMoveBottom.
36 |If there is only one matching window, WinActivateBottom behaves identically to WinActivate.
37 |Window groups are more advanced than this function, so consider using them for more features and flexibility.
38 |If the window is minimized and inactive, it is automatically restored prior to being activated. If WinTitle is the letter "A" and the other parameters are omitted, the active window is restored. The window is restored even if it was already active.
39 |Six attempts will be made to activate the target window over the course of 60 ms. Thus, it is usually unnecessary to follow it with the WinWaitActive function.
40 |Unlike WinActivate, the Last Found Window cannot be used because it might not be the bottommost window. Therefore, at least one of the parameters must be non-blank.
41 |When a window is activated immediately after another window was activated, task bar buttons may start flashing on some systems (depending on OS and settings). To prevent this, use #WinActivateForce.
42 | 43 |WinActivate, #WinActivateForce, SetTitleMatchMode, DetectHiddenWindows, WinExist, WinActive, WinWaitActive, WinWait, WinWaitClose, GroupActivate
45 |Press a hotkey to visit all open browser windows in order from oldest to newest.
48 |#i:: ; Win+I 49 | { 50 | SetTitleMatchMode 2 51 | WinActivateBottom "- Microsoft Internet Explorer" 52 | }53 |
Checks if the specified window is active and returns its unique ID (HWND).
15 |UniqueID := WinActive(WinTitle, WinText, ExcludeTitle, ExcludeText)16 | 17 |
Type: String, Integer or Object
23 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
24 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
25 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
26 |Type: Integer
32 |This function returns the unique ID (HWND) of the active window if it matches the specified criteria, or 0 if it does not.
33 |Since all non-zero numbers are seen as "true", the statement if WinActive(WinTitle)
is true whenever WinTitle is active.
If the active window is a qualified match, the Last Found Window will be updated to be the active window.
37 |An easy way to retrieve the unique ID of the active window is with ActiveHwnd := WinExist("A")
.
SetWinDelay does not apply to this function.
39 | 40 |WinExist, SetTitleMatchMode, DetectHiddenWindows, Last Found Window, WinActivate, WinWaitActive, WinWait, WinWaitClose, #HotIf
42 | 43 |Closes either Notepad or another window, depending on which of them was found by the WinActive 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 WinActive.
46 |if WinActive("ahk_class Notepad") or WinActive("ahk_class" ClassName) 47 | WinClose ; Use the window found by WinActive.48 |
Closes the specified window.
16 | 17 |WinClose WinTitle, WinText, SecondsToWait, ExcludeTitle, ExcludeText18 |
Type: String, Integer or Object
24 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
25 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
26 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
27 |If omitted, the function will not wait at all. Otherwise, specify the number of seconds (can contain a decimal point) to wait for the window to close. If the window does not close within that period, the script will continue.
33 |A TargetError is thrown if the window could not be found, except if the group mode is used.
39 |No exception is thrown if a window is found but cannot be closed, so use WinExist or WinWaitClose if you need to determine for certain that a window has closed.
40 | 41 |This function sends a close message to a window. The result depends on the window (it may ask to save data, etc.)
43 |If a matching window is active, that window will be closed in preference to any other matching window. In general, if more than one window matches, the topmost (most recently used) will be closed.
44 |This function operates only upon a single window except when WinTitle is ahk_group GroupName (with no other criteria specified), in which case all windows in the group are affected.
45 |While the function is in a waiting state, new threads can be launched via hotkey, custom menu item, or timer.
46 |WinClose sends a WM_CLOSE message to the target window, which is a somewhat forceful method of closing it. An alternate method of closing is to send the following message. It might produce different behavior because it is similar in effect to pressing Alt+F4 or clicking the window's close button in its title bar:
47 |PostMessage 0x0112, 0xF060,,, WinTitle, WinText ; 0x0112 = WM_SYSCOMMAND, 0xF060 = SC_CLOSE48 |
If a window does not close via WinClose, you can force it to close with WinKill.
49 | 50 |WinKill, WinWaitClose, ProcessClose, WinActivate, SetTitleMatchMode, DetectHiddenWindows, Last Found Window, WinExist, WinActive, WinWaitActive, WinWait, GroupActivate
52 |If Notepad does exist, close it, otherwise close the calculator.
55 |if WinExist("Untitled - Notepad") 56 | WinClose ; Use the window found by WinExist. 57 | else 58 | WinClose "Calculator"59 |
Checks if the specified window exists and returns the unique ID (HWND) of the first matching window.
15 |UniqueID := WinExist(WinTitle, WinText, ExcludeTitle, ExcludeText)16 | 17 |
Type: String, Integer or Object
23 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
24 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
25 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
26 |Type: Integer
32 |This function returns the unique ID (HWND) of the first matching window (or 0 if none).
33 |Since all non-zero numbers are seen as "true", the statement if WinExist(WinTitle)
is true whenever WinTitle exists.
If a qualified window exists, the Last Found Window will be updated to be that window.
37 |To discover the HWND of a control (for use with PostMessage, SendMessage or DllCall), use ControlGetHwnd or MouseGetPos.
38 |SetWinDelay does not apply to this function.
39 | 40 |WinActive, SetTitleMatchMode, DetectHiddenWindows, Last Found Window, ProcessExist, WinActivate, WinWaitActive, WinWait, WinWaitClose, #HotIf
42 | 43 |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.
46 |if WinExist("ahk_class Notepad") or WinExist("ahk_class" ClassName) 47 | WinActivate ; Use the window found by WinExist.48 |
Retrieves and reports the unique ID (HWND) of the active window.
52 |MsgBox "The active window's ID is " WinExist("A")53 |
Retrieves the specified window's class name.
16 | 17 |Class := WinGetClass(WinTitle, WinText, ExcludeTitle, ExcludeText)18 |
Type: String, Integer or Object
24 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
25 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
26 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
27 |Type: String
33 |This function returns the class name of the specified window.
34 | 35 |A TargetError is thrown if the window could not be found.
37 |An OSError is thrown on if the class name could not be retrieved.
38 | 39 |Only the class name is retrieved (the prefix "ahk_class" is not included in the return value).
41 |For a general explanation of window classes and one way to use them, see ahk_class.
42 | 43 |Retrieves and reports the class name of the active window.
48 |MsgBox "The active window's class is " WinGetClass("A")49 |
Retrieves the position and size of the specified window's client area.
17 | 18 |WinGetClientPos &OutX, &OutY, &OutWidth, &OutHeight, WinTitle, WinText, ExcludeTitle, ExcludeText19 |
Type: VarRef
25 |If omitted, the corresponding value will not be stored. Otherwise, specify references to the output variables in which to store the X and Y coordinates of the client area's upper left corner.
26 |Type: VarRef
31 |If omitted, the corresponding value will not be stored. Otherwise, specify references to the output variables in which to store the width and height of the client area.
32 |Type: String, Integer or Object
37 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
38 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
39 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
40 |A TargetError is thrown if the window could not be found.
46 | 47 |The client area is the part of the window which can contain controls. It excludes the window's title bar, menu (if it has a standard one) and borders. The position and size of the client area are less dependent on OS version and theme than the values returned by WinGetPos.
49 |If WinTitle is "Program Manager"
, the function will retrieve the size of the desktop, which is usually the same as the current screen resolution.
A minimized window will still have a position and size. The values returned in this case may vary depending on OS and configuration, but are usually -32000 for the X and Y coordinates and zero for the width and height.
51 |To discover the name of the window and control that the mouse is currently hovering over, use MouseGetPos.
52 |On systems with multiple screens which have different DPI settings, the returned position and size may be different than expected due to OS DPI scaling.
53 | 54 |WinGetPos, WinMove, ControlGetPos, WinGetTitle, WinGetText, ControlGetText
56 | 57 |Retrieves and reports the position and size of the calculator's client area.
60 |WinGetClientPos &X, &Y, &W, &H, "Calculator" 61 | MsgBox "Calculator's client area is at " X "," Y " and its size is " W "x" H62 |
Retrieves and reports the position of the active window's client area.
66 |WinGetClientPos &X, &Y,,, "A" 67 | MsgBox "The active window's client area is at " X "," Y68 |
If Notepad does exist, retrieve and report the position of its client area.
72 |if WinExist("Untitled - Notepad") 73 | { 74 | WinGetClientPos &Xpos, &Ypos ; Use the window found by WinExist. 75 | MsgBox "Notepad's client area is at " Xpos "," Ypos 76 | }77 |
Returns an array of names (ClassNNs) for all controls in the specified window.
17 | 18 |ClassNNs := WinGetControls(WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
26 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
27 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
28 |Type: Array
33 |This function returns an array of names for all controls in the specified window. Each name consists of the control's class name followed immediately by its sequence number (ClassNN), as shown by Window Spy.
34 |For example, if the return value is assigned to a variable named ClassNNs
and two controls are present, ClassNNs[1]
contains the name of the first control, ClassNNs[2]
contains the name of the second control, and ClassNNs.Length
returns the number 2.
Controls are sorted according to their Z-order, which is usually the same order as the navigation order via Tab if the window supports tabbing.
36 | 37 |A TargetError is thrown if the window could not be found.
39 | 40 |The ID of the window or control under the mouse cursor can be retrieved with MouseGetPos.
42 | 43 |WinGetControlsHwnd, Win functions, Control functions
45 | 46 |Extracts the individual control names from the active window's control list.
49 |for n, ctrl in WinGetControls("A") 50 | { 51 | Result := MsgBox("Control #" n " is '" ctrl "'. Continue?",, 4) 52 | if (Result = "No") 53 | break 54 | }55 |
Displays in real time the active window's control list.
59 |SetTimer WatchActiveWindow, 200 60 | 61 | WatchActiveWindow() 62 | { 63 | try 64 | { 65 | Controls := WinGetControls("A") 66 | ControlList := "" 67 | for ClassNN in Controls 68 | ControlList .= ClassNN . "`n" 69 | if (ControlList = "") 70 | ToolTip "The active window has no controls." 71 | else 72 | ToolTip ControlList 73 | } 74 | catch TargetError 75 | ToolTip "No visible window is active." 76 | }77 |
Returns an array of unique ID numbers (HWNDs) for all controls in the specified window.
17 | 18 |HWNDs := WinGetControlsHwnd(WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
26 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
27 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
28 |Type: Array
33 |This function returns an array of unique ID numbers for all controls in the specified window. Each number is a window handle (HWND).
34 |For example, if the return value is assigned to a variable named HWNDs
and two controls are present, HWNDs[1]
contains the ID of the first control, HWNDs[2]
contains the ID of the second control, and HWNDs.Length
returns the number 2.
Controls are sorted according to their Z-order, which is usually the same order as the navigation order via Tab if the window supports tabbing.
36 | 37 |A TargetError is thrown if the window could not be found.
39 | 40 |The ID of the window or control under the mouse cursor can be retrieved with MouseGetPos.
42 | 43 |WinGetControls, Win functions, Control functions
45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/lib/WinGetCount.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the number of existing windows that match the specified criteria.
17 | 18 |Count := WinGetCount(WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |If each of these is blank or omitted, all windows on the entire system will be counted. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
26 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
27 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
28 |Type: Integer
33 |This function returns the number of existing windows that match the specified criteria. If there is no matching window, zero is returned.
34 | 35 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos.
37 | 38 |WinGetList, Win functions, Control functions
40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /docs/lib/WinGetID.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the unique ID number (HWND) of the specified window.
17 | 18 |HWND := WinGetID(WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
26 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
27 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
28 |Type: Integer
33 |This function returns the window handle (HWND) of the specified window.
34 | 35 |A TargetError is thrown if the window could not be found.
37 | 38 |This function is equivalent to WinExist.
40 |A window's ID number is valid only during its lifetime. In other words, if an application restarts, all of its windows will get new ID numbers.
41 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos. To discover the HWND of a control (for use with PostMessage, SendMessage or DllCall), use ControlGetHwnd or MouseGetPos.
42 | 43 |WinGetIDLast, ControlGetHwnd, Hwnd property (Gui object), Win functions, Control functions
45 | 46 |Maximizes the active window and reports its unique ID.
49 |active_id := WinGetID("A") 50 | WinMaximize active_id 51 | MsgBox "The active window's ID is " active_id52 |
Returns the unique ID number (HWND) of the last/bottommost window if there is more than one match.
17 | 18 |HWND := WinGetIDLast(WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
26 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
27 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
28 |Type: Integer
33 |This function returns the window handle (HWND) of the last/bottommost window if there is more than one match.
34 | 35 |A TargetError is thrown if the window could not be found.
37 | 38 |If there is only one match, it performs identically to WinGetID.
40 |A window's ID number is valid only during its lifetime. In other words, if an application restarts, all of its windows will get new ID numbers.
41 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos. To discover the HWND of a control (for use with PostMessage, SendMessage or DllCall), use ControlGetHwnd or MouseGetPos.
42 | 43 |WinGetID, ControlGetHwnd, Hwnd property (Gui object), Win functions, Control functions
45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/lib/WinGetList.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns an array of unique ID numbers (HWNDs) for all existing windows that match the specified criteria.
17 | 18 |HWNDs := WinGetList(WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |If each of these is blank or omitted, all windows on the entire system will be retrieved. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
26 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
27 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
28 |Type: Array
33 |This function returns an array of unique ID numbers for all existing windows that match the specified criteria. Each number is a window handle (HWND). If there is no matching window, an empty array is returned.
34 |For example, if the return value is assigned to a variable named HWNDs
and two matching windows are discovered, HWNDs[1]
contains the ID of the first window, HWNDs[2]
contains the ID of the second window, and HWNDs.Length
returns the number 2.
Windows are retrieved in order from topmost to bottommost (according to how they are stacked on the desktop).
36 | 37 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos.
39 | 40 |WinGetCount, Win functions, Control functions
42 | 43 |Visits all windows on the entire system and displays info about each of them.
46 |ids := WinGetList(,, "Program Manager") 47 | for this_id in ids 48 | { 49 | WinActivate this_id 50 | this_class := WinGetClass(this_id) 51 | this_title := WinGetTitle(this_id) 52 | Result := MsgBox( 53 | ( 54 | "Visiting All Windows 55 | " A_Index " of " ids.Length " 56 | ahk_id " this_id " 57 | ahk_class " this_class " 58 | " this_title " 59 | 60 | Continue?" 61 | ),, 4) 62 | if (Result = "No") 63 | break 64 | }65 |
Returns a non-zero number if the specified window is maximized or minimized.
17 | 18 |MinMax := WinGetMinMax(WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
26 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
27 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
28 |Type: Integer
33 |This function returns a number indicating the current state of the specified window:
34 |A TargetError is thrown if the window could not be found.
42 | 43 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos.
45 | 46 |WinMaximize, WinMinimize, Win functions, Control functions
48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /docs/lib/WinGetPID.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the Process ID number (PID) of the specified window.
17 | 18 |PID := WinGetPID(WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
26 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
27 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
28 |Type: Integer
33 |This function returns the Process ID (PID) of the specified window.
34 | 35 |A TargetError is thrown if the window could not be found.
37 | 38 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos.
40 | 41 |WinGetProcessName, WinGetProcessPath, Process functions, Win functions, Control functions
43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /docs/lib/WinGetPos.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Retrieves the position and size of the specified window.
16 | 17 |WinGetPos &OutX, &OutY, &OutWidth, &OutHeight, WinTitle, WinText, ExcludeTitle, ExcludeText18 |
Type: VarRef
24 |If omitted, the corresponding value will not be stored. Otherwise, specify references to the output variables in which to store the X and Y coordinates of the target window's upper left corner.
25 |Type: VarRef
30 |If omitted, the corresponding value will not be stored. Otherwise, specify references to the output variables in which to store the width and height of the target window.
31 |Type: String, Integer or Object
36 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
37 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
38 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
39 |A TargetError is thrown if the window could not be found.
45 | 46 |If WinTitle is "Program Manager"
, the function will retrieve the size of the desktop, which is usually the same as the current screen resolution.
A minimized window will still have a position and size. The values returned in this case may vary depending on OS and configuration, but are usually -32000 for the X and Y coordinates and zero for the width and height.
49 |To discover the name of the window and control that the mouse is currently hovering over, use MouseGetPos.
50 |As the coordinates returned by this function include the window's title bar, menu and borders, they may be dependent on OS version and theme. To get more consistent values across different systems, consider using WinGetClientPos instead.
51 |On systems with multiple screens which have different DPI settings, the returned position and size may be different than expected due to OS DPI scaling.
52 | 53 |WinMove, WinGetClientPos, ControlGetPos, WinGetTitle, WinGetText, ControlGetText
55 |Retrieves and reports the position and size of the calculator.
58 |WinGetPos &X, &Y, &W, &H, "Calculator" 59 | MsgBox "Calculator is at " X "," Y " and its size is " W "x" H60 |
Retrieves and reports the position of the active window.
64 |WinGetPos &X, &Y,,, "A" 65 | MsgBox "The active window is at " X "," Y66 |
If Notepad does exist, retrieve and report its position.
70 |if WinExist("Untitled - Notepad") 71 | { 72 | WinGetPos &Xpos, &Ypos ; Use the window found by WinExist. 73 | MsgBox "Notepad is at " Xpos "," Ypos 74 | }75 |
Returns the name of the process that owns the specified window.
17 | 18 |ProcessName := WinGetProcessName(WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
26 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
27 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
28 |Type: String
33 |This function returns the name of the process that owns the specified window. For example: notepad.exe.
34 | 35 |A TargetError is thrown if the window could not be found.
37 | 38 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos.
40 | 41 |WinGetPID, WinGetProcessPath, Process functions, Win functions, Control functions
43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /docs/lib/WinGetProcessPath.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the full path and name of the process that owns the specified window.
17 | 18 |ProcessPath := WinGetProcessPath(WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
26 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
27 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
28 |Type: String
33 |This function returns the full path and name of the process that owns the specified window. For example: C:\Windows\System32\notepad.exe.
34 | 35 |A TargetError is thrown if the window could not be found.
37 | 38 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos.
40 | 41 |WinGetPID, WinGetProcessName, Process functions, Win functions, Control functions
43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /docs/lib/WinGetStyle.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Returns the style or extended style (respectively) of the specified window.
17 | 18 |Style := WinGetStyle(WinTitle, WinText, ExcludeTitle, ExcludeText) 19 | ExStyle := WinGetExStyle(WinTitle, WinText, ExcludeTitle, ExcludeText)20 | 21 |
Type: String, Integer or Object
26 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
27 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
28 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
29 |Type: Integer
34 |These functions return the style or extended style (respectively) of the specified window.
35 | 36 |A TargetError is thrown if the window could not be found.
38 | 39 |See the styles table for a partial listing of styles.
41 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos.
42 | 43 |WinSetStyle / WinSetExStyle, ControlGetStyle / ControlGetExStyle, styles table, Win functions, Control functions
45 | 46 |Determines whether a window has the WS_DISABLED style.
49 |Style := WinGetStyle("My Window Title") 50 | if (Style & 0x8000000) ; 0x8000000 is WS_DISABLED. 51 | MsgBox "The window is disabled."52 |
Determines whether a window has the WS_EX_TOPMOST style (always-on-top).
56 |ExStyle := WinGetExStyle("My Window Title") 57 | if (ExStyle & 0x8) ; 0x8 is WS_EX_TOPMOST. 58 | MsgBox "The window is always-on-top."59 |
Retrieves the text from the specified window.
16 | 17 |Text := WinGetText(WinTitle, WinText, ExcludeTitle, ExcludeText)18 |
Type: String, Integer or Object
24 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
25 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
26 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
27 |Type: String
33 |This function returns the text of the specified window.
34 | 35 |A TargetError is thrown if the window could not be found.
37 |An Error is thrown if there was a problem retrieving the window's text.
38 | 39 |The text retrieved is generally the same as what Window Spy shows for that window. However, if DetectHiddenText has been turned off, hidden text is omitted from the return value.
41 |Each text element ends with a carriage return and linefeed (CR+LF), which can be represented in the script as `r`n. To extract individual lines or substrings, use functions such as InStr and SubStr. A parsing loop can also be used to examine each line or word one by one.
42 |If the retrieved text appears to be truncated (incomplete), it may be necessary to retrieve the text by sending the WM_GETTEXT message via SendMessage instead. This is because some applications do not respond properly to the WM_GETTEXTLENGTH message, which causes AutoHotkey to make the return value too small to fit all the text.
43 |This function might use a large amount of RAM if the target window (e.g. an editor with a large document open) contains a large quantity of text. To avoid this, it might be possible to retrieve only portions of the window's text by using ControlGetText instead. In any case, a variable's memory can be freed later by assigning it to nothing, i.e. Text := ""
.
It is not necessary to do SetTitleMatchMode "Slow"
because WinGetText always retrieves the text using the slow mode (since it works on a broader range of control types).
To retrieve an array of all controls in a window, use WinGetControls or WinGetControlsHwnd.
46 | 47 |ControlGetText, WinGetTitle, WinGetPos
49 |Opens the calculator, waits until it exists, and retrieves and reports its text.
52 |Run "calc.exe" 53 | WinWait "Calculator" 54 | MsgBox "The text is:`n" WinGetText() ; Use the window found by WinWait.55 |
Retrieves the title of the specified window.
16 | 17 |Title := WinGetTitle(WinTitle, WinText, ExcludeTitle, ExcludeText)18 |
Type: String, Integer or Object
24 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
25 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
26 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
27 |Type: String
33 |This function returns the title of the specified window.
34 | 35 |A TargetError is thrown if the window could not be found.
37 | 38 |To discover the name of the window that the mouse is currently hovering over, use MouseGetPos.
40 | 41 |WinSetTitle, WinGetClass, WinGetText, ControlGetText, WinGetPos, Win functions
43 |Retrieves and reports the title of the active window.
46 |MsgBox "The active window is '" WinGetTitle("A") "'."47 |
Returns the color that is marked transparent in the specified window.
17 | 18 |TransColor := WinGetTransColor(WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
26 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
27 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
28 |Type: String
33 |This function returns the six-digit RGB color such as 0x00CC99 that is marked transparent in the specified window.
34 |The return value is an empty string in the following cases:
35 |A TargetError is thrown if the window could not be found.
42 | 43 |To mark a color as transparent, use WinSetTransColor.
45 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos.
46 | 47 |WinSetTransColor, WinGetTransparent, Win functions, Control functions
49 | 50 |Retrieves the transparent color of a window under the mouse cursor.
53 |MouseGetPos ,, &MouseWin 54 | TransColor := WinGetTransColor(MouseWin)55 |
Returns the degree of transparency of the specified window.
17 | 18 |TransDegree := WinGetTransparent(WinTitle, WinText, ExcludeTitle, ExcludeText)19 | 20 |
Type: String, Integer or Object
25 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
26 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
27 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
28 |Type: Integer or String (empty)
33 |This function returns a number between 0 and 255 representing the degree of transparency of the specified window, where 0 indicates an invisible window and 255 indicates an opaque window.
34 |The return value is an empty string in the following cases:
35 |A TargetError is thrown if the window could not be found.
42 | 43 |To set transparency, use WinSetTransparent.
45 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos.
46 | 47 |WinSetTransparent, WinGetTransColor, Win functions, Control functions
49 | 50 |Retrieves the degree of transparency of the window under the mouse cursor.
53 |MouseGetPos ,, &MouseWin 54 | TransDegree := WinGetTransparent(MouseWin)55 |
Hides the specified window.
16 | 17 |WinHide WinTitle, WinText, ExcludeTitle, ExcludeText18 |
Type: String, Integer or Object
24 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
25 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
26 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
27 |A TargetError is thrown if the window could not be found, except if the group mode is used.
33 | 34 |Use WinShow to unhide a hidden window (DetectHiddenWindows can be either On or Off to do this).
36 |This function operates only upon the topmost matching window except when WinTitle is ahk_group GroupName, in which case all windows in the group are affected.
37 | 38 |WinShow, SetTitleMatchMode, DetectHiddenWindows, Last Found Window, Win functions
40 |Opens Notepad, waits until it exists, hides it for a short time and unhides it.
43 |Run "notepad.exe" 44 | WinWait "Untitled - Notepad" 45 | Sleep 500 46 | WinHide ; Use the window found by WinWait. 47 | Sleep 1000 48 | WinShow ; Use the window found by WinWait.49 |
Temporarily hides the taskbar.
52 |WinHide "ahk_class Shell_TrayWnd" 53 | Sleep 1000 54 | WinShow "ahk_class Shell_TrayWnd"55 |
Forces the specified window to close.
16 | 17 |WinKill WinTitle, WinText, SecondsToWait, ExcludeTitle, ExcludeText18 |
Type: String, Integer or Object
24 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
25 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
26 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
27 |If omitted, the function will not wait at all. Otherwise, specify the number of seconds (can contain a decimal point) to wait for the window to close. If the window does not close within that period, the script will continue.
33 |A TargetError is thrown if the window could not be found, except if the group mode is used.
39 |No exception is thrown if a window is found but cannot be closed, so use WinExist or WinWaitClose if you need to determine for certain that a window has closed.
40 | 41 |This function first makes a brief attempt to close the window normally. If that fails, the function will attempt to force the window closed by terminating its process.
43 |If a matching window is active, that window will be closed in preference to any other matching window. In general, if more than one window matches, the topmost (most recently used) will be closed.
44 |This function operates only upon a single window except when WinTitle is ahk_group GroupName, in which case all windows in the group are affected.
45 |While the function is in a waiting state, new threads can be launched via hotkey, custom menu item, or timer.
46 | 47 |WinClose, WinWaitClose, ProcessClose, WinActivate, SetTitleMatchMode, DetectHiddenWindows, Last Found Window, WinExist, WinActive, WinWaitActive, WinWait, GroupActivate
49 |If Notepad does exist, force it to close, otherwise force the calculator to close.
52 |if WinExist("Untitled - Notepad") 53 | WinKill ; Use the window found by WinExist. 54 | else 55 | WinKill "Calculator"56 |
Enlarges the specified window to its maximum size.
16 | 17 |WinMaximize WinTitle, WinText, ExcludeTitle, ExcludeText18 |
Type: String, Integer or Object
24 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
25 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
26 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
27 |A TargetError is thrown if the window could not be found, except if the group mode is used.
33 | 34 |Use WinRestore to unmaximize a window or WinMinimize to minimize it.
36 |If a particular type of window does not respond correctly to WinMaximize, try using the following instead:
37 |PostMessage 0x0112, 0xF030,,, WinTitle, WinText ; 0x0112 = WM_SYSCOMMAND, 0xF030 = SC_MAXIMIZE38 |
This function operates only upon the topmost matching window except when WinTitle is ahk_group GroupName, in which case all windows in the group are affected.
39 | 40 |Opens Notepad, waits until it exists and maximizes it.
45 |Run "notepad.exe" 46 | WinWait "Untitled - Notepad" 47 | WinMaximize ; Use the window found by WinWait.48 |
Collapses the specified window into a button on the task bar.
16 | 17 |WinMinimize WinTitle, WinText, ExcludeTitle, ExcludeText18 |
Type: String, Integer or Object
24 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
25 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
26 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
27 |A TargetError is thrown if the window could not be found, except if the group mode is used.
33 | 34 |Use WinRestore to unminimize a window or WinMaximize to maximize it.
36 |WinMinimize minimizes the window using a direct method, bypassing the window message which is usually sent when the minimize button, window menu or taskbar is used to minimize the window. This prevents the window from overriding the action (such as to "minimize" to the taskbar by hiding the window), but may also prevent the window from responding correctly, such as to save the current focus for when the window is restored. It also prevents the "minimize" system sound from being played.
37 |If a particular type of window does not respond correctly to WinMinimize, try using the following instead:
38 |PostMessage 0x0112, 0xF020,,, WinTitle, WinText ; 0x0112 = WM_SYSCOMMAND, 0xF020 = SC_MINIMIZE39 |
This function operates only upon the topmost matching window except when WinTitle is ahk_group GroupName, in which case all windows in the group are affected.
40 | 41 |WinRestore, WinMaximize, WinMinimizeAll
43 |Opens Notepad, waits until it exists and minimizes it.
46 |Run "notepad.exe" 47 | WinWait "Untitled - Notepad" 48 | WinMinimize ; Use the window found by WinWait.49 |
Minimizes or unminimizes all windows.
16 | 17 |WinMinimizeAll 18 | WinMinimizeAllUndo19 |
On most systems, this is equivalent to Explorer's Win+M and Win+D hotkeys.
20 |Minimizes all windows for 1 second and unminimizes them.
25 |WinMinimizeAll 26 | Sleep 1000 27 | WinMinimizeAllUndo28 |
Changes the position and/or size of the specified window.
16 | 17 |WinMove X, Y, Width, Height, WinTitle, WinText, ExcludeTitle, ExcludeText18 |
Type: Integer
23 |If either is omitted, the position in that dimension will not be changed. Otherwise, specify the X and Y coordinates (in pixels) of the upper left corner of the target window's new location. The upper-left pixel of the screen is at 0, 0.
24 |Type: Integer
29 |If either is omitted, the size in that dimension will not be changed. Otherwise, specify the new width and height of the window (in pixels).
30 |Type: String, Integer or Object
35 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
36 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
37 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
38 |A TargetError is thrown if the window could not be found.
43 |An OSError is thrown if an internal function call reported failure. However, success may be reported even if the window has not moved, such as if the window restricts its own movement.
44 | 45 |If Width or Height is small (or negative), most windows with a title bar will generally go no smaller than 112 x 27 pixels (however, some types of windows may have a different minimum size). If Width or Height is large, most windows will go no larger than approximately 12 pixels beyond the dimensions of the desktop.
47 |Negative X and Y coordinates are allowed to support multi-monitor systems and to move a window entirely off-screen.
48 |Although WinMove cannot move minimized windows, it can move hidden windows if DetectHiddenWindows is on.
49 |The speed of WinMove is affected by SetWinDelay.
50 | 51 |On systems with multiple screens which have different DPI settings, the final position and size of the window may differ from the requested values due to OS DPI scaling.
52 | 53 |ControlMove, WinGetPos, WinHide, WinMinimize, WinMaximize, Win functions
55 | 56 |Opens the calculator, waits until it exists and moves it to the upper-left corner of the screen.
59 |Run "calc.exe" 60 | WinWait "Calculator" 61 | WinMove 0, 0 ; Use the window found by WinWait.62 |
Creates a fixed-size popup window that shows the contents of the clipboard, and moves it to the upper-left corner of the screen.
66 |MyGui := Gui("ToolWindow -Sysmenu Disabled", "The clipboard contains:") 67 | MyGui.Add("Text",, A_Clipboard) 68 | MyGui.Show("w400 h300") 69 | WinMove 0, 0,,, MyGui 70 | MsgBox "Press OK to dismiss the popup window" 71 | MyGui.Destroy()72 |
Centers a window on the screen.
76 |CenterWindow("ahk_class Notepad") 77 | 78 | CenterWindow(WinTitle) 79 | { 80 | WinGetPos ,, &Width, &Height, WinTitle 81 | WinMove (A_ScreenWidth/2)-(Width/2), (A_ScreenHeight/2)-(Height/2),,, WinTitle 82 | }83 |
Sends the specified window to the bottom of stack; that is, beneath all other windows.
17 | 18 |WinMoveBottom WinTitle, WinText, ExcludeTitle, ExcludeText19 | 20 |
Type: String, Integer or Object
25 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
26 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
27 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
28 |A TargetError is thrown if the window could not be found.
33 |An OSError may be thrown on failure.
34 | 35 |The effect is similar to pressing Alt+Esc.
37 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos.
38 | 39 |WinMoveTop, WinSetAlwaysOnTop, Win functions, Control functions
41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /docs/lib/WinMoveTop.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Brings the specified window to the top of the stack without explicitly activating it.
17 | 18 |WinMoveTop WinTitle, WinText, ExcludeTitle, ExcludeText19 | 20 |
Type: String, Integer or Object
25 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
26 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
27 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
28 |A TargetError is thrown if the window could not be found.
33 |An OSError may be thrown on failure.
34 | 35 |However, the system default settings will probably cause it to activate in most cases. In addition, this function may have no effect due to the operating system's protection against applications that try to steal focus from the user (it may depend on factors such as what type of window is currently active and what the user is currently doing). One possible work-around is to make the window briefly always-on-top, then turn off always-on-top.
37 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos.
38 | 39 |WinMoveBottom, WinSetAlwaysOnTop, Win functions, Control functions
41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /docs/lib/WinRedraw.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Redraws the specified window.
17 | 18 |WinRedraw WinTitle, WinText, ExcludeTitle, ExcludeText19 | 20 |
Type: String, Integer or Object
25 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
26 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
27 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
28 |A TargetError is thrown if the window could not be found.
33 | 34 |This function attempts to update the appearance/contents of a window by informing the OS that the window's rectangle needs to be redrawn. If this approach does not work for a particular window, try WinMove. If that does not work, try WinHide in combination with WinShow.
36 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos.
37 | 38 |WinMoveBottom, WinSetAlwaysOnTop, Win functions, Control functions
40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /docs/lib/WinRestore.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Unminimizes or unmaximizes the specified window if it is minimized or maximized.
16 | 17 |WinRestore WinTitle, WinText, ExcludeTitle, ExcludeText18 |
Type: String, Integer or Object
24 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
25 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
26 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
27 |A TargetError is thrown if the window could not be found, except if the group mode is used.
33 | 34 |If a particular type of window does not respond correctly to WinRestore, try using the following instead:
36 |PostMessage 0x0112, 0xF120,,, WinTitle, WinText ; 0x0112 = WM_SYSCOMMAND, 0xF120 = SC_RESTORE37 |
This function operates only upon the topmost matching window except when WinTitle is ahk_group GroupName, in which case all windows in the group are affected.
38 | 39 |Unminimizes or unmaximizes Notepad if it is minimized or maximized.
44 |WinRestore "Untitled - Notepad"45 |
Makes the specified window stay on top of all other windows (except other always-on-top windows).
17 | 18 |WinSetAlwaysOnTop NewSetting, WinTitle, WinText, ExcludeTitle, ExcludeText19 | 20 |
Type: Integer
25 |If omitted, it defaults to 1. Otherwise, specify one of the following values:
26 |1
or True
turns on the setting0
or False
turns off the setting-1
toggles the setting (sets it to the opposite of its current state)Type: String, Integer or Object
35 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
36 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
37 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
38 |A TargetError is thrown if the window could not be found.
43 |An OSError may be thrown on failure.
44 | 45 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos.
47 | 48 |WinMoveTop, WinMoveBottom, Win functions, Control functions
50 | 51 |Toggles the always-on-top status of the calculator.
54 |WinSetAlwaysOnTop -1, "Calculator"55 |
Enables or disables the specified window.
17 | 18 |WinSetEnabled NewSetting , WinTitle, WinText, ExcludeTitle, ExcludeText19 | 20 |
Type: Integer
25 |One of the following values:
26 |1
or True
turns on the setting0
or False
turns off the setting-1
toggles the setting (sets it to the opposite of its current state)Type: String, Integer or Object
35 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
36 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
37 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
38 |A TargetError is thrown if the window could not be found.
43 |An OSError is thrown if the change could not be applied.
44 | 45 |When a window is disabled, the user cannot move it or interact with its controls. In addition, disabled windows are omitted from the alt-tab list.
47 |WinGetStyle example #1 can be used to determine whether a window is disabled.
48 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos.
49 | 50 |ControlSetEnabled, Win functions, Control functions
52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /docs/lib/WinSetRegion.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Changes the shape of the specified window to be the specified rectangle, ellipse, or polygon.
17 | 18 |WinSetRegion Options, WinTitle, WinText, ExcludeTitle, ExcludeText19 | 20 |
Type: String
25 |If blank or omitted, the window is restored to its original/default display area. Otherwise, specify one or more of the following options, each separated from the others with space(s):
26 |Wn: Width of rectangle or ellipse. For example: w200
.
Hn: Height of rectangle or ellipse. For example: h200
.
X-Y: Each of these is a pair of X/Y coordinates. For example, 200-0
would use 200 for the X coordinate and 0 for the Y.
E: Makes the region an ellipse rather than a rectangle. This option is valid only when W and H are present.
30 |Rw-h: Makes the region a rectangle with rounded corners. For example, r30-30
would use a 30x30 ellipse for each corner. If w-h is omitted, 30-30 is used. R is valid only when W and H are present.
Rectangle or ellipse: If the W and H options are present, the new display area will be a rectangle whose upper left corner is specified by the first (and only) pair of X-Y coordinates. However, if the E option is also present, the new display area will be an ellipse rather than a rectangle. For example: WinSetRegion "50-0 w200 h250 E"
.
Polygon: When the W and H options are absent, the new display area will be a polygon determined by multiple pairs of X-Y coordinates (each pair of coordinates is a point inside the window relative to its upper left corner). For example, if three pairs of coordinates are specified, the new display area will be a triangle in most cases. The order of the coordinate pairs with respect to each other is sometimes important. In addition, the word Wind may be present in Options to use the winding method instead of the alternating method to determine the polygon's region.
33 |Type: String, Integer or Object
37 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
38 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
39 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
40 |A TargetError is thrown if the window could not be found.
45 |A ValueError is thrown if one or more Options are invalid, or if more than 2000 pairs of coordinates were specified.
46 |An OSError is thrown if the specified region is invalid or could not be applied to the target window.
47 | 48 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos.
50 |When a region is set for a window owned by the script, the system may automatically change the method it uses to render the window's frame, thereby altering its appearance. The effect is similar to workaround #2 shown below, but only affects the window until its region is reset.
51 |Known limitation: Setting a region for a window not owned by the script may produce unexpected results if the window has a caption (title bar), and the system has desktop composition enabled. This is because the visible frame is not actually part of the window, but rendered by a separate system process known as Desktop Window Manager (DWM). Note that desktop composition is always enabled on Windows 8 and later. One of the following two workarounds can be used:
52 |; #1: Remove the window's caption. 53 | WinSetStyle "-0xC00000", "Window Title" 54 | 55 | ; To undo it: 56 | WinSetStyle "+0xC00000", "Window Title"57 |
; #2: Disable DWM rendering of the window's frame. 58 | DllCall("dwmapi\DwmSetWindowAttribute", "ptr", WinExist("Window Title") 59 | , "uint", DWMWA_NCRENDERING_POLICY := 2, "int*", DWMNCRP_DISABLED := 1, "uint", 4) 60 | 61 | ; To undo it (this might also cause any set region to be ignored): 62 | DllCall("dwmapi\DwmSetWindowAttribute", "ptr", WinExist("Window Title") 63 | , "uint", DWMWA_NCRENDERING_POLICY := 2, "int*", DWMNCRP_ENABLED := 2, "uint", 4) 64 |65 | 66 | 67 |
Win functions, Control functions
69 | 70 |Makes all parts of Notepad outside this rectangle invisible. This example may not work well with the new Notepad on Windows 11 or later.
73 |WinSetRegion "50-0 w200 h250", "ahk_class Notepad"74 |
Same as above but with corners rounded to 40x40. This example may not work well with the new Notepad on Windows 11 or later.
78 |WinSetRegion "50-0 w200 h250 r40-40", "ahk_class Notepad"79 |
Creates an ellipse instead of a rectangle. This example may not work well with the new Notepad on Windows 11 or later.
83 |WinSetRegion "50-0 w200 h250 E", "ahk_class Notepad"84 |
Creates a triangle with apex pointing down. This example may not work well with the new Notepad on Windows 11 or later.
88 |WinSetRegion "50-0 250-0 150-250", "ahk_class Notepad"89 |
Restores the window to its original/default display area. This example may not work well with the new Notepad on Windows 11 or later.
93 |WinSetRegion , "ahk_class Notepad"94 |
Creates a see-through rectangular hole inside Notepad (or any other window). There are two rectangles specified below: an outer and an inner. Each rectangle consists of 5 pairs of X/Y coordinates because the first pair is repeated at the end to "close off" each rectangle. This example may not work well with the new Notepad on Windows 11 or later.
98 |WinSetRegion "0-0 300-0 300-300 0-300 0-0 100-100 200-100 200-200 100-200 100-100", "ahk_class Notepad"99 |
Changes the style or extended style of the specified window, respectively.
17 | 18 |WinSetStyle Value , WinTitle, WinText, ExcludeTitle, ExcludeText 19 | WinSetExStyle Value , WinTitle, WinText, ExcludeTitle, ExcludeText20 | 21 |
Pass a positive integer to completely overwrite the window's style; that is, to set it to Value.
27 |To easily add, remove or toggle styles, pass a numeric string prefixed with a plus sign (+), minus sign (-) or caret (^), respectively. The new style value is calculated as shown below (where CurrentStyle could be retrieved with WinGetStyle or WinGetExStyle):
28 |Operation | 31 |Prefix | 32 |Example | 33 |Formula | 34 |
---|---|---|---|
Add | 37 |+ | 38 |"+0x80" |
39 | NewStyle := CurrentStyle | Value |
40 |
Remove | 43 |- | 44 |"-0x80" |
45 | NewStyle := CurrentStyle & ~Value |
46 |
Toggle | 49 |^ | 50 |"^0x80" |
51 | NewStyle := CurrentStyle ^ Value |
52 |
If Value is a negative integer, it is treated the same as the corresponding numeric string.
55 |To use the + or ^ prefix literally in an expression, the prefix or value must be enclosed in quote marks. For example: WinSetStyle("+0x80")
or WinSetStyle("^" StylesToToggle)
. This is because the expression +123
produces 123 (without a prefix) and ^123
is a syntax error.
Type: String, Integer or Object
60 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
61 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
62 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
63 |A TargetError is thrown if the window could not be found.
68 |An OSError is thrown if the change could not be applied.
69 | 70 |See the styles table for a partial listing of styles.
72 |After applying certain style changes to a visible window, it might be necessary to redraw the window using WinRedraw.
73 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos.
74 | 75 |WinGetStyle / WinGetExStyle, ControlSetStyle / ControlSetExStyle, styles table, Win functions, Control functions
77 | 78 |Toggles the WS_EX_TOOLWINDOW attribute, which removes/adds Notepad from the alt-tab list.
86 |WinSetExStyle "^0x80", "ahk_class Notepad"87 |
Changes the title of the specified window.
16 | 17 |WinSetTitle NewTitle , WinTitle, WinText, ExcludeTitle, ExcludeText18 |
Type: String
24 |The new title for the window. If this is the only parameter given, the Last Found Window will be used.
25 |Type: String, Integer or Object
30 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
31 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
32 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
33 |A TargetError is thrown if the window could not be found.
39 |An OSError is thrown if the change could not be applied.
40 | 41 |A change to a window's title might be merely temporary if the application that owns the window frequently changes the title.
43 | 44 |WinMove, WinGetTitle, WinGetText, ControlGetText, WinGetPos, Win functions
46 |Changes the title of Notepad. This example may fail on Windows 11 or later, as it requires the classic version of Notepad.
49 |WinSetTitle("This is a new title", "Untitled - Notepad")50 |
Opens Notepad, waits until it is active and changes its title. This example may fail on Windows 11 or later, as it requires the classic version of Notepad.
54 |Run "notepad.exe" 55 | WinWaitActive "Untitled - Notepad" 56 | WinSetTitle "This is a new title" ; Use the window found by WinWaitActive.57 |
Opens the main window, waits until it is active and changes its title.
61 |ListVars 62 | WinWaitActive "ahk_class AutoHotkey" 63 | WinSetTitle "This is a new title" ; Use the window found by WinWaitActive.64 |
Makes all pixels of the chosen color invisible inside the specified window.
17 | 18 |WinSetTransColor Color , WinTitle, WinText, ExcludeTitle, ExcludeText19 | 20 |
Specify a color name or RGB value (see the color chart for guidance, or use PixelGetColor in its RGB mode). To additionally make the visible part of the window partially transparent, append a space (not a comma) followed by the transparency level (0-255). For example: WinSetTransColor "EEAA99 150"
.
If the value is a string, any numeric color value must be in hexadecimal format. The color value can be omitted; for example, WinSetTransColor " 150"
(with the leading space) is equivalent to WinSetTransparent 150
.
"Off"
(case-insensitive) or an empty string may be specified to completely turn off transparency for a window. This is functionally identical to WinSetTransparent "Off"
. Specifying Off is different than specifying 255 because it may improve performance and reduce usage of system resources (but probably only when desktop composition is disabled).
Type: String, Integer or Object
32 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
33 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
34 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
35 |A TargetError is thrown if the window could not be found.
40 |An OSError is thrown if the change could not be applied.
41 | 42 |This allows the contents of the window behind it to show through. If the user clicks on an invisible pixel, the click will "fall through" to the window behind it.
44 |To change a window's existing TransColor, it may be necessary to turn off transparency before making the change.
45 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos.
46 |This function is often used to create on-screen displays and other visual effects. There is an example of an on-screen display at the bottom of the Gui object page. For a simple demonstration via hotkeys, see WinSetTransparent example #4.
47 | 48 |WinSetTransparent, Win functions, Control functions
50 | 51 |Makes all white pixels in Notepad invisible. This example may not work well with the new Notepad on Windows 11 or later.
54 |WinSetTransColor "White", "Untitled - Notepad"55 |
Makes the specified window semi-transparent.
17 | 18 |WinSetTransparent N, WinTitle, WinText, ExcludeTitle, ExcludeText19 | 20 |
To enable transparency, specify a number between 0 and 255 indicating the degree of transparency: 0 makes the window invisible while 255 makes it opaque.
26 |"Off"
(case-insensitive) or an empty string may be specified to completely turn off transparency for a window. This is functionally identical to WinSetTransColor "Off"
. Specifying Off is different than specifying 255 because it may improve performance and reduce usage of system resources (but probably only when desktop composition is disabled).
Type: String, Integer or Object
31 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
32 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
33 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
34 |A TargetError is thrown if the window could not be found.
39 |An OSError is thrown if the change could not be applied.
40 | 41 |For example, to make the task bar transparent, use WinSetTransparent 150, "ahk_class Shell_TrayWnd"
. Similarly, to make the classic Start Menu transparent, see example #2. To make the Start Menu's submenus transparent, also include the script from example #3.
Setting the transparency level to 255 before using Off might avoid window redrawing problems such as a black background. If the window still fails to be redrawn correctly, see WinRedraw for a possible workaround.
44 |The ID of the window under the mouse cursor can be retrieved with MouseGetPos.
45 | 46 |WinSetTransColor, Win functions, Control functions
48 | 49 |Makes the classic Start Menu transparent (to additionally make the Start Menu's submenus transparent, see example #3).
57 |DetectHiddenWindows True 58 | WinSetTransparent 150, "ahk_class BaseBar"59 |
Makes all or selected menus transparent throughout the system as soon as they appear. Note that although such a script cannot make its own menus transparent, it can make those of other scripts transparent.
63 |SetTimer WatchForMenu, 5 64 | 65 | WatchForMenu() 66 | { 67 | DetectHiddenWindows True ; Might allow detection of menu sooner. 68 | if WinExist("ahk_class #32768") 69 | WinSetTransparent 150 ; Uses the window found by the above line. 70 | }71 |
Demonstrates the effects of WinSetTransparent and WinSetTransColor. Note: If you press one of the hotkeys while the mouse cursor is hovering over a pixel that is invisible as a result of TransColor, the window visible beneath that pixel will be acted upon instead!
75 |#t:: ; Press Win+T to make the color under the mouse cursor invisible. 76 | { 77 | MouseGetPos &MouseX, &MouseY, &MouseWin 78 | MouseRGB := PixelGetColor(MouseX, MouseY) 79 | ; It seems necessary to turn off any existing transparency first: 80 | WinSetTransColor "Off", MouseWin 81 | WinSetTransColor MouseRGB " 220", MouseWin 82 | } 83 | 84 | #o:: ; Press Win+O to turn off transparency for the window under the mouse. 85 | { 86 | MouseGetPos ,, &MouseWin 87 | WinSetTransColor "Off", MouseWin 88 | } 89 | 90 | #g:: ; Press Win+G to show the current settings of the window under the mouse. 91 | { 92 | MouseGetPos ,, &MouseWin 93 | TransDegree := WinGetTransparent(MouseWin) 94 | TransColor := WinGetTransColor(MouseWin) 95 | ToolTip "Translucency:`t" TransDegree "`nTransColor:`t" TransColor 96 | }97 |
Unhides the specified window.
16 | 17 |WinShow WinTitle, WinText, ExcludeTitle, ExcludeText18 |
Type: String, Integer or Object
24 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
25 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
26 |Window titles and text are case-sensitive. Hidden windows are always detected regardless of DetectHiddenWindows. By default, hidden text elements are detected unless changed with DetectHiddenText. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
27 |A TargetError is thrown if the window could not be found, except if the group mode is used.
33 | 34 |By default, WinShow is the only function that can always detect hidden windows. Other built-in functions can detect them only if DetectHiddenWindows has been turned on.
36 |This function operates only upon the topmost matching window except when WinTitle is ahk_group GroupName, in which case all windows in the group are affected.
37 |WinHide, SetTitleMatchMode, DetectHiddenWindows, Last Found Window
39 |Opens Notepad, waits until it exists, hides it for a short time and unhides it.
42 |Run "notepad.exe" 43 | WinWait "Untitled - Notepad" 44 | Sleep 500 45 | WinHide ; Use the window found by WinWait. 46 | Sleep 1000 47 | WinShow ; Use the window found by WinWait.48 |
Waits until the specified window exists.
16 | 17 |HWND := WinWait(WinTitle, WinText, Timeout, ExcludeTitle, ExcludeText)18 |
Type: String, Integer or Object
24 |At least one of these is required. Specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
25 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
26 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
27 |If omitted, the function will wait indefinitely. Otherwise, it will wait no longer than this many seconds. To wait for a fraction of a second, specify a floating-point number, for example, 0.25 to wait for a maximum of 250 milliseconds.
33 |Type: Integer
39 |This function returns the HWND (unique ID) of a matching window if one was found, or 0 if the function timed out.
40 | 41 |If a matching window comes into existence, the function will not wait for Timeout to expire. Instead, it will update the Last Found Window and return, allowing the script to continue execution.
43 |If WinTitle specifies a pure HWND (as an Integer or an Object with a HWND property), hidden windows are detected only when using DetectHiddenWindows. This only applies to WinWait and WinWaitClose; for other windowing functions, specifying a pure HWND causes hidden windows to be detected regardless of DetectHiddenWindows.
44 |If WinTitle specifies an invalid pure HWND, the function returns immediately, without waiting for Timeout to expire. Waiting for another window to be created with the same HWND value would not be meaningful, as there would likely be no relation between the two windows.
45 |While the function is in a waiting state, new threads can be launched via hotkey, custom menu item, or timer.
46 |If another thread changes the contents of any variable(s) that were used for this function's parameters, the function will not see the change -- it will continue to use the title and text that were originally present in the variables when the function first started waiting.
47 |Unlike WinWaitActive, the Last Found Window cannot be used. Therefore, at least one of the window parameters (WinTitle, WinText, ExcludeTitle, ExcludeText) must be non-blank.
48 | 49 |WinWaitActive, WinWaitClose, WinExist, WinActive, ProcessWait, SetTitleMatchMode, DetectHiddenWindows
51 |Opens Notepad and waits a maximum of 3 seconds until it exists. If WinWait times out, an error message is shown, otherwise Notepad is minimized.
54 |Run "notepad.exe" 55 | if WinWait("Untitled - Notepad", , 3) 56 | WinMinimize ; Use the window found by WinWait. 57 | else 58 | MsgBox "WinWait timed out." 59 |60 |
Waits until the specified window is active or not active.
16 | 17 |HWND := WinWaitActive(WinTitle, WinText, Timeout, ExcludeTitle, ExcludeText) 18 | Boolean := WinWaitNotActive(WinTitle, WinText, Timeout, ExcludeTitle, ExcludeText)19 |
Type: String, Integer or Object
25 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
26 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
27 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText; however, when using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
28 |If omitted, the function will wait indefinitely. Otherwise, it will wait no longer than this many seconds. To wait for a fraction of a second, specify a floating-point number, for example, 0.25 to wait for a maximum of 250 milliseconds.
34 |Type: Integer or Integer (boolean)
40 |WinWaitActive returns the HWND (unique ID) of the active window if it matches the criteria, or 0 if the function timed out.
41 |WinWaitNotActive returns 1 (true) if the active window does not match the criteria, or 0 (false) if the function timed out.
42 | 43 |If the active window satisfies the function's expectation, the function will not wait for Timeout to expire. Instead, it will immediately return, allowing the script to resume.
45 |Since "A"
matches whichever window is active at any given moment, WinWaitNotActive "A"
typically waits indefinitely. To instead wait for a different window to become active, specify its unique ID as in the following example:
WinWaitNotActive WinExist("A")47 |
Both WinWaitActive and WinWaitNotActive will update the Last Found Window if a matching window is active when the function begins or becomes active while the function is waiting.
48 |While the function is in a waiting state, new threads can be launched via hotkey, custom menu item, or timer.
49 |If another thread changes the contents of any variable(s) that were used for this function's parameters, the function will not see the change -- it will continue to use the title and text that were originally present in the variables when the function first started waiting.
50 | 51 |WinWait, WinWaitClose, WinExist, WinActive, SetTitleMatchMode, DetectHiddenWindows
53 |Opens Notepad and waits a maximum of 2 seconds until it is active. If WinWait times out, an error message is shown, otherwise Notepad is minimized.
56 |Run "notepad.exe" 57 | if WinWaitActive("Untitled - Notepad", , 2) 58 | WinMinimize ; Use the window found by WinWaitActive. 59 | else 60 | MsgBox "WinWaitActive timed out." 61 |62 |
Waits until no matching windows can be found.
16 | 17 |Boolean := WinWaitClose(WinTitle, WinText, Timeout, ExcludeTitle, ExcludeText)18 |
Type: String, Integer or Object
24 |If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).
25 |ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.
26 |Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText. By default, a window title can contain WinTitle or ExcludeTitle anywhere inside it to be a match, unless changed with SetTitleMatchMode.
27 |If omitted, the function will wait indefinitely. Otherwise, it will wait no longer than this many seconds. To wait for a fraction of a second, specify a floating-point number, for example, 0.25 to wait for a maximum of 250 milliseconds.
33 |Type: Integer (boolean)
39 |This function returns 0 (false) if the function timed out or 1 (true) otherwise.
40 | 41 |Whenever no matching windows exist, the function will not wait for Timeout to expire. Instead, it will immediately return 1 and the script will continue executing. Conversely, the function may continue waiting even after a matching window is closed, until no more matching windows can be found.
43 |If WinTitle specifies a pure HWND (as an Integer or an Object with a HWND property), hidden windows are detected only when using DetectHiddenWindows. This only applies to WinWait and WinWaitClose; for other windowing functions, specifying a pure HWND causes hidden windows to be detected regardless of DetectHiddenWindows.
44 |Since "A"
matches whichever window is active at any given moment, WinWaitClose "A"
typically waits indefinitely. To instead wait for the current active window to close, specify its title or unique ID as in the following example:
WinWaitClose WinExist("A")46 |
WinWaitClose updates the Last Found Window whenever it finds a matching window. One use for this is to identify or operate on the window after the function times out. For example:
47 |48 | Gui("", "Test window " Random()).Show("w300 h50") ; Show a test window. 49 | if !WinWaitClose("Test",, 5) ; Wait 5 seconds for someone to close it. 50 | { 51 | MsgBox "Window not yet closed: " WinGetTitle() 52 | WinClose ; Close the window found by WinWaitClose. 53 | } 54 |55 |
While the function is in a waiting state, new threads can be launched via hotkey, custom menu item, or timer.
56 |If another thread changes the contents of any variable(s) that were used for this function's parameters, the function will not see the change -- it will continue to use the title and text that were originally present in the variables when the function first started waiting.
57 | 58 |WinClose, WinWait, WinWaitActive, WinExist, WinActive, ProcessWaitClose, SetTitleMatchMode, DetectHiddenWindows
60 |Opens Notepad, waits until it exists and then waits until it is closed.
63 |Run "notepad.exe" 64 | WinWait "Untitled - Notepad" 65 | WinWaitClose ; Use the window found by WinWait. 66 | MsgBox "Notepad is now closed."67 |
Changes how long the script keeps trying to access the clipboard when the first attempt fails.
16 | 17 |#ClipboardTimeout Milliseconds
18 | Type: Integer
24 |The length of the interval in milliseconds. Specify -1 to have it keep trying indefinitely. Specify 0 to have it try only once.
25 |If this directive is unspecified in the script, it will behave as though set to 1000 (milliseconds).
30 |Some applications keep the clipboard open for long periods of time, perhaps to write or read large amounts of data. In such cases, increasing this setting causes the script to wait longer before giving up and displaying an error message.
31 |This settings applies to all clipboard operations, the simplest of which are the following examples: Var := A_Clipboard
and A_Clipboard := "New Text"
.
Whenever the script is waiting for the clipboard to become available, new threads cannot be launched and timers will not run. However, if the user presses a hotkey, selects a custom menu item, or performs a GUI action such as pressing a button, that event will be buffered until later; in other words, its subroutine will be performed after the clipboard finally becomes available.
33 |This directive does not cause the reading of clipboard data to be reattempted if the first attempt fails.
34 |Like other directives, #ClipboardTimeout cannot be executed conditionally.
35 |Causes the script to wait 2 seconds instead of 1 second before giving up accessing the clipboard and displaying an error message.
40 |#ClipboardTimeout 200041 |
Loads a DLL or EXE file before the script starts executing.
17 | 18 |#DllLoad FileOrDirName19 |
Type: String
25 |The path of a file or directory as explained below. This must not contain double quotes (except for an optional pair of double quotes surrounding the parameter), wildcards (*
and ?
) or escape sequences other than semicolon (`;
).
Built-in variables may be used by enclosing them in percent signs (for example, #DllLoad "%A_ScriptDir%"
). Percent signs which are not part of a valid variable reference are interpreted literally. All built-in variables are valid, except for A_Args and built-in classes.
Known limitation: When compiling a script, variables are evaluated by the compiler and may differ from what the script would return when it is finally executed. The following variables are supported: A_AhkPath, A_AppData, A_AppDataCommon, A_ComputerName, A_ComSpec, A_Desktop, A_DesktopCommon, A_IsCompiled, A_LineFile, A_MyDocuments, A_ProgramFiles, A_Programs, A_ProgramsCommon, A_ScriptDir, A_ScriptFullPath, A_ScriptName, A_Space, A_StartMenu, A_StartMenuCommon, A_Startup, A_StartupCommon, A_Tab, A_Temp, A_UserName, A_WinDir.
28 |File: The absolute or relative path to the DLL or EXE file to be loaded. If a relative path is specified, the directive searches for the file using the same search strategy as the system's function LoadLibraryW. Note: SetWorkingDir has no effect on #DllLoad because #DllLoad is processed before the script begins executing.
29 |Directory: Specify a directory instead of a file to alter the search strategy by all subsequent occurrences of #DllLoad which do not specify an absolute path to a DLL or EXE. The new search strategy is the same as if Directory was passed to the system's function SetDllDirectoryW. If this parameter is omitted, the default search strategy is restored.
30 |Note: This parameter is not an expression, but can be enclosed in quote marks (either 'single' or "double").
31 |Once a DLL or EXE has been loaded by this directive it cannot be unloaded by calling the system's function FreeLibrary. When the script is terminated, all loaded files are unloaded automatically.
35 |The file path may optionally be preceded by *i
and a single space, which causes the program to ignore any failure to load the file. This option should be used only if the script is capable of executing despite the failure, such as if the DLL or EXE is non-essential, or if the script is designed to detect the failure. For example:
#DllLoad "*i MyDLL" 37 | if !DllCall("GetModuleHandle", "str", "MyDLL") 38 | MsgBox "Failed to load MyDLL!"39 |
If the FileOrDirName parameter specifies a DLL name without a path and the file name extension is omitted, .dll is appended to the file name. To prevent this, include a trailing period (.) in the file name.
40 |Like other directives, #DllLoad cannot be executed conditionally.
41 |Loads a DLL file located in the current user's "My Documents" folder before the script starts executing.
46 |#DllLoad "%A_MyDocuments%\MyDLL.dll"47 |
Sends any syntax error that prevents a script from launching to the standard error stream (stderr) rather than displaying a dialog.
16 | 17 |#ErrorStdOut Encoding18 | 19 |
Type: String
24 |If omitted, it defaults to CP0 (the system default ANSI code page). Otherwise, specify an encoding string indicating how to encode the output. For example, #ErrorStdOut "UTF-8"
encodes error messages as UTF-8 before sending them to stderr. Whatever program is capturing the output must support UTF-8, and in some cases may need to be configured to expect it.
Note: This parameter is not an expression, but can be enclosed in quote marks (either 'single' or "double").
26 |If this directive is unspecified in the script, any syntax error is displayed in a dialog.
31 |Errors are written to stderr instead of stdout. The command prompt and fancy editors usually display both.
32 |This allows fancy editors such as TextPad, SciTE, Crimson, and EditPlus to jump to the offending line when a syntax error occurs. Since the #ErrorStdOut directive would have to be added to every script, it is usually better to set up your editor to use the command line switch /ErrorStdOut when launching any AutoHotkey script (see further below for setup instructions).
33 |Because AutoHotkey is not a console program, errors will not appear at the command prompt directly. This can be worked around by 1) compiling the script with the Ahk2Exe ConsoleApp directive, or 2) capturing the script's output via piping or redirection. For example:
34 |"C:\Program Files\AutoHotkey\AutoHotkey.exe" /ErrorStdOut "My Script.ahk" 2>&1 |more 35 | "C:\Program Files\AutoHotkey\AutoHotkey.exe" /ErrorStdOut "My Script.ahk" 2>"Syntax-Error Log.txt"36 |
You can also pipe the output directly to the clipboard by using the operating system's built-in clip command. For example:
37 |"C:\Program Files\AutoHotkey\AutoHotkey.exe" /ErrorStdOut "My Script.ahk" 2>&1 |clip38 |
Note: 2>&1
causes stderr to be redirected to stdout, while 2>Filename
redirects only stderr to a file.
Like other directives, #ErrorStdOut cannot be executed conditionally.
40 | 41 |EditPlus:
43 |C:\Program Files\AutoHotkey\AutoHotkey.exe
/ErrorStdOut "$(FilePath)"
$(FileDir)
TextPad:
53 |C:\Windows\System32\cmd.exe
-- then press OK.cmd.exe
(or the full path to it)/c ""C:\Program Files\AutoHotkey\AutoHotkey.exe" /ErrorStdOut "$File""
$FileDir
FileAppend (because it can also send text to stderr or stdout)
70 |Sends any syntax error that prevents the script from launching to stderr rather than displaying a dialog.
73 |#ErrorStdOut74 |
Creates context-sensitive hotkeys and hotstrings. They perform a different action (or none at all) depending on any condition (an expression).
18 | 19 |#HotIf Expression20 |
Type: Boolean
26 |If omitted, subsequently-created hotkeys and hotstrings are not context-sensitive. Otherwise, specify any valid expression. This becomes the return value of an implicit function which has one parameter (ThisHotkey). The function cannot modify global variables directly (as it is assume-local as usual, and cannot contain declarations), but can call other functions which do.
27 |The #HotIf directive sets the expression which will be used by subsequently created hotkeys and hotstrings to determine whether they should activate. This expression is evaluated when the hotkey's key, mouse button or combination is pressed, when the hotstring's abbreviation is typed, or at other times when the program needs to know whether the hotkey or hotstring is active.
33 |To make context-sensitive hotkeys and hotstrings, simply precede them with the #HotIf directive. For example:
34 |#HotIf WinActive("ahk_class Notepad") or WinActive(MyWindowTitle) 35 | #Space::MsgBox "You pressed Win+Spacebar in Notepad or " MyWindowTitle 36 | :X:btw::MsgBox "You typed btw in Notepad or " MyWindowTitle37 |
The #HotIf directive is positional: it affects all hotkeys and hotstrings physically beneath it in the script, until the next #HotIf directive.
38 |Note: Unlike if statements, braces have no effect with the #HotIf directive.
39 |The #HotIf directive only affects hotkeys and hotstrings created via the double-colon syntax, such as ^!c::
or ::btw::
. For hotkeys and hotstrings created via the Hotkey or Hotstring function, use the HotIf function.
To turn off context sensitivity, specify #HotIf without any expression. For example:
41 |#HotIf42 |
Like other directives, #HotIf cannot be executed conditionally.
43 |When a mouse or keyboard hotkey is disabled via #HotIf, it performs its native function; that is, it passes through to the active window as though there is no such hotkey. There is one exception: Controller hotkeys: although #HotIf works, it never prevents other programs from seeing the press of a button.
44 |#HotIf can also be used to alter the behavior of an ordinary key like Enter or Space. This is useful when a particular window ignores that key or performs some action you find undesirable. For example:
45 |#HotIf WinActive("Reminders ahk_class #32770") ; The "reminders" window in Outlook. 46 | Enter::Send "!o" ; Have an "Enter" keystroke open the selected reminder rather than snoozing it. 47 | #HotIf48 | 49 |
A particular hotkey or hotstring can be defined more than once in the script if each definition has different HotIf criteria. These are known as hotkey variants or hotstring variants. For example:
51 |#HotIf WinActive("ahk_class Notepad") 52 | ^!c::MsgBox "You pressed Control+Alt+C in Notepad." 53 | #HotIf WinActive("ahk_class WordPadClass") 54 | ^!c::MsgBox "You pressed Control+Alt+C in WordPad." 55 | #HotIf 56 | ^!c::MsgBox "You pressed Control+Alt+C in a window other than Notepad/WordPad."57 |
If more than one variant is eligible to fire, only the one closest to the top of the script will fire. The exception to this is the global variant (the one with no HotIf criteria): It always has the lowest precedence; therefore, it will fire only if no other variant is eligible (this exception does not apply to hotstrings).
58 |When creating duplicate hotkeys, the order of modifier symbols such as ^!+#
does not matter. For example, ^!c
is the same as !^c
. However, keys must be spelled consistently. For example, Esc is not the same as Escape for this purpose (though the case does not matter). Also, any hotkey with a wildcard prefix (*) is entirely separate from a non-wildcard one; for example, *F1
and F1
would each have their own set of variants.
A window group can be used to make a hotkey or hotstring execute for a group of windows. For example:
61 |62 | GroupAdd "MyGroup", "ahk_class Notepad" 63 | GroupAdd "MyGroup", "ahk_class WordPadClass" 64 | 65 | #HotIf WinActive("ahk_group MyGroup") 66 | #z::MsgBox "You pressed Win+Z in either Notepad or WordPad." 67 |68 |
To create hotkey or hotstring variants dynamically (while the script is running), see HotIf.
69 | 70 |When the hotkey's key, mouse or controller button combination is pressed or the hotstring's abbreviation is typed, the #HotIf expression is evaluated to determine if the hotkey or hotstring should activate.
72 |Note: Scripts should not assume that the expression is only evaluated when the hotkey's key is pressed (see below).
73 |The expression may also be evaluated whenever the program needs to know whether the hotkey is active. For example, the #HotIf expression for a custom combination like a & b::
might be evaluated when the prefix key (a
in this example) is pressed, to determine whether it should act as a custom modifier key.
Note: Use of #HotIf in an unresponsive script may cause input lag or break hotkeys and hotstrings (see below).
75 |There are several more caveats to the #HotIf directive:
76 |ThisHotkey, A_ThisHotkey and A_TimeSinceThisHotkey are set based on the hotkey or non-auto-replace hotstring for which the current #HotIf expression is being evaluated.
83 |A_PriorHotkey and A_TimeSincePriorHotkey temporarily contain the previous values of the corresponding "This" variables.
84 | 85 |#HotIf is optimized to avoid expression evaluation for simple calls to WinActive or WinExist, thereby reducing the risk of lag or other issues in such cases. Specifically:
87 |not
or !
, but no other operators may be used.If the expression meets these criteria, it is evaluated directly by the program and does not appear in ListLines.
94 |Before the Hotkey or Hotstring function is used to modify an existing hotkey or hotstring variant, typically the HotIf function must be used with the original expression text. However, the first unique expression with a given combination of criteria can also be referenced by that criteria. For example:
95 |96 | HotIfWinExist "ahk_class Notepad" 97 | Hotkey "#n", "Off" ; Turn the hotkey off. 98 | HotIf 'WinExist("ahk_class Notepad")' 99 | Hotkey "#n", "On" ; Turn the same hotkey back on. 100 | 101 | #HotIf WinExist("ahk_class Notepad") 102 | #n::WinActivate 103 |104 |
Note that any use of variables will disqualify the expression. If the variable's value never changes after the hotkey or hotstring is created, there are two strategies for minimizing the risk of lag or other issues inherent to #HotIf:
105 |HotIfWin...(MyTitleVar)
to set the criteria and Hotkey(KeyName, Action)
or Hotstring(String, Replacement)
to create the hotkey or hotstring variant.#HotIf WinActive("ahk_group MyGroup")
and define the window group with GroupAdd "MyGroup", MyTitleVar
elsewhere in the script.#HotIf also restores prefix keys to their native function when appropriate (a prefix key is A in a hotkey such as a & b
). This occurs whenever there are no enabled hotkeys for a given prefix.
When a hotkey is currently disabled via #HotIf, its key or mouse button will appear with a "#" character in KeyHistory's "Type" column. This can help debug a script.
113 |Alt-tab hotkeys are not affected by #HotIf: they are in effect for all windows.
114 |The Last Found Window can be set by #HotIf. For example:
115 |#HotIf WinExist("ahk_class Notepad") 116 | #n::WinActivate ; Activates the window found by WinExist().117 | 118 |
#HotIfTimeout may be used to override the default timeout value.
120 |Hotkey function, Hotkeys, Hotstring function, Hotstrings, Suspend, WinActive, WinExist, SetTitleMatchMode, DetectHiddenWindows
121 | 122 |Creates two hotkeys and one hotstring which only work when Notepad is active, and one hotkey which works for any window except Notepad.
125 |#HotIf WinActive("ahk_class Notepad") 126 | ^!a::MsgBox "You pressed Ctrl-Alt-A while Notepad is active." 127 | #c::MsgBox "You pressed Win-C while Notepad is active." 128 | ::btw::This replacement text for "btw" will occur only in Notepad. 129 | #HotIf 130 | #c::MsgBox "You pressed Win-C in a window other than Notepad."131 |
Allows the volume to be adjusted by scrolling the mouse wheel over the taskbar.
135 |136 | #HotIf MouseIsOver("ahk_class Shell_TrayWnd") 137 | WheelUp::Send "{Volume_Up}" 138 | WheelDown::Send "{Volume_Down}" 139 | 140 | MouseIsOver(WinTitle) { 141 | MouseGetPos ,, &Win 142 | return WinExist(WinTitle " ahk_id " Win) 143 | } 144 |145 |
Simple word-delete shortcuts for all Edit controls.
149 |150 | #HotIf ActiveControlIsOfClass("Edit") 151 | ^BS::Send "^+{Left}{Del}" 152 | ^Del::Send "^+{Right}{Del}" 153 | 154 | ActiveControlIsOfClass(Cls) { 155 | FocusedControl := 0 156 | try FocusedControl := ControlGetFocus("A") 157 | FocusedControlClass := "" 158 | try FocusedControlClass := WinGetClass(FocusedControl) 159 | return (FocusedControlClass=Cls) 160 | } 161 |162 |
Dynamic Hotkeys. This example should be combined with example #2 before running it.
174 |175 | NumpadAdd:: 176 | { 177 | static toggle := false 178 | HotIf 'MouseIsOver("ahk_class Shell_TrayWnd")' 179 | if (toggle := !toggle) 180 | Hotkey "WheelUp", DoubleUp 181 | else 182 | Hotkey "WheelUp", "WheelUp" 183 | return 184 | ; Nested function: 185 | DoubleUp(ThisHotkey) => Send("{Volume_Up 2}") 186 | } 187 |188 |
Sets the maximum time that may be spent evaluating a single #HotIf expression.
18 | 19 |#HotIfTimeout Timeout
20 | Type: Integer
26 |The timeout value to apply globally, in milliseconds.
27 |If this directive is unspecified in the script, it will behave as though set to 1000 (milliseconds).
33 |A timeout is implemented to prevent long-running expressions from stalling keyboard input processing. If the timeout value is exceeded, the expression continues to evaluate, but the keyboard hook continues as if the expression had already returned false.
34 |Note that the system implements its own timeout, defined by the DWORD value LowLevelHooksTimeout in the following registry key:
35 |HKEY_CURRENT_USER\Control Panel\Desktop
36 |If the system timeout value is exceeded, the system may stop calling the script's keyboard hook, thereby preventing hook hotkeys from working until the hook is re-registered or the script is reloaded. The hook can usually be re-registered by suspending and un-suspending all hotkeys.
37 |Microsoft's documentation is unclear about the details of this timeout, but research indicates the following for Windows 7 and later: If LowLevelHooksTimeout is not defined, the default timeout is 300 ms. The hook may time out up to 10 times, but is silently removed if it times out an 11th time.
38 |If a given hotkey has multiple #HotIf variants, the timeout might be applied to each variant independently, making it more likely that the system timeout will be exceeded. This may be changed in a future update.
39 |Like other directives, #HotIfTimeout cannot be executed conditionally.
40 |Changes hotstring options or ending characters.
16 | 17 |#Hotstring NoMouse 18 | #Hotstring EndChars NewChars 19 | #Hotstring NewOptions20 |
Type: String
26 |Prevents mouse clicks from resetting the hotstring recognizer as described here. As a side-effect, this also prevents the mouse hook from being required by hotstrings (though it will still be installed if the script requires it for other purposes, such as mouse hotkeys). The presence of #Hotstring NoMouse
anywhere in the script affects all hotstrings, not just those physically beneath it.
Type: String
32 |Specify the word EndChars followed by a single space and then the new ending characters. For example:
33 |#Hotstring EndChars -()[]{}':;"/\,.?!`n`s`t34 |
Since the new ending characters are in effect globally for the entire script -- regardless of where the EndChars directive appears -- there is no need to specify EndChars more than once.
35 |The maximum number of ending characters is 100. Characters beyond this length are ignored.
36 |To make tab or space an ending character, include `t or `s in the list.
37 |Type: String
42 |Specify new options as described in Hotstring Options. For example: #Hotstring r s k0 c0
.
Unlike EndChars above, the #Hotstring directive is positional when used this way. In other words, entire sections of hotstrings can have different default options as in this example:
44 |::btw::by the way 45 | 46 | #Hotstring r c ; All the below hotstrings will use "send raw" and will be case-sensitive by default. 47 | ::al::airline 48 | ::CEO::Chief Executive Officer 49 | 50 | #Hotstring c0 ; Make all hotstrings below this point case-insensitive.51 |
Like other directives, #Hotstring cannot be executed conditionally.
57 | 58 |The Hotstring function can be used to change hotstring options while the script is running.
61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /docs/lib/_Include.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Causes the script to behave as though the specified file's contents are present at this exact position.
16 | 17 |#Include FileOrDirName 18 | #Include <LibName> 19 | #IncludeAgain FileOrDirName20 |
Type: String
26 |The path of a file or directory as explained below. This must not contain double quotes (except for an optional pair of double quotes surrounding the parameter), wildcards (*
and ?
) or escape sequences other than semicolon (`;
).
Built-in variables may be used by enclosing them in percent signs (for example, #Include "%A_ScriptDir%"
). Percent signs which are not part of a valid variable reference are interpreted literally. All built-in variables containing strings or numbers are valid.
Known limitation: When compiling a script, variables are evaluated by the compiler and may differ from what the script would return when it is finally executed. The following variables are supported: A_AhkPath, A_AppData, A_AppDataCommon, A_ComputerName, A_ComSpec, A_Desktop, A_DesktopCommon, A_IsCompiled, A_LineFile, A_MyDocuments, A_ProgramFiles, A_Programs, A_ProgramsCommon, A_ScriptDir, A_ScriptFullPath, A_ScriptName, A_Space, A_StartMenu, A_StartMenuCommon, A_Startup, A_StartupCommon, A_Tab, A_Temp, A_UserName, A_WinDir.
29 |File: The name of the file to be included. By default, relative paths are relative to the directory of the file which contains the #Include directive. This default can be overridden by using #Include Dir
as described below. Note: SetWorkingDir has no effect on #Include because #Include is processed before the script begins executing.
Directory: Specify a directory instead of a file to change the working directory used by all subsequent occurrences of #Include and FileInstall in the current file. Note: Changing the working directory in this way does not affect the script's initial working directory when it starts running (A_WorkingDir). To change that, use SetWorkingDir at the top of the script.
31 |Note: This parameter is not an expression, but can be enclosed in quote marks (either 'single' or "double").
32 |Type: String
37 |A library file or function name. For example, #Include <lib>
and #Include <lib_func>
would both include lib.ahk from one of the Lib folders. Variable references are not allowed.
A subdirectory can be specified, with the caveat that the first underscore may be interpreted as a delimiter as described under Script Library Folders, e.g. #Include <a_b\c>
will try a.ahk if a_b\c.ahk is not found.
A script behaves as though the included file's contents are physically present at the exact position of the #Include directive (as though a copy-and-paste were done from the included file). Consequently, it generally cannot merge two isolated scripts together into one functioning script.
44 |#Include ensures that the specified file is included only once, even if multiple inclusions are encountered for it. By contrast, #IncludeAgain allows multiple inclusions of the same file, while being the same as #Include in all other respects.
45 |The file path may optionally be preceded by *i
and a single space, which causes the program to ignore any failure to read the file. For example: #Include "*i SpecialOptions.ahk"
. This option should be used only when the file's contents are not essential to the main script's operation.
Lines displayed in the main window via ListLines or the menu View->Lines are always numbered according to their physical order within their own files. In other words, including a new file will change the line numbering of the main script file by only one line, namely that of the #Include line itself (except for compiled scripts, which merge their included files into one big script at the time of compilation).
47 |#Include is often used to load functions defined in an external file.
48 |Like other directives, #Include cannot be executed conditionally. In other words, this example would not work as expected:
49 |if (x = 1) 50 | #Include "SomeFile.ahk" ; This line takes effect regardless of the value of x.51 | 52 |
Script Library Folders, Functions, FileInstall
54 |Includes the contents of the specified file into the current script.
57 |#Include "C:\My Documents\Scripts\Utility Subroutines.ahk"58 |
Changes the working directory for subsequent #Includes and FileInstalls.
62 |#Include "%A_ScriptDir%"63 |
Controls which artificial keyboard and mouse events are ignored by hotkeys and hotstrings.
15 |#InputLevel Level16 | 17 |
Type: Integer
23 |If omitted, it defaults to 0. Otherwise, specify an integer between 0 and 100.
24 |If this directive is unspecified in the script, it will behave as though set to 0.
30 |For an explanation of how SendLevel and #InputLevel are used, see SendLevel.
31 |This directive is positional: it affects all hotkeys and hotstrings between it and the next #InputLevel directive. If not specified by an #InputLevel directive, hotkeys and hotstrings default to level 0.
32 |A hotkey's input level can also be set using the Hotkey function. For example: Hotkey "#z", my_hotkey_sub, "I1"
The input level of a hotkey or non-auto-replace hotstring is also used as the default send level for any keystrokes or button clicks generated by that hotkey or hotstring. Since a keyboard or mouse remapping is actually a pair of hotkeys, this allows #InputLevel to be used to allow remappings to trigger other hotkeys.
34 |AutoHotkey versions older than v1.1.06 behave as though #InputLevel 0
and SendLevel 0
are in effect.
Like other directives, #InputLevel cannot be executed conditionally.
36 | 37 |SendLevel, Hotkeys, Hotstrings
39 | 40 | Causes the first hotkey *Numpad0::
to trigger the second hotkey ~LButton::
. This would be not the case if the #InputLevel directives are omitted or commented out.
44 | #InputLevel 1 45 | ; Use SendEvent so that the script's own hotkeys can be triggered. 46 | *Numpad0::SendEvent "{Blind}{Click Down}" 47 | *Numpad0 up::SendEvent "{Blind}{Click Up}" 48 | #InputLevel 0 49 | ; This hotkey can be triggered by both Numpad0 and LButton: 50 | ~LButton::MsgBox "Clicked" 51 |52 |
Sets the maximum number of simultaneous threads.
16 | 17 |#MaxThreads Value
18 | Type: Integer
24 |The maximum total number of threads that can exist simultaneously. Specifying a number higher than 255 is the same as specifying 255.
25 |If this directive is unspecified in the script, it will behave as though set to 10.
30 |This setting is global, meaning that it needs to be specified only once (anywhere in the script) to affect the behavior of the entire script.
31 |Although a value of 1 is allowed, it is not recommended because it would prevent new hotkeys from launching whenever the script is displaying a message box or other dialog. It would also prevent timers from running whenever another thread is sleeping or waiting.
32 |The OnExit callback function will always launch regardless of how many threads exist.
33 |If this setting is lower than #MaxThreadsPerHotkey, it effectively overrides that setting.
34 |Like other directives, #MaxThreads cannot be executed conditionally.
35 |#MaxThreadsPerHotkey, Threads, A_MaxHotkeysPerInterval, ListHotkeys
37 |Causes some or all hotkeys to buffer rather than ignore keypresses when their #MaxThreadsPerHotkey limit has been reached.
16 | 17 |#MaxThreadsBuffer Setting18 |
If omitted, it defaults to True. Otherwise, specify one of the following literal values:
25 |True or 1: All hotkey subroutines between here and the next #MaxThreadsBuffer False
directive will buffer rather than ignore presses of their hotkeys whenever their subroutines are at their #MaxThreadsPerHotkey limit.
False or 0: A hotkey press will be ignored whenever that hotkey is already running its maximum number of threads (usually 1, but this can be changed with #MaxThreadsPerHotkey).
27 |If this directive is unspecified in the script, it will behave as though set to False.
33 |This directive is rarely used because this type of buffering usually does more harm than good. For example, if you accidentally press a hotkey twice, having this setting ON would cause that hotkey's subroutine to automatically run a second time if its first thread takes less than 1 second to finish (this type of buffer expires after 1 second, by design). Note that AutoHotkey buffers hotkeys in several other ways (such as Thread Interrupt and Critical). It's just that this particular way can be detrimental, thus it is OFF by default.
34 |The main use for this directive is to increase the responsiveness of the keyboard's auto-repeat feature. For example, when you hold down a hotkey whose #MaxThreadsPerHotkey setting is 1 (the default), incoming keypresses are ignored if that hotkey subroutine is already running. Thus, when the subroutine finishes, it must wait for the next auto-repeat keypress to come in, which might take 50 ms or more due to being caught in between keystrokes of the auto-repeat cycle. This 50 ms delay can be avoided by enabling this directive for any hotkey that needs the best possible response time while it is being auto-repeated.
35 |As with all # directives, this one should not be positioned in the script as though it were a function (i.e. it is not necessary to have it contained within a subroutine). Instead, position it immediately before the first hotkey you wish to have affected by it.
36 |Like other directives, #MaxThreadsBuffer cannot be executed conditionally.
37 |#MaxThreads, #MaxThreadsPerHotkey, Critical, Thread (function), Threads, Hotkey, A_MaxHotkeysPerInterval, ListHotkeys
39 |Causes the first two hotkeys to buffer rather than ignore keypresses when their #MaxThreadsPerHotkey limit has been reached.
42 |#MaxThreadsBuffer True 43 | #x::MsgBox "This hotkey will use this type of buffering." 44 | #y::MsgBox "And this one too." 45 | #MaxThreadsBuffer False 46 | #z::MsgBox "But not this one."47 |
Sets the maximum number of simultaneous threads per hotkey or hotstring.
16 | 17 |#MaxThreadsPerHotkey Value
18 | Type: Integer
24 |The maximum number of threads that can be launched for a given hotkey/hotstring subroutine (limit 255).
25 |If this directive is unspecified in the script, it will behave as though set to 1.
30 |This setting is used to control how many "instances" of a given hotkey or hotstring subroutine are allowed to exist simultaneously. For example, if a hotkey has a max of 1 and it is pressed again while its subroutine is already running, the press will be ignored. This is helpful to prevent accidental double-presses. However, if you wish these keypresses to be buffered rather than ignored -- perhaps to increase the responsiveness of the keyboard's auto-repeat feature -- use #MaxThreadsBuffer.
31 |Unlike #MaxThreads, this setting is not global. Instead, position it before the first hotkey you wish to have affected by it, which will result in all subsequent hotkeys using that value until another instance of this directive is encountered.
32 |The setting of #MaxThreads -- if lower than this setting -- takes precedence.
33 |Like other directives, #MaxThreadsPerHotkey cannot be executed conditionally.
34 |#MaxThreads, #MaxThreadsBuffer, Critical, Threads, Hotkey, A_MaxHotkeysPerInterval, ListHotkeys
36 |Allows a maximum of 3 simultaneous threads instead of 1 per hotkey or hotstring.
39 |#MaxThreadsPerHotkey 340 |
Disables the showing of a tray icon.
16 | 17 |#NoTrayIcon
18 | Specifying this anywhere in a script will prevent the showing of a tray icon for that script when it is launched (even if the script is compiled into an EXE).
19 |If you use this for a script that has hotkeys, you might want to bind a hotkey to the ExitApp function. Otherwise, there will be no easy way to exit the program (without restarting the computer or killing the process). For example: #x::ExitApp
.
The tray icon can be made to disappear or reappear at any time during the execution of the script by assigning a true or false value to A_IconHidden. The only drawback of using A_IconHidden := true
at the very top of the script is that the tray icon might be briefly visible when the script is first launched. To avoid that, use #NoTrayIcon instead.
The built-in variable A_IconHidden contains 1 if the tray icon is currently hidden or 0 otherwise, and can be assigned a value to show or hide the icon.
22 | 23 |Like other directives, #NoTrayIcon cannot be executed conditionally.
24 |Tray Icon, TraySetIcon, A_IconHidden, A_IconTip, ExitApp
26 |Displays an error and quits if a version requirement is not met.
16 | 17 |#Requires Requirement
18 |
19 | Type: String
24 |If this does not begin with the word "AutoHotkey", an error message is shown and the program exits. This encourages clarity and reserves the directive for future uses. Other forks of AutoHotkey may support other names.
25 |Otherwise, the word "AutoHotkey" should be followed by any combination of the following, separated by spaces or tabs:
26 |<
, <=
, >
, >=
or =
immediately followed by an optional letter "v" and a version number. For example, >=2-rc <2
allows v2 release candidates but not the final release.The message shown depends on the version of AutoHotkey interpreting the directive.
36 |For v2, the path, version and build of AutoHotkey are always shown in the error message.
37 |If the script is launched with a version of AutoHotkey that does not support this directive, the error message is something like the following:
38 |Line Text: #Requires %Requirement% 39 | Error: This line does not contain a recognized action.40 | 41 |
If the script uses syntax or functions which are unavailable in earlier versions, using this directive ensures that the error message shows the unmet requirement, rather than indicating an arbitrary syntax error. This cannot be done with something like if (A_AhkVersion <= "1.1.33")
because a syntax error elsewhere in the script would prevent it from executing.
When sharing a script or posting code online, using this directive allows anyone who finds the code to readily identify which version of AutoHotkey it was intended for.
44 |Other programs or scripts can check for this directive for various purposes. For example, the launcher installed with AutoHotkey v2 uses it to determine which AutoHotkey executable to launch, while a script editor or related tools might use it to determine how to interpret or highlight the script file.
45 |Version strings are compared as a series of dot-delimited components, optionally followed by a hyphen and pre-release identifier(s).
46 |#Requires AutoHotkey v2
will not run on v2.0-a112. To permit pre-release versions, include a hyphen suffix. For example: v2.0-
.A trailing "+" is sufficient to indicate to the reader that later versions are acceptable, but is not required.
55 |Like other directives, #Requires cannot be executed conditionally.
56 | 57 |Causes the script to run only on v2.0, including alpha releases.
63 |#Requires AutoHotkey v2.0-a 64 | MsgBox "This script will run only on v2.0, including alpha releases."65 |
Causes the script to run only on v2.0, including pre-release versions.
69 |#Requires AutoHotkey >=2.0- <2.170 |
Causes the script to run only with a 64-bit interpreter (EXE).
74 |#Requires AutoHotkey 64-bit75 |
Causes the script to run only with a 64-bit interpreter (EXE) version 2.0-rc.2 or later.
79 |#Requires AutoHotkey v2.0-rc.2 64-bit80 |
Determines whether a script is allowed to run again when it is already running.
16 | 17 |#SingleInstance ForceIgnorePromptOff18 |
Type: String
24 |If omitted, it defaults to Force. Otherwise, specify one of the following words:
25 |Force: Skips the dialog box and replaces the old instance automatically, which is similar in effect to the Reload function.
26 |Ignore: Skips the dialog box and leaves the old instance running. In other words, attempts to launch an already-running script are ignored.
27 |Prompt: Displays a dialog box asking whether to keep the old instance or replace it with the new one.
28 |Off: Allows multiple instances of the script to run concurrently.
29 |If this directive is unspecified in a script, it will behave as though set to Prompt.
34 |This directive is ignored when any of the following command line switches are used: /force /restart
35 |Like other directives, #SingleInstance cannot be executed conditionally.
36 | 37 |Previous instances of the script are identified by searching for a main window with the default title. Therefore, a previous instance may not be found if:
39 |At most one previous instance is detected and sent a message asking it to close. Therefore, the following additional limitations also apply:
45 |#SingleInstance Off
mode), the topmost matching instance is sent the message, and other instances are not considered.If multiple instances of the script are started simultaneously, they may fail to detect each other or may all target the same previous instance. This would result in multiple instances of the script starting.
50 | 51 |Skips the dialog box and replaces the old instance automatically.
56 |#SingleInstance Force57 |
Exempts subsequent hotkeys and hotstrings from suspension.
17 | 18 |#SuspendExempt Setting19 |
If omitted, it defaults to True. Otherwise, specify one of the following literal values:
26 |True or 1: Enables exemption for subsequent hotkeys and hotstrings.
27 |False or 0: Disables exemption.
28 |If this directive is unspecified in the script, all hotkeys or hotstrings are disabled when the script is suspended, even those which call the Suspend function.
33 |Hotkeys and hotstrings can be suspended by the Suspend function or via the tray icon or main window.
34 |This directive does not affect the Hotkey or Hotstring functions, for which the S hotkey option or S hotstring option can be used instead.
35 |Like other directives, #SuspendExempt cannot be executed conditionally.
36 | 37 |The first hotkey in this example toggles the suspension. To prevent this hotkey from being suspended after the suspension has been turned on and thus no longer being able to turn it off, it must be exempted.
43 |#SuspendExempt ; Exempt the following hotkey from Suspend. 44 | #Esc::Suspend -1 45 | #SuspendExempt False ; Disable exemption for any hotkeys/hotstrings below this. 46 | ^1::MsgBox "This hotkey is affected by Suspend." 47 |48 |
Forces the use of the hook to implement all or some keyboard hotkeys.
16 | 17 |#UseHook Setting18 |
If omitted, it defaults to True. Otherwise, specify one of the following literal values:
25 |True or 1: The keyboard hook will be used to implement all keyboard hotkeys between here and the next #UseHook False
(if any).
False or 0: Hotkeys will be implemented using the default method (RegisterHotkey() if possible; otherwise, the keyboard hook).
27 |If this directive is unspecified in the script, it will behave as though set to False, meaning the windows API function RegisterHotkey() is used to implement a keyboard hotkey whenever possible. However, the responsiveness of hotkeys might be better under some conditions if the keyboard hook is used instead.
33 |Turning this directive ON is equivalent to using the $ prefix in the definition of each affected hotkey.
34 |As with all # directives -- which are processed only once when the script is launched -- #UseHook
should not be positioned in the script as though it were a function (that is, it is not necessary to have it contained within a subroutine). Instead, position it immediately before the first hotkey you wish to have affected by it.
By default, hotkeys that use the keyboard hook cannot be triggered by means of the Send function. Similarly, mouse hotkeys cannot be triggered by built-in functions such as Click because all mouse hotkeys use the mouse hook. One workaround is to name the hotkey's function and call it directly.
36 |#InputLevel and SendLevel provide additional control over which hotkeys and hotstrings are triggered by the Send function.
37 |Like other directives, #UseHook cannot be executed conditionally.
38 | 39 |InstallKeybdHook, InstallMouseHook, ListHotkeys, #InputLevel
41 |Causes the first two hotkeys to use the keyboard hook.
44 |#UseHook ; Force the use of the hook for hotkeys after this point. 45 | #x::MsgBox "This hotkey will be implemented with the hook." 46 | #y::MsgBox "And this one too." 47 | #UseHook False 48 | #z::MsgBox "But not this one."49 |
Enables or disables warnings for specific conditions which may indicate an error, such as a typo or missing "global" declaration.
16 | 17 |#Warn WarningType, WarningMode18 | 19 |
Type: String
25 | 26 |If omitted, it defaults to All. Otherwise, specify the type of warning to enable or disable.
27 |VarUnset: Before the script starts to run, display a warning for the first reference to each variable which is never used in any of the following ways:
28 |MyVar := ""
.&MyVar
).IsSet(MyVar)
).LocalSameAsGlobal: Before the script starts to run, display a warning for each undeclared local variable which has the same name as a global variable. This is intended to prevent errors caused by forgetting to declare a global variable inside a function before attempting to assign to it. If the variable really was intended to be local, a declaration such as local x
or static y
can be used to suppress the warning.
This warning is disabled by default.
35 |#Warn 36 | g := 1 37 | ShowG() { ; The warning is displayed even if the function is never called. 38 | ;global g ; <-- This is required to assign to the global variable. 39 | g := 2 40 | } 41 | ShowG 42 | MsgBox g ; Without the declaration, the above assigned to a local "g".43 |
Unreachable: Before the script starts to run, show a warning for each line that immediately follows a Return
, Break
, Continue
, Throw
or Goto
at the same nesting level, unless that line is the target of a label. Any such line would never be executed.
If the code is intended to be unreachable - such as if a return
has been used to temporarily disable a block of code, or a hotkey or hotstring has been temporarily disabled by commenting it out - consider commenting out the unreachable code as well. Alternatively, the warning can be suppressed by defining a label above the first unreachable line.
All: Apply the given WarningMode to all supported warning types.
46 |Type: String
51 | 52 |If omitted, it defaults to MsgBox. Otherwise, specify a value indicating how warnings should be delivered.
53 |MsgBox: Show a message box describing the warning. Note that once the message box is dismissed, the script will continue as usual.
54 |StdOut: Send a description of the warning to stdout (the program's standard output stream), along with the filename and line number. This allows fancy editors such as SciTE to capture warnings without disrupting the script - the user can later jump to each offending line via the editor's output pane.
55 |OutputDebug: Send a description of the warning to the debugger for display. If a debugger is not active, this will have no effect. For more details, see OutputDebug.
56 |Off: Disable warnings of the given WarningType.
57 |If this directive is unspecified in the script, all warnings are enabled and use the MsgBox mode, except for LocalSameAsGlobal, which is disabled.
62 |The checks which produce VarUnset, LocalSameAsGlobal and Unreachable warnings are performed after all directives have been parsed, but before the script executes. Therefore, the location in the script is not significant (and, like other directives, #Warn cannot be executed conditionally).
63 |However, the ordering of multiple #Warn directives is significant: the last occurrence that sets a given warning determines the mode for that warning. So, for example, the two statements below have the combined effect of enabling all warnings except LocalSameAsGlobal:
64 |#Warn All 65 | #Warn LocalSameAsGlobal, Off 66 |67 |
Sends a warning to OutputDebug for each undeclared local variable which has the same name as a global variable.
82 |#Warn LocalSameAsGlobal, OutputDebug83 |
Skips the gentle method of activating a window and goes straight to the forceful method.
16 | 17 |#WinActivateForce
18 | Specifying this anywhere in a script will cause built-in functions that activate a window -- such as WinActivate, WinActivateBottom, and GroupActivate -- to skip the "gentle" method of activating a window and go straight to the more forceful methods.
19 |Although this directive will usually not change how quickly or reliably a window is activated, it might prevent task bar buttons from flashing when different windows are activated quickly one after the other.
20 | 21 |Like other directives, #WinActivateForce cannot be executed conditionally.
23 | 24 |WinActivate, WinActivateBottom, GroupActivate
26 |Click on a function name for details. Entries in large font are the most commonly used.
18 |Go to entries starting with: E, I, M, S, W, #
19 | 20 |Name | 23 |Description | 24 |
---|---|
{ ... } (Block) | 27 |Blocks are one or more statements enclosed in braces. Typically used with function definitions and control flow statements. | 28 |
{ ... } / Object | 31 |Creates an Object from a list of property name and value pairs. | 32 |
[ ... ] / Array | 35 |Creates an Array from a sequence of parameter values. | 36 |
Abs | 39 |Returns the absolute value of the specified number. | 40 |
ASin | 43 |Returns the arcsine (the number whose sine is the specified number) in radians. | 44 |
ACos | 47 |Returns the arccosine (the number whose cosine is the specified number) in radians. | 48 |
ATan | 51 |Returns the arctangent (the number whose tangent is the specified number) in radians. | 52 |
BlockInput | 55 |Disables or enables the user's ability to interact with the computer via keyboard and mouse. | 56 |
Break | 59 |Exits (terminates) any type of loop statement. | 60 |
Buffer | 63 |Creates a Buffer, which encapsulates a block of memory for use with other functions. | 64 |
CallbackCreate | 67 |Creates a machine-code address that when called, redirects the call to a function in the script. | 68 |
CallbackFree | 71 |Deletes a callback and releases its reference to the function object. | 72 |
CaretGetPos | 75 |Retrieves the current position of the caret (text insertion point). | 76 |
Catch | 79 |Specifies one or more statements to execute if a value or error is thrown during execution of a Try statement. | 80 |
Ceil | 83 |Returns the specified number rounded up to the nearest integer (without any .00 suffix). | 84 |
Chr | 87 |Returns the string (usually a single character) corresponding to the character code indicated by the specified number. | 88 |
Click | 91 |Clicks a mouse button at the specified coordinates. It can also hold down a mouse button, turn the mouse wheel, or move the mouse. | 92 |
ClipboardAll | 95 |Creates an object containing everything on the clipboard (such as pictures and formatting). | 96 |
ClipWait | 99 |Waits until the clipboard contains data. | 100 |
ComCall | 103 |Calls a native COM interface method by index. | 104 |
ComObjActive | 107 |Retrieves a registered COM object. | 108 |
ComObjArray | 111 |Creates a SafeArray for use with COM. | 112 |
ComObjConnect | 115 |Connects a COM object's event source to the script, enabling events to be handled. | 116 |
ComObject | 119 |Creates a COM object. | 120 |
ComObjFlags | 123 |Retrieves or changes flags which control a COM wrapper object's behaviour. | 124 |
ComObjFromPtr | 127 |Wraps a raw IDispatch pointer (COM object) for use by the script. | 128 |
ComObjGet | 131 |Returns a reference to an object provided by a COM component. | 132 |
ComObjQuery | 135 |Queries a COM object for an interface or service. | 136 |
ComObjType | 139 |Retrieves type information from a COM object. | 140 |
ComObjValue | 143 |Retrieves the value or pointer stored in a COM wrapper object. | 144 |
ComValue | 147 |Wraps a value, SafeArray or COM object for use by the script or for passing to a COM method. | 148 |
Continue | 151 |Skips the rest of a loop statement's current iteration and begins a new one. | 152 |
ControlAddItem | 155 |Adds the specified string as a new entry at the bottom of a ListBox or ComboBox. | 156 |
ControlChooseIndex | 159 |Sets the selection in a ListBox, ComboBox or Tab control to be the Nth item. | 160 |
ControlChooseString | 163 |Sets the selection in a ListBox or ComboBox to be the first entry whose leading part matches the specified string. | 164 |
ControlClick | 167 |Sends a mouse button or mouse wheel event to a control. | 168 |
ControlDeleteItem | 171 |Deletes the specified entry number from a ListBox or ComboBox. | 172 |
ControlFindItem | 175 |Returns the entry number of a ListBox or ComboBox that is a complete match for the specified string. | 176 |
ControlFocus | 179 |Sets input focus to a given control on a window. | 180 |
ControlGetChecked | 183 |Returns a non-zero value if the checkbox or radio button is checked. | 184 |
ControlGetChoice | 187 |Returns the name of the currently selected entry in a ListBox or ComboBox. | 188 |
ControlGetClassNN | 191 |Returns the ClassNN (class name and sequence number) of the specified control. | 192 |
ControlGetEnabled | 195 |Returns a non-zero value if the specified control is enabled. | 196 |
ControlGetFocus | 199 |Retrieves which control of the target window has keyboard focus, if any. | 200 |
ControlGetHwnd | 203 |Returns the unique ID number of the specified control. | 204 |
ControlGetIndex | 207 |Returns the index of the currently selected entry or tab in a ListBox, ComboBox or Tab control. | 208 |
ControlGetItems | 211 |Returns an array of items/rows from a ListBox, ComboBox, or DropDownList. | 212 |
ControlGetPos | 215 |Retrieves the position and size of a control. | 216 |
ControlGetStyle ControlGetExStyle |
219 | Returns an integer representing the style or extended style of the specified control. | 220 |
ControlGetText | 223 |Retrieves text from a control. | 224 |
ControlGetVisible | 227 |Returns a non-zero value if the specified control is visible. | 228 |
ControlHide | 231 |Hides the specified control. | 232 |
ControlHideDropDown | 235 |Hides the drop-down list of a ComboBox control. | 236 |
ControlMove | 239 |Moves or resizes a control. | 240 |
ControlSend ControlSendText |
243 | Sends simulated keystrokes or text to a window or control. | 244 |
ControlSetChecked | 247 |Turns on (checks) or turns off (unchecks) a checkbox or radio button. | 248 |
ControlSetEnabled | 251 |Enables or disables the specified control. | 252 |
ControlSetStyle ControlSetExStyle |
255 | Changes the style or extended style of the specified control, respectively. | 256 |
ControlSetText | 259 |Changes the text of a control. | 260 |
ControlShow | 263 |Shows the specified control if it was previously hidden. | 264 |
ControlShowDropDown | 267 |Shows the drop-down list of a ComboBox control. | 268 |
CoordMode | 271 |Sets coordinate mode for various built-in functions to be relative to either the active window or the screen. | 272 |
Cos | 275 |Returns the trigonometric cosine of the specified number. | 276 |
Critical | 279 |Prevents the current thread from being interrupted by other threads, or enables it to be interrupted. | 280 |
DateAdd | 283 |Adds or subtracts time from a date-time value. | 284 |
DateDiff | 287 |Compares two date-time values and returns the difference. | 288 |
DetectHiddenText | 291 |Determines whether invisible text in a window is "seen" for the purpose of finding the window. This affects windowing functions such as WinExist and WinActivate. | 292 |
DetectHiddenWindows | 295 |Determines whether invisible windows are "seen" by the script. | 296 |
DirCopy | 299 |Copies a folder along with all its sub-folders and files (similar to xcopy) or the entire contents of an archive file such as ZIP. | 300 |
DirCreate | 303 |Creates a folder. | 304 |
DirDelete | 307 |Deletes a folder. | 308 |
DirExist | 311 |Checks for the existence of a folder and returns its attributes. | 312 |
DirMove | 315 |Moves a folder along with all its sub-folders and files. It can also rename a folder. | 316 |
DirSelect | 319 |Displays a standard dialog that allows the user to select a folder. |
320 |
DllCall | 323 |Calls a function inside a DLL, such as a standard Windows API function. | 324 |
Download | 327 |Downloads a file from the Internet. | 328 |
DriveEject | 331 |Ejects the tray of the specified CD/DVD drive, or ejects a removable drive. | 332 |
DriveGetCapacity | 335 |Returns the total capacity of the drive which contains the specified path, in megabytes. | 336 |
DriveGetFileSystem | 339 |Returns the type of the specified drive's file system. | 340 |
DriveGetLabel | 343 |Returns the volume label of the specified drive. | 344 |
DriveGetList | 347 |Returns a string of letters, one character for each drive letter in the system. | 348 |
DriveGetSerial | 351 |Returns the volume serial number of the specified drive. | 352 |
DriveGetSpaceFree | 355 |Returns the free disk space of the drive which contains the specified path, in megabytes. | 356 |
DriveGetStatus | 359 |Returns the status of the drive which contains the specified path. | 360 |
DriveGetStatusCD | 363 |Returns the media status of the specified CD/DVD drive. | 364 |
DriveGetType | 367 |Returns the type of the drive which contains the specified path. | 368 |
DriveLock | 371 |Prevents the eject feature of the specified drive from working. | 372 |
DriveRetract | 375 |Retracts the tray of the specified CD/DVD drive. | 376 |
DriveSetLabel | 379 |Changes the volume label of the specified drive. | 380 |
DriveUnlock | 383 |Restores the eject feature of the specified drive. | 384 |
Edit | 387 |Opens the current script for editing in the default editor. | 388 |
EditGetCurrentCol | 391 |Returns the column number in an Edit control where the caret (text insertion point) resides. | 392 |
EditGetCurrentLine | 395 |Returns the line number in an Edit control where the caret (text insert point) resides. | 396 |
EditGetLine | 399 |Returns the text of the specified line in an Edit control. | 400 |
EditGetLineCount | 403 |Returns the number of lines in an Edit control. | 404 |
EditGetSelectedText | 407 |Returns the selected text in an Edit control. | 408 |
EditPaste | 411 |Pastes the specified string at the caret (text insertion point) in an Edit control. | 412 |
Else | 415 |Specifies one or more statements to execute if the associated statement's body did not execute. | 416 |
EnvGet | 419 |Retrieves the value of the specified environment variable. | 420 |
EnvSet | 423 |Writes a value to the specified environment variable. | 424 |
Exit | 427 |Exits the current thread. | 428 |
ExitApp | 431 |Terminates the script. | 432 |
Exp | 435 |Returns the result of raising e (which is approximately 2.71828182845905) to the Nth power. | 436 |
FileAppend | 439 |Writes text or binary data to the end of a file (first creating the file, if necessary). | 440 |
FileCopy | 443 |Copies one or more files. | 444 |
FileCreateShortcut | 447 |Creates a shortcut (.lnk) file. | 448 |
FileDelete | 451 |Deletes one or more files permanently. | 452 |
FileEncoding | 455 |Sets the default encoding for FileRead, Loop Read, FileAppend, and FileOpen. | 456 |
FileExist | 459 |Checks for the existence of a file or folder and returns its attributes. | 460 |
FileInstall | 463 |Includes the specified file inside the compiled version of the script. | 464 |
FileGetAttrib | 467 |Reports whether a file or folder is read-only, hidden, etc. | 468 |
FileGetShortcut | 471 |Retrieves information about a shortcut (.lnk) file, such as its target file. | 472 |
FileGetSize | 475 |Retrieves the size of a file. | 476 |
FileGetTime | 479 |Retrieves the datetime stamp of a file or folder. | 480 |
FileGetVersion | 483 |Retrieves the version of a file. | 484 |
FileMove | 487 |Moves or renames one or more files. | 488 |
FileOpen | 491 |Opens a file to read specific content from it and/or to write new content into it. | 492 |
FileRead | 495 |Retrieves the contents of a file. | 496 |
FileRecycle | 499 |Sends a file or directory to the recycle bin if possible, or permanently deletes it. | 500 |
FileRecycleEmpty | 503 |Empties the recycle bin. | 504 |
FileSelect | 507 |Displays a standard dialog that allows the user to open or save file(s). | 508 |
FileSetAttrib | 511 |Changes the attributes of one or more files or folders. Wildcards are supported. | 512 |
FileSetTime | 515 |Changes the datetime stamp of one or more files or folders. Wildcards are supported. | 516 |
Finally | 519 |Ensures that one or more statements are always executed after a Try statement finishes. | 520 |
Float | 523 |Converts a numeric string or integer value to a floating-point number. | 524 |
Floor | 527 |Returns the specified number rounded down to the nearest integer (without any .00 suffix). | 528 |
For | 531 |Repeats one or more statements once for each key-value pair in an object. | 532 |
Format | 535 |Formats a variable number of input values according to a format string. | 536 |
FormatTime | 539 |Transforms a YYYYMMDDHH24MISS timestamp into the specified date/time format. | 540 |
GetKeyName | 543 |Retrieves the name/text of a key. | 544 |
GetKeyVK | 547 |Retrieves the virtual key code of a key. | 548 |
GetKeySC | 551 |Retrieves the scan code of a key. | 552 |
GetKeyState | 555 |Returns 1 (true) or 0 (false) depending on whether the specified keyboard key or mouse/controller button is down or up. Also retrieves controller status. | 556 |
GetMethod | 559 |Retrieves the implementation function of a method. | 560 |
Goto | 563 |Jumps to the specified label and continues execution. | 564 |
GroupActivate | 567 |Activates the next window in a window group that was defined with GroupAdd. | 568 |
GroupAdd | 571 |Adds a window specification to a window group, creating the group if necessary. | 572 |
GroupClose | 575 |Closes the active window if it was just activated by GroupActivate or GroupDeactivate. It then activates the next window in the series. It can also close all windows in a group. | 576 |
GroupDeactivate | 579 |Similar to GroupActivate except activates the next window not in the group. | 580 |
Gui() | 583 |Creates and returns a new Gui object. This can be used to define a custom window, or graphical user interface (GUI), to display information or accept user input. | 584 |
GuiCtrlFromHwnd | 587 |Retrieves the GuiControl object of a GUI control associated with the specified window handle. | 588 |
GuiFromHwnd | 591 |Retrieves the Gui object of a GUI window associated with the specified window handle. | 592 |
HasBase | 595 |Returns a non-zero number if the specified value is derived from the specified base object. | 596 |
HasMethod | 599 |Returns a non-zero number if the specified value has a method by the specified name. | 600 |
HasProp | 603 |Returns a non-zero number if the specified value has a property by the specified name. | 604 |
HotIf / HotIfWin... | 607 |Specifies the criteria for subsequently created or modified hotkey variants and hotstring variants. | 608 |
Hotkey | 611 |Creates, modifies, enables, or disables a hotkey while the script is running. | 612 |
Hotstring | 615 |Creates, modifies, enables, or disables a hotstring while the script is running. | 616 |
If | 619 |Specifies one or more statements to execute if an expression evaluates to true. | 620 |
IL_Create 623 | IL_Add 624 | IL_Destroy |
625 | The means by which icons are added to a ListView or TreeView control. | 626 |
ImageSearch | 629 |Searches a region of the screen for an image. | 630 |
IniDelete | 633 |Deletes a value from a standard format .ini file. | 634 |
IniRead | 637 |Reads a value, section or list of section names from a standard format .ini file. | 638 |
IniWrite | 641 |Writes a value or section to a standard format .ini file. | 642 |
InputBox | 645 |Displays an input box to ask the user to enter a string. | 646 |
InputHook | 649 |Creates an object which can be used to collect or intercept keyboard input. | 650 |
InstallKeybdHook | 653 |Installs or uninstalls the keyboard hook. | 654 |
InstallMouseHook | 657 |Installs or uninstalls the mouse hook. | 658 |
InStr | 661 |Searches for a given occurrence of a string, from the left or the right. | 662 |
Integer | 665 |Converts a numeric string or floating-point value to an integer. | 666 |
IsLabel | 669 |Returns a non-zero number if the specified label exists in the current scope. | 670 |
IsObject | 673 |Returns a non-zero number if the specified value is an object. | 674 |
IsSet / IsSetRef | 677 |Returns a non-zero number if the specified variable has been assigned a value. | 678 |
KeyHistory | 681 |Displays script info and a history of the most recent keystrokes and mouse clicks. | 682 |
KeyWait | 685 |Waits for a key or mouse/controller button to be released or pressed down. | 686 |
ListHotkeys | 689 |Displays the hotkeys in use by the current script, whether their subroutines are currently running, and whether or not they use the keyboard or mouse hook. | 690 |
ListLines | 693 |Enables or disables line logging or displays the script lines most recently executed. | 694 |
ListVars | 697 |Displays the script's variables: their names and current contents. | 698 |
ListViewGetContent | 701 |Returns a list of items/rows from a ListView. | 702 |
LoadPicture | 705 |Loads a picture from file and returns a bitmap or icon handle. | 706 |
Log | 709 |Returns the logarithm (base 10) of the specified number. | 710 |
Ln | 713 |Returns the natural logarithm (base e) of the specified number. | 714 |
Loop (normal) | 717 |Performs one or more statements repeatedly: either the specified number of times or until Break is encountered. | 718 |
Loop Files | 721 |Retrieves the specified files or folders, one at a time. | 722 |
Loop Parse | 725 |Retrieves substrings (fields) from a string, one at a time. | 726 |
Loop Read | 729 |Retrieves the lines in a text file, one at a time. | 730 |
Loop Reg | 733 |Retrieves the contents of the specified registry subkey, one item at a time. | 734 |
Map | 737 |Creates a Map from a list of key-value pairs. | 738 |
Max | 741 |Returns the highest number from a set of numbers. | 742 |
MenuBar() | 745 |Creates a MenuBar object, which can be used to define a GUI menu bar. | 746 |
Menu() | 749 |Creates a Menu object, which can be used to create and display a menu. | 750 |
MenuFromHandle | 753 |Retrieves the Menu or MenuBar object corresponding to a Win32 menu handle. | 754 |
MenuSelect | 757 |Invokes a menu item from the menu bar of the specified window. | 758 |
Min | 761 |Returns the lowest number from a set of numbers. | 762 |
Mod | 765 |Modulo. Returns the remainder of a number (dividend) divided by another number (divisor). | 766 |
MonitorGet | 769 |Checks if the specified monitor exists and optionally retrieves its bounding coordinates. | 770 |
MonitorGetCount | 773 |Returns the total number of monitors. | 774 |
MonitorGetName | 777 |Returns the operating system's name of the specified monitor. | 778 |
MonitorGetPrimary | 781 |Returns the number of the primary monitor. | 782 |
MonitorGetWorkArea | 785 |Checks if the specified monitor exists and optionally retrieves the bounding coordinates of its working area. | 786 |
MouseClick | 789 |Clicks or holds down a mouse button, or turns the mouse wheel. Note: The Click function is generally more flexible and easier to use. | 790 |
MouseClickDrag | 793 |Clicks and holds the specified mouse button, moves the mouse to the destination coordinates, then releases the button. | 794 |
MouseGetPos | 797 |Retrieves the current position of the mouse cursor, and optionally which window and control it is hovering over. | 798 |
MouseMove | 801 |Moves the mouse cursor. | 802 |
MsgBox | 805 |Displays the specified text in a small window containing one or more buttons (such as Yes and No). | 806 |
Number | 809 |Converts a numeric string to a pure integer or floating-point number. | 810 |
NumGet | 813 |Returns the binary number stored at the specified address+offset. | 814 |
NumPut | 817 |Stores one or more numbers in binary format at the specified address+offset. | 818 |
ObjAddRef / ObjRelease | 821 |Increments or decrements an object's reference count. | 822 |
ObjBindMethod | 825 |Creates a BoundFunc object which calls a method of a given object. | 826 |
829 | ObjHasOwnProp 830 | ObjOwnProps 831 | |
832 | These functions are equivalent to built-in methods of the Object type. It is usually recommended to use the corresponding method instead. | 833 |
ObjGetBase | 836 |Retrieves an object's base object. | 837 |
ObjGetCapacity | 840 |Returns the current capacity of the object's internal array of properties. | 841 |
ObjOwnPropCount | 844 |Returns the number of properties owned by an object. | 845 |
ObjSetBase | 848 |Sets an object's base object. | 849 |
ObjSetCapacity | 852 |Sets the current capacity of the object's internal array of own properties. | 853 |
OnClipboardChange | 856 |Registers a function to be called automatically whenever the clipboard's content changes. | 857 |
OnError | 860 |Registers a function to be called automatically whenever an unhandled error occurs. | 861 |
OnExit | 864 |Registers a function to be called automatically whenever the script exits. | 865 |
OnMessage | 868 |Registers a function to be called automatically whenever the script receives the specified message. | 869 |
Ord | 872 |Returns the ordinal value (numeric character code) of the first character in the specified string. | 873 |
OutputDebug | 876 |Sends a string to the debugger (if any) for display. | 877 |
Pause | 880 |Pauses the script's current thread or sets the pause state of the underlying thread. | 881 |
Persistent | 884 |Prevents the script from exiting automatically when its last thread completes, allowing it to stay running in an idle state. | 885 |
PixelGetColor | 888 |Retrieves the color of the pixel at the specified X and Y coordinates. | 889 |
PixelSearch | 892 |Searches a region of the screen for a pixel of the specified color. | 893 |
PostMessage | 896 |Places a message in the message queue of a window or control. | 897 |
ProcessClose | 900 |Forces the first matching process to close. | 901 |
ProcessExist | 904 |Checks if the specified process exists. | 905 |
ProcessGetName | 908 |Returns the name of the specified process. | 909 |
ProcessGetParent | 912 |Returns the process ID (PID) of the process which created the specified process. | 913 |
ProcessGetPath | 916 |Returns the path of the specified process. | 917 |
ProcessSetPriority | 920 |Changes the priority level of the first matching process. | 921 |
ProcessWait | 924 |Waits for the specified process to exist. | 925 |
ProcessWaitClose | 928 |Waits for all matching processes to close. | 929 |
Random | 932 |Generates a pseudo-random number. | 933 |
RegExMatch | 936 |Determines whether a string contains a pattern (regular expression). | 937 |
RegExReplace | 940 |Replaces occurrences of a pattern (regular expression) inside a string. | 941 |
RegCreateKey | 944 |Creates a registry key without writing a value. | 945 |
RegDelete | 948 |Deletes a value from the registry. | 949 |
RegDeleteKey | 952 |Deletes a subkey from the registry. | 953 |
RegRead | 956 |Reads a value from the registry. | 957 |
RegWrite | 960 |Writes a value to the registry. | 961 |
Reload | 964 |Replaces the currently running instance of the script with a new one. | 965 |
Return | 968 |Returns from a function to which execution had previously jumped via function-call, Hotkey activation, or other means. | 969 |
Round | 972 |Returns the specified number rounded to N decimal places. | 973 |
Run | 976 |Runs an external program. | 977 |
RunAs | 980 |Specifies a set of user credentials to use for all subsequent Run and RunWait functions. | 981 |
RunWait | 984 |Runs an external program and waits until it finishes. | 985 |
Send / SendText / SendInput / SendPlay / SendEvent | 988 |Sends simulated keystrokes and mouse clicks to the active window. | 989 |
SendLevel | 992 |Controls which artificial keyboard and mouse events are ignored by hotkeys and hotstrings. | 993 |
SendMessage | 996 |Sends a message to a window or control and waits for acknowledgement. | 997 |
SendMode | 1000 |Makes Send synonymous with SendEvent or SendPlay rather than the default (SendInput). Also makes Click and MouseMove/Click/Drag use the specified method. | 1001 |
SetCapsLockState | 1004 |Sets the state of CapsLock. Can also force the key to stay on or off. | 1005 |
SetControlDelay | 1008 |Sets the delay that will occur after each control-modifying function. | 1009 |
SetDefaultMouseSpeed | 1012 |Sets the mouse speed that will be used if unspecified in Click, MouseMove, MouseClick, and MouseClickDrag. | 1013 |
SetKeyDelay | 1016 |Sets the delay that will occur after each keystroke sent by Send or ControlSend. | 1017 |
SetMouseDelay | 1020 |Sets the delay that will occur after each mouse movement or click. | 1021 |
SetNumLockState | 1024 |Sets the state of NumLock. Can also force the key to stay on or off. | 1025 |
SetScrollLockState | 1028 |Sets the state of ScrollLock. Can also force the key to stay on or off. | 1029 |
SetRegView | 1032 |Sets the registry view used by RegRead, RegWrite, RegDelete, RegDeleteKey and Loop Reg, allowing them in a 32-bit script to access the 64-bit registry view and vice versa. | 1033 |
SetStoreCapsLockMode | 1036 |Whether to restore the state of CapsLock after a Send. | 1037 |
SetTimer | 1040 |Causes a function to be called automatically and repeatedly at a specified time interval. | 1041 |
SetTitleMatchMode | 1044 |Sets the matching behavior of the WinTitle parameter in built-in functions such as WinWait. | 1045 |
SetWinDelay | 1048 |Sets the delay that will occur after each windowing function, such as WinActivate. | 1049 |
SetWorkingDir | 1052 |Changes the script's current working directory. | 1053 |
Shutdown | 1056 |Shuts down, restarts, or logs off the system. | 1057 |
Sin | 1060 |Returns the trigonometric sine of the specified number. | 1061 |
Sleep | 1064 |Waits the specified amount of time before continuing. | 1065 |
Sort | 1068 |Arranges a variable's contents in alphabetical, numerical, or random order (optionally removing duplicates). | 1069 |
SoundBeep | 1072 |Emits a tone from the PC speaker. | 1073 |
SoundGetInterface | 1076 |Retrieves a native COM interface of a sound device or component. | 1077 |
SoundGetMute | 1080 |Retrieves a mute setting of a sound device. | 1081 |
SoundGetName | 1084 |Retrieves the name of a sound device or component. | 1085 |
SoundGetVolume | 1088 |Retrieves a volume setting of a sound device. | 1089 |
SoundPlay | 1092 |Plays a sound, video, or other supported file type. | 1093 |
SoundSetMute | 1096 |Changes a mute setting of a sound device. | 1097 |
SoundSetVolume | 1100 |Changes a volume setting of a sound device. | 1101 |
SplitPath | 1104 |Separates a file name or URL into its name, directory, extension, and drive. | 1105 |
Sqrt | 1108 |Returns the square root of the specified number. | 1109 |
StatusBarGetText | 1112 |Retrieves the text from a standard status bar control. | 1113 |
StatusBarWait | 1116 |Waits until a window's status bar contains the specified string. | 1117 |
StrCompare | 1120 |Compares two strings alphabetically. | 1121 |
StrGet | 1124 |Copies a string from a memory address or buffer, optionally converting it from a given code page. | 1125 |
String | 1128 |Converts a value to a string. | 1129 |
StrLen | 1132 |Retrieves the count of how many characters are in a string. | 1133 |
StrLower | 1136 |Converts a string to lowercase. | 1137 |
StrPtr | 1140 |Returns the current memory address of a string. | 1141 |
StrPut | 1144 |Copies a string to a memory address or buffer, optionally converting it to a given code page. | 1145 |
StrReplace | 1148 |Replaces the specified substring with a new string. | 1149 |
StrSplit | 1152 |Separates a string into an array of substrings using the specified delimiters. | 1153 |
StrTitle | 1156 |Converts a string to title case. | 1157 |
StrUpper | 1160 |Converts a string to uppercase. | 1161 |
SubStr | 1164 |Retrieves one or more characters from the specified position in a string. | 1165 |
Suspend | 1168 |Disables or enables all or selected hotkeys and hotstrings. | 1169 |
Switch | 1172 |Compares a value with multiple cases and executes the statements of the first match. | 1173 |
SysGet | 1176 |Retrieves dimensions of system objects, and other system properties. | 1177 |
SysGetIPAddresses | 1180 |Returns an array of the system's IPv4 addresses. | 1181 |
Tan | 1184 |Returns the trigonometric tangent of the specified number. | 1185 |
Thread | 1188 |Sets the priority or interruptibility of threads. It can also temporarily disable all timers. | 1189 |
Throw | 1192 |Signals the occurrence of an error. This signal can be caught by a Try-Catch statement. | 1193 |
ToolTip | 1196 |Shows an always-on-top window anywhere on the screen. | 1197 |
TraySetIcon | 1200 |Changes the script's tray icon (which is also used by GUI and dialog windows). | 1201 |
TrayTip | 1204 |Shows a balloon message window or, on Windows 10 and later, a toast notification near the tray icon. | 1205 |
Trim / LTrim / RTrim | 1208 |Trims characters from the beginning and/or end of a string. | 1209 |
Try | 1212 |Guards one or more statements against runtime errors and values thrown by the Throw statement. | 1213 |
Type | 1216 |Returns the class name of a value. | 1217 |
Until | 1220 |Applies a condition to the continuation of a Loop or For-loop. | 1221 |
VarSetStrCapacity | 1224 |Enlarges a variable's holding capacity or frees its memory. This is not normally needed, but may be used with DllCall or SendMessage or to optimize repeated concatenation. | 1225 |
VerCompare | 1228 |Compares two version strings. | 1229 |
While-loop | 1232 |Performs one or more statements repeatedly until the specified expression evaluates to false. | 1233 |
WinActivate | 1236 |Activates the specified window. | 1237 |
WinActivateBottom | 1240 |Same as WinActivate except that it activates the bottommost matching window rather than the topmost. | 1241 |
WinActive | 1244 |Checks if the specified window is active and returns its unique ID (HWND). | 1245 |
WinClose | 1248 |Closes the specified window. | 1249 |
WinExist | 1252 |Checks if the specified window exists and returns the unique ID (HWND) of the first matching window. | 1253 |
WinGetClass | 1256 |Retrieves the specified window's class name. | 1257 |
WinGetClientPos | 1260 |Retrieves the position and size of the specified window's client area. | 1261 |
WinGetControls | 1264 |Returns an array of names (ClassNNs) for all controls in the specified window. | 1265 |
WinGetControlsHwnd | 1268 |Returns an array of unique ID numbers (HWNDs) for all controls in the specified window. | 1269 |
WinGetCount | 1272 |Returns the number of existing windows that match the specified criteria. | 1273 |
WinGetID | 1276 |Returns the unique ID number (HWND) of the specified window. | 1277 |
WinGetIDLast | 1280 |Returns the unique ID number (HWND) of the last/bottommost window if there is more than one match. | 1281 |
WinGetList | 1284 |Returns an array of unique ID numbers (HWNDs) for all existing windows that match the specified criteria. | 1285 |
WinGetMinMax | 1288 |Returns a non-zero number if the specified window is maximized or minimized. | 1289 |
WinGetPID | 1292 |Returns the Process ID number (PID) of the specified window. | 1293 |
WinGetPos | 1296 |Retrieves the position and size of the specified window. | 1297 |
WinGetProcessName | 1300 |Returns the name of the process that owns the specified window. | 1301 |
WinGetProcessPath | 1304 |Returns the full path and name of the process that owns the specified window. | 1305 |
WinGetStyle WinGetExStyle |
1308 | Returns the style or extended style (respectively) of the specified window. | 1309 |
WinGetText | 1312 |Retrieves the text from the specified window. | 1313 |
WinGetTitle | 1316 |Retrieves the title of the specified window. | 1317 |
WinGetTransColor | 1320 |Returns the color that is marked transparent in the specified window. | 1321 |
WinGetTransparent | 1324 |Returns the degree of transparency of the specified window. | 1325 |
WinHide | 1328 |Hides the specified window. | 1329 |
WinKill | 1332 |Forces the specified window to close. | 1333 |
WinMaximize | 1336 |Enlarges the specified window to its maximum size. | 1337 |
WinMinimize | 1340 |Collapses the specified window into a button on the task bar. | 1341 |
WinMinimizeAll / WinMinimizeAllUndo | 1344 |Minimizes or unminimizes all windows. | 1345 |
WinMove | 1348 |Changes the position and/or size of the specified window. | 1349 |
WinMoveBottom | 1352 |Sends the specified window to the bottom of stack; that is, beneath all other windows. | 1353 |
WinMoveTop | 1356 |Brings the specified window to the top of the stack without explicitly activating it. | 1357 |
WinRedraw | 1360 |Redraws the specified window. | 1361 |
WinRestore | 1364 |Unminimizes or unmaximizes the specified window if it is minimized or maximized. | 1365 |
WinSetAlwaysOnTop | 1368 |Makes the specified window stay on top of all other windows (except other always-on-top windows). | 1369 |
WinSetEnabled | 1372 |Enables or disables the specified window. | 1373 |
WinSetRegion | 1376 |Changes the shape of the specified window to be the specified rectangle, ellipse, or polygon. | 1377 |
WinSetStyle WinSetExStyle |
1380 | Changes the style or extended style of the specified window, respectively. | 1381 |
WinSetTitle | 1384 |Changes the title of the specified window. | 1385 |
WinSetTransColor | 1388 |Makes all pixels of the chosen color invisible inside the specified window. | 1389 |
WinSetTransparent | 1392 |Makes the specified window semi-transparent. | 1393 |
WinShow | 1396 |Unhides the specified window. | 1397 |
WinWait | 1400 |Waits until the specified window exists. | 1401 |
WinWaitActive / WinWaitNotActive | 1404 |Waits until the specified window is active or not active. | 1405 |
WinWaitClose | 1408 |Waits until no matching windows can be found. | 1409 |
#ClipboardTimeout | 1412 |Changes how long the script keeps trying to access the clipboard when the first attempt fails. | 1413 |
#DllLoad | 1416 |Loads a DLL or EXE file before the script starts executing. | 1417 |
#ErrorStdOut | 1420 |Sends any syntax error that prevents a script from launching to the standard error stream (stderr) rather than displaying a dialog. | 1421 |
#Hotstring | 1424 |Changes hotstring options or ending characters. | 1425 |
#HotIf | 1428 |Creates context-sensitive hotkeys and hotstrings. They perform a different action (or none at all) depending on any condition (an expression). | 1429 |
#HotIfTimeout | 1432 |Sets the maximum time that may be spent evaluating a single #HotIf expression. | 1433 |
#Include / #IncludeAgain | 1436 |Causes the script to behave as though the specified file's contents are present at this exact position. | 1437 |
#InputLevel | 1440 |Controls which artificial keyboard and mouse events are ignored by hotkeys and hotstrings. | 1441 |
#MaxThreads | 1444 |Sets the maximum number of simultaneous threads. | 1445 |
#MaxThreadsBuffer | 1448 |Causes some or all hotkeys to buffer rather than ignore keypresses when their #MaxThreadsPerHotkey limit has been reached. | 1449 |
#MaxThreadsPerHotkey | 1452 |Sets the maximum number of simultaneous threads per hotkey or hotstring. | 1453 |
#NoTrayIcon | 1456 |Disables the showing of a tray icon. | 1457 |
#Requires | 1460 |Displays an error and quits if a version requirement is not met. | 1461 |
#SingleInstance | 1464 |Determines whether a script is allowed to run again when it is already running. | 1465 |
#SuspendExempt | 1468 |Exempts subsequent hotkeys and hotstrings from suspension. | 1469 |
#UseHook | 1472 |Forces the use of the hook to implement all or some keyboard hotkeys. | 1473 |
#Warn | 1476 |Enables or disables warnings for specific conditions which may indicate an error, such as a typo or missing "global" declaration. | 1477 |
#WinActivateForce | 1480 |Skips the gentle method of activating a window and goes straight to the forceful method. | 1481 |
Version 2, June 1991
15 |16 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 17 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA 18 | 19 | Everyone is permitted to copy and distribute verbatim copies 20 | of this license document, but changing it is not allowed. 21 |22 |
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
24 |When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
25 |To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
26 |For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
27 |We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
28 |Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
29 |Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
30 |The precise terms and conditions for copying, distribution and modification follow.
31 |0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
33 |Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
34 |1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
35 |You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
36 |2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
37 |These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
46 |Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
47 |In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
48 |3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
49 | 50 | 51 | 52 | 53 |The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
62 |If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
63 |4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
64 |5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
65 |6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
66 |7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
67 |If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
68 |It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
69 |This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
70 |8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
71 |9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
72 |Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
73 |10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
74 |NO WARRANTY
75 |11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
76 |12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
77 |In addition to the AutoIt authors already mentioned:
15 |Robert Yaklin: A lot of tireless testing to isolate bugs, a great first draft of the installer, as well as great suggestions for how commands ought to work :)
16 |Jason Payam Ahdoot: For suggesting and describing floating point support.
17 |Jay D. Novak: For discovering many Win9x problems with the Send command, CapsLock, and hotkey modifiers; and for generously sharing his wealth of code and wisdom for hotkeys, hot-strings, hook usage, and typing acceleration.
18 |Rajat: For creating stylish replacements for the original AHK icons; a great product logo; making the syntax customizations for TextPad; discovering some bugs with the registry commands and AutoIt v2 compatibility; making SmartGUI Creator; and many other things.
19 |Thaddeus Beck (Beardboy): For NT4 testing to fix GetKeyState and the Send command; for a lot of help on the forum; and for many suggestions and bug reports.
20 |Gregory F. Hogg of Hogg's Software: For writing the source code for multi-monitor support in the SysGet command.
21 |Aurelian Maga: For writing the source code for ImageSearch and the faster PixelSearch.
22 |Joost Mulders: Whose source code provided the foundation for expressions.
23 |Laszlo Hars: For advice about data structures and algorithms, which helped greatly speed up arrays and dynamic variables.
24 |Marcus Sonntag (Ultra): For the research, design, coding, and testing of DllCall.
25 |Gena Shimanovich: For debugging and coding assistance; and for some advanced prototype scripts upon which future features may be based.
26 |Eric Morin (numEric): For advice on mathematics; for steadfast debugging of areas like OnMessage, floating point computations, and mouse movement; and for improvements to overall quality.
27 |Philip Hazel: For Perl-Compatible Regular Expressions (PCRE).
28 |Titan/polyethene: For providing community hosting on autohotkey.net, creating many useful scripts and libraries, creating the JavaScript to colorize code-comments in the forum, and many other things.
29 |Philippe Lhoste (PhiLho): For tireless moderation and support in the forum, RegEx advice and testing, syntax and design ideas, and many other things.
30 |John Biederman: For greatly improving the presentation and ergonomics of the documentation.
31 |Jonathan Rennison (JGR): For developing RegisterCallback (now called CallbackCreate), and for beneficial suggestions.
32 |Steve Gray (Lexikos): For developing dynamic function calling and other new functionality; analyzing and fixing bugs; and valuable support and advice for hundreds of individual visitors at the forum.
33 |AutoHotkey_L:
34 |jackieku: For developing Unicode support and other new functionality.
35 |fincs: For developing native 64-bit support and try/catch/throw, writing a replacement for the old compiler, analyzing and fixing bugs.
36 |Sean: For developing built-in COM functionality and providing valuable insight into COM.
37 |TheGood: For merging the documentation and adapting the installer script.
38 |ac: For developing #Warn.
39 |Russell Davis: For developing A_PriorKey, ahk_path (the basis of ahk_exe in WinTitle parameters), #InputLevel and SendLevel.
40 |Christian Sander: For developing support for SysLink controls.
41 |42 |
And to everyone else who's contributed or sent in bug reports or suggestions: Thanks!
43 | 44 | 45 | -------------------------------------------------------------------------------- /docs/misc/Ahk2ExeDirectives.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Script compiler directives allow the user to specify details of how a script is to be compiled via Ahk2Exe. Some of the features are:
45 |The script compiler looks for special comments in the source script and recognises these as Compiler Directives. All compiler directives are introduced by the string @Ahk2Exe-
, preceded by the comment flag (usually ;
).
It is possible to remove code sections from the compiled script by wrapping them in directives:
55 |MsgBox "This message appears in both the compiled and uncompiled script" 56 | ;@Ahk2Exe-IgnoreBegin 57 | MsgBox "This message does NOT appear in the compiled script" 58 | ;@Ahk2Exe-IgnoreEnd 59 | MsgBox "This message appears in both the compiled and uncompiled script" 60 |61 |
The reverse is also possible, i.e. marking a code section to only be executed in the compiled script:
62 |/*@Ahk2Exe-Keep 63 | MsgBox "This message appears only in the compiled script" 64 | */ 65 | MsgBox "This message appears in both the compiled and uncompiled script" 66 |67 |
This has advantage over A_IsCompiled because the code is completely removed from the compiled script during preprocessing, thus making the compiled script smaller. The reverse is also true: it will not be necessary to check for A_IsCompiled because the code is inside a comment block in the uncompiled script.
68 | 69 |In the parameters of these directives, the following escape sequences are supported: ``
, `,
, `n
, `r
and `t
. Commas always need to be escaped, regardless of the parameter position. "Integer" refers to unsigned 16-bit integers (0..0xFFFF).
If required, directive parameters can reference the following list of standard built-in variables by enclosing the variable name with %
signs:
Group 1: A_AhkPath, A_AppData, A_AppDataCommon, A_ComputerName, A_ComSpec, A_Desktop, A_DesktopCommon, A_MyDocuments, A_ProgramFiles, A_Programs, A_ProgramsCommon, A_ScriptDir, A_ScriptFullPath, A_ScriptName, A_Space, A_StartMenu, A_StartMenuCommon, A_Startup, A_StartupCommon, A_Tab, A_Temp, A_UserName, A_WinDir.
75 | 76 |Group 2: A_AhkVersion, A_IsCompiled, A_PtrSize.
77 | 78 |In addition to these variable names, the special variable A_WorkFileName holds the temporary name of the processed .exe file. This can be used to pass the file name as a parameter to any PostExec directives which need to access the generated .exe.
79 | 80 |Furthermore, the special variable A_BasePath contains the full path and name of the selected base file.
81 | 82 |Also, the special variable A_PriorLine contains the source line immediately preceding the current compiler directive. Intervening lines of blanks and comments only are ignored, as are any intervening compiler directive lines. This variable can be used to 'pluck' constant information from the script source, and use it in later compiler directives. An example would be accessing the version number of the script, which may be changed often. Accessing the version number in this way means that it needs to be changed only once in the source code, and the change will get copied through to the necessary directive. (See the RegEx example below for more information.)
83 | 84 |As well, special user variables can be created with the format U_Name
using the Let and Obey directives, described below.
In addition to being available for directive parameters, all variables can be accessed from any RT_MENU, RT_DIALOG, RT_STRING, RT_ACCELERATORS, RT_HTML, and RT_MANIFEST file supplied to the AddResource directive, below.
87 | 88 |If needed, the value returned from the above variables can be manipulated by including at the end of the built-in variable name before the ending %
, up to 2 parameters (called p2 and p3) all separated by tilde ~
. The p2 and p3 parameters will be used as literals in the 2nd and 3rd parameters of a RegExReplace function to manipulate the value returned. (See RegEx Quick Reference.) Note that p3 is optional.
To include a tilde as data in p2 or p3, preceded it with a back-tick, i.e. `~
. To include a back-tick character as data in p2 or p3, double it, i.e. ``
.
%A_ScriptName~\.[^\.]+$~.exe%96 |
This replaces the extension plus preceding full-stop, with .exe
in the actual script name.
(\.[^\.]+$~.exe
means scan for a .
followed by 1 or more non-.
characters followed by end-of-string, and replace them with .exe
)
Assume there is a source line followed by two compiler directives as follows:
100 |CodeVersion := "1.2.3.4", company := "My Company"101 |
;@Ahk2Exe-Let U_version = %A_PriorLine~U)^(.+"){1}(.+)".*$~$2%102 |
;@Ahk2Exe-Let U_company = %A_PriorLine~U)^(.+"){3}(.+)".*$~$2%103 |
These directives copy the version number 1.2.3.4
into the special variable U_version
, and the company name My Company
into the special variable U_company
for use in other directives later.
104 | (The {1}
in the first regex was changed to {3}
in the second regex to select after the third "
to extract the company name.)
Other examples: Other working examples which can be downloaded and examined, are available from here.
108 | 109 |Adds a resource to the compiled executable. (Also see UseResourceLang below)
111 |;@Ahk2Exe-AddResource FileName , ResourceName112 |
*type Filename
. If omitted, Ahk2Exe automatically detects the type according to the file extension.Here is a list of common standard resource types and the extensions that trigger them by default.
119 |.bmp
, .dib
.cur
(not yet supported).ico
.htm
, .html
, .mht
.manifest
. If the name for the resource is not specified, it defaults to 1
Example 1: To replace the standard icons (other than the main icon):
133 |;@Ahk2Exe-AddResource Icon1.ico, 160 ; Replaces 'H on blue' 134 | ;@Ahk2Exe-AddResource Icon2.ico, 206 ; Replaces 'S on green' 135 | ;@Ahk2Exe-AddResource Icon3.ico, 207 ; Replaces 'H on red' 136 | ;@Ahk2Exe-AddResource Icon4.ico, 208 ; Replaces 'S on red'137 | 138 |
Example 2: To include another script as a separate RCDATA resource (see Embedded Scripts):
139 |;@Ahk2Exe-AddResource MyScript1.ahk, #2 140 | ;@Ahk2Exe-AddResource MyScript2.ahk, MYRESOURCE141 |
Note that each script added with this directive will be fully and separately processed by the compiler, and can include further directives. If there are any competing directives overall, the last encountered by the compiler will be used.
142 | 143 |Specifies the base version of AutoHotkey to be used to generate the .exe file. This directive may be overridden by a base file parameter specified in the GUI or CLI. This directive can be specified many times if necessary, but only in the top level script file (i.e. not in an #Include file). The compiler will be run at least once for each Bin/Base directive found. (If an actual comment is appended to this directive, it must use the ;
flag. To truly comment out this directive, insert a space after the first comment flag.)
;@Ahk2Exe-Bin [Path\]Name , [Exe_path\][Name], Codepage ; Deprecated 147 | ;@Ahk2Exe-Base [Path\]Name , [Exe_path\][Name], Codepage148 |
.bin
is assumed. The file is assumed to be in (or relative to) the compiler's own directory if an absolute path isn't specified. A DOS mask may be specified for Name, e.g. ANSI*
, Unicode 32*
, Unicode 64*
, or *bit
for all three. The compiler will be run for each *.bin or *.exe file that matches. Any use of built-in variable replacements must only be from group 1 above..exe
. If no path is specified, the .exe will be created in the script folder. If no name is specified, the .exe will have the default name. Any use of built-in variable replacements must only be from group 1 above. (This parameter can be overridden by the ExeName directive.)Changes the executable subsystem to Console mode.
160 |;@Ahk2Exe-ConsoleApp
161 |
162 | Specifies a continuation line for the preceding directive. This allows a long-lined directive to be formatted so that it is easy to read in the source code.
164 |;@Ahk2Exe-Cont Text
165 | Cont
key-word.Shows a message box with the supplied text, for debugging purposes.
172 |;@Ahk2Exe-Debug Text
173 | %
signs to see the (manipulated) contents.Specifies the location and name given to the generated .exe file. (Also see the Base directive.) This directive may be overridden by an output file specified in the GUI or CLI.
180 |;@Ahk2Exe-ExeName [Path\][Name]
181 | .exe
. If no path is specified, the .exe will be created in the script folder. If no name is specified, the .exe will have the default name.;@Ahk2Exe-Obey U_bits, = %A_PtrSize% * 8 187 | ;@Ahk2Exe-Obey U_type, = "%A_IsUnicode%" ? "Unicode" : "ANSI" 188 | ;@Ahk2Exe-ExeName %A_ScriptName~\.[^\.]+$%_%U_type%_%U_bits%189 | 190 |
Creates (or modifies) one or more user variables which can be accessed by %U_Name%
, similar to the built-in variables (see above).
;@Ahk2Exe-Let Name = Value , Name = Value, ...193 |
U_
).Does nothing.
202 |;@Ahk2Exe-Nop Text203 |
Ver := A_AhkVersion "" ; If quoted literal not empty, do 'SetVersion' 209 | ;@Ahk2Exe-Obey U_V, = "%A_PriorLine~U)^(.+")(.*)".*$~$2%" ? "SetVersion" : "Nop" 210 | ;@Ahk2Exe-%U_V% %A_AhkVersion%%A_PriorLine~U)^(.+")(.*)".*$~$2%211 | 212 |
Obeys isolated AutoHotkey commands or expressions, with result in U_Name
.
;@Ahk2Exe-Obey Name, CmdOrExp , Extra215 |
U_
) to receive the result.The command or expression to obey.
221 |Command format must use Name as the output variable (often the first parameter), e.g.
222 |;@Ahk2Exe-Obey U_date, FormatTime U_date`, R D2 T2223 |
Expression format must start with =
, e.g.
;@Ahk2Exe-Obey U_type, = "%A_IsUnicode%" ? "Unicode" : "ANSI"225 |
Expressions can be written in command format, e.g.
226 |;@Ahk2Exe-Obey U_bits, U_bits := %A_PtrSize% * 8227 |
If needed, separate multiple commands and expressions with `n
.
U_name
, U_name1
, and U_name2
. The values in the name
s must first be set by the expression or command.Specifies a program to be executed after a successful compilation, before (or after) any Compression is applied to the .exe. This directive can be present many times and will be executed in the order encountered by the compiler, in the appropriate queue as specified by the When parameter.
235 |;@Ahk2Exe-PostExec Program [parameters] , When, WorkingDir, Hidden, IgnoreErrors236 |
"%A_WorkFileName%"
. If the program changes the .exe, the altered .exe must be moved back to the input file specified by %A_WorkFileName%
, by the program. (Note that the .exe will contain binary data.)(Optional) Leave blank to execute before any Compression is done. Otherwise set to a number to run after compression as follows:
242 |Example 1: (To use the first two examples, first download BinMod.ahk and compile it according to the instructions in the downloaded script.)
256 |This example can be used to remove a reference to "AutoHotkey" in the generated .exe to disguise that it is a compiled AutoHotkey script:
257 |;@Ahk2Exe-Obey U_au, = "%A_IsUnicode%" ? 2 : 1 ; Script ANSI or Unicode? 258 | ;@Ahk2Exe-PostExec "BinMod.exe" "%A_WorkFileName%" 259 | ;@Ahk2Exe-Cont "%U_au%2.>AUTOHOTKEY SCRIPT<. DATA "260 |
Example 2: This example will alter a UPX compressed .exe so that it can't be de-compressed with UPX -d
:
;@Ahk2Exe-PostExec "BinMod.exe" "%A_WorkFileName%" 262 | ;@Ahk2Exe-Cont "11.UPX." "1.UPX!.", 2263 |
(There are other examples mentioned in the BinMod.ahk script.)
264 |Example 3: This example specifies the Compression to be used on a compiled script, if none is specified in the CLI or GUI. The default parameters normally used by the compiler are shown.
For MPRESS:
265 |;@Ahk2Exe-PostExec "MPRESS.exe" "%A_WorkFileName%" -q -x, 0,, 1266 |
For UPX:
267 |;@Ahk2Exe-PostExec "UPX.exe" "%A_WorkFileName%" 268 | ;@Ahk2Exe-Cont -q --all-methods --compress-icons=0, 0,, 1269 | 270 |
Assigns a non-standard resource ID to be used for the main script for compilations which use an .exe base file (see Embedded Scripts). This directive may be overridden by a Resource ID specified in the GUI or CLI. This directive is ignored if it appears in a script inserted by the AddResource directive.
272 |;@Ahk2Exe-ResourceID Name
273 | Overrides the custom EXE icon used for compilation. (To change the other icons, see the AddResource example.) This directive may be overridden by an icon file specified in the GUI or CLI. The new icon might not be immediately visible in Windows Explorer if the compiled file existed before with a different icon, however the new icon can be shown by selecting Refresh Windows Icons
from the Ahk2Exe File
menu.
;@Ahk2Exe-SetMainIcon IcoFile281 |
Changes a property in the compiled executable's version information. Note that all properties are processed in alphabetical order, regardless of the order they are specified.
288 |;@Ahk2Exe-SetProp Value
289 | The name of the property to change. Must be one of those listed below.
293 |Property | 296 |Description | 297 |
---|---|
CompanyName | 300 |Changes the company name. | 301 |
Copyright | 304 |Changes the legal copyright information. | 305 |
Description | 308 |Changes the file description. On Windows 8 and above, this also changes the script's name in Task Manager under "Processes". | 309 |
FileVersion | 312 |Changes the file version, in both text and raw binary format. (See Version below, for more details.) | 313 |
InternalName | 316 |Changes the internal name. | 317 |
Language | 320 |Changes the language code. Please note that hexadecimal numbers must have an 0x prefix. |
321 |
LegalTrademarks | 324 |Changes the legal trademarks information. | 325 |
Name | 328 |Changes the product name and the internal name. | 329 |
OrigFilename | 332 |Changes the original filename information. | 333 |
ProductName | 336 |Changes the product name. | 337 |
ProductVersion | 340 |Changes the product version, in both text and raw binary format. (See Version below, for more details.) | 341 |
Version | 344 |
345 | Changes the file version and the product version, in both text and raw binary format. 346 |Ahk2Exe fills the binary version fields with the period-delimited numbers (up to four) that may appear at the beginning of the version text. Unfilled fields are set to zero. For example, |
348 |
Changes other miscellaneous properties in the compiled executable's version information not covered by the SetProp directive. Note that all properties are processed in alphabetical order, regardless of the order they are specified. This directive is for specialised use only.
357 |;@Ahk2Exe-Set Prop, Value
358 | Changes details in the .exe's manifest. This directive is for specialised use only.
367 |;@Ahk2Exe-UpdateManifest RequireAdmin , Name, Version, UIAccess368 |
Changes the resource language used by AddResource. This directive is positional and affects all AddResource directives that follow it.
381 |;@Ahk2Exe-UseResourceLang LangCode
382 | 0x
prefix. The default resource language is US English (0x0409).Certain special folders within the operating system are identified by unique strings. Some of these strings can be used with DirSelect. For example:
25 |DirSelect("::{20D04FE0-3AEA-1069-A2D8-08002B30309D}") ; Select a folder within This PC (formerly My Computer or Computer).26 |
To open a CLSID via Run, simply specify the CLSID as the first parameter. Most of the CLSIDs in the table below can be opened by using Run "shell:CLSID"
. Some can be opened without the shell: prefix. For example:
Run "shell:::{D20EA4E1-3957-11D2-A40B-0C5020524153}" ; Windows Tools. 28 | Run "::{21EC2020-3AEA-1069-A2DD-08002B30309D}" ; All Control Panel Items. 29 | Run "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}" ; This PC (formerly My Computer or Computer). 30 | Run "::{645FF040-5081-101B-9F08-00AA002F954E}" ; Recycle Bin. 31 | Run "::{450D8FBA-AD25-11D0-98A8-0800361B1103}\My Folder" ; Opens a folder that exists inside My Documents. 32 | Run A_MyDocuments "\My Folder" ; Same as the above on most systems.33 |
The availability and functionality of CLSIDs varies depending on the current OS, installed applications, and the command being used. The Availability column indicates the OS version range for which the CLSID can be used (XP, Vista, 7, 8, 10, 11). Additional CLSIDs may be found in the registry at HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID
.
By default, the table is sorted by CLSID in ascending order. To sort the table by another column or in another order, click on a column header.
35 |CLSID | 39 |Location | 40 |Availability | 41 |
---|---|---|
::{00020D75-0000-0000-C000-000000000046} | 46 |Inbox (Outlook) | 47 |XP-11 | 48 |
::{00028B00-0000-0000-C000-000000000046} | 51 |Microsoft Network | 52 |XP | 53 |
::{00C6D95F-329C-409A-81D7-C46C66EA7F33} | 56 |Default Location | 57 |7 | 58 |
::{0142E4D0-FB7A-11DC-BA4A-000FFE7AB428} | 61 |Biometric Devices | 62 |7 | 63 |
::{018D5C66-4533-4307-9B53-224DE2ED1FE6} | 66 |OneDrive | 67 |10-11 | 68 |
::{025A5937-A6BE-4686-A844-36FE4BEC8B6D} | 71 |Power Options | 72 |Vista-11 | 73 |
::{031E4825-7B94-4DC3-B131-E946B44C8DD5} | 76 |Libraries | 77 |7-11 | 78 |
::{04731B67-D933-450A-90E6-4ACD2E9408FE} | 81 |Desktop in Favorites | 82 |Vista-11 | 83 |
::{05D7B0F4-2121-4EFF-BF6B-ED3F69B894D9} | 86 |Notification Area Icons (append \SystemIcons for System Icons) | 87 |7-10 | 88 |
::{088E3905-0323-4B02-9826-5D99428E115F} | 91 |Downloads | 92 |10-11 | 93 |
::{0907616E-F5E6-48D8-9D61-A91C3D28106D} | 96 |Hyper-V Remote File Browsing | 97 |10-11 | 98 |
::{0DB7E03F-FC29-4DC6-9020-FF41B59E513A} | 101 |3D Objects | 102 |10 | 103 |
::{0DF44EAA-FF21-4412-828E-260A8728E7F1} | 106 |Taskbar Settings | 107 |XP-11 | 108 |
::{1206F5F1-0569-412C-8FEC-3204630DFB70} | 111 |Credential Manager | 112 |7-11 | 113 |
::{15EAE92E-F17A-4431-9F28-805E482DAFD4} | 116 |Get Programs | 117 |Vista-11 | 118 |
::{17CD9488-1228-4B2F-88CE-4298E93E0966} | 121 |Default Programs Default Apps |
122 | Vista-11 | 123 |
::{1CF1260C-4DD0-4EBB-811F-33C572699FDE} | 126 |Music | 127 |7-11 | 128 |
::{1F3427C8-5C10-4210-AA03-2EE45287D668} | 131 |User Pinned | 132 |7-11 | 133 |
::{1F4DE370-D627-11D1-BA4F-00A0C91EEDBA} | 136 |Network Computers | 137 |XP | 138 |
::{1FA9085F-25A2-489B-85D4-86326EEDCD87} | 141 |Manage Wireless Networks | 142 |Vista-7 | 143 |
::{208D2C60-3AEA-1069-A2D7-08002B30309D} | 146 |My Network Places | 147 |XP-11 | 148 |
::{20D04FE0-3AEA-1069-A2D8-08002B30309D} | 151 |My Computer Computer This PC |
152 | XP-11 | 153 |
::{21EC2020-3AEA-1069-A2DD-08002B30309D} | 156 |Control Panel All Control Panel Items |
157 | XP-11 | 158 |
::{2227A280-3AEA-1069-A2DE-08002B30309D} | 161 |Printers and Faxes | 162 |XP-11 | 163 |
::{22877A6D-37A1-461A-91B0-DBDA5AAEBC99} | 166 |Recent Places Recent Folders |
167 | Vista-11 | 168 |
::{241D7C96-F8BF-4F85-B01F-E2B043341A4B} | 171 |RemoteApp and Desktop Connections | 172 |7-11 | 173 |
::{24AD3AD4-A569-4530-98E1-AB02F9417AA8} | 176 |Pictures | 177 |10-11 | 178 |
::{2559A1F0-21D7-11D4-BDAF-00C04F60B9F0} | 181 |Search | 182 |XP-10 | 183 |
::{2559A1F3-21D7-11D4-BDAF-00C04F60B9F0} | 186 |Run | 187 |XP-11 | 188 |
::{2559A1F5-21D7-11D4-BDAF-00C04F60B9F0} | 191 |XP-11 | 193 ||
::{2559A1F7-21D7-11D4-BDAF-00C04F60B9F0} | 196 |Set Program Access and Defaults | 197 |XP-11 | 198 |
::{2559A1F8-21D7-11D4-BDAF-00C04F60B9F0} | 201 |Search (Modern) | 202 |8-11 | 203 |
::{26EE0668-A00A-44D7-9371-BEB064C98683} | 206 |Control Panel (Category view) | 207 |Vista-11 | 208 |
::{28803F59-3A75-4058-995F-4EE5503B023C} | 211 |Bluetooth Devices | 212 |Vista-11 | 213 |
::{289AF617-1CC3-42A6-926C-E6A863F0E3BA} | 216 |Media Servers | 217 |8-11 | 218 |
::{2965E715-EB66-4719-B53F-1672673BBEFA} | 221 |Results Folder | 222 |Vista-11 | 223 |
::{2E9E59C0-B437-4981-A647-9C34B9B90891} | 226 |Sync Setup Folder | 227 |Vista-11 | 228 |
::{3080F90D-D7AD-11D9-BD98-0000947B0257} | 231 |Show Desktop | 232 |Vista-11 | 233 |
::{3080F90E-D7AD-11D9-BD98-0000947B0257} | 236 |Window Switcher | 237 |Vista-11 | 238 |
::{323CA680-C24D-4099-B94D-446DD2D7249E} | 241 |Favorites | 242 |7-11 | 243 |
::{35786D3C-B075-49B9-88DD-029876E11C01} | 246 |Portable Devices | 247 |7-11 | 248 |
::{36EEF7DB-88AD-4E81-AD49-0E313F0C35F8} | 251 |Windows Update | 252 |Vista-8 | 253 |
::{374DE290-123F-4565-9164-39C4925E467B} | 256 |Downloads | 257 |8-11 | 258 |
::{37EFD44D-EF8D-41B1-940D-96973A50E9E0} | 261 |Windows Sidebar Properties Desktop Gadgets |
262 | Vista-8 | 263 |
::{38A98528-6CBF-4CA9-8DC0-B1E1D10F7B1B} | 266 |Connected To | 267 |Vista-8 | 268 |
::{3936E9E4-D92C-4EEE-A85A-BC16D5EA0819} | 271 |Frequent Folders | 272 |10-11 | 273 |
::{3ADD1653-EB32-4CB0-BBD7-DFA0ABB5ACCA} | 276 |Pictures | 277 |8-11 | 278 |
::{3DFDF296-DBEC-4FB4-81D1-6A3438BCF4DE} | 281 |Music | 282 |10-11 | 283 |
::{3F6BC534-DFA1-4AB4-AE54-EF25A74E0107} | 286 |System Restore | 287 |Vista-10 | 288 |
::{4026492F-2F69-46B8-B9BF-5654FC07E423} | 291 |Windows Firewall | 292 |Vista-10 | 293 |
::{40419485-C444-4567-851A-2DD7BFA1684D} | 296 |Phone and Modem | 297 |7-11 | 298 |
::{4234D49B-0245-4DF3-B780-3893943456E1} | 301 |Applications | 302 |8-11 | 303 |
::{4336A54D-038B-4685-AB02-99BB52D3FB8B} | 306 |Public Folder | 307 |Vista-11 | 308 |
::{437FF9C0-A07F-4FA0-AF80-84B6C6440A16} | 311 |Command Folder | 312 |Vista-11 | 313 |
::{450D8FBA-AD25-11D0-98A8-0800361B1103} | 316 |My Documents | 317 |XP-11 | 318 |
::{48E7CAAB-B918-4E58-A94D-505519C795DC} | 321 |Start Menu Folder | 322 |XP-Vista | 323 |
::{5224F545-A443-4859-BA23-7B5A95BDC8EF} | 326 |People Near Me | 327 |Vista-7 | 328 |
::{5399E694-6CE5-4D6C-8FCE-1D8870FDCBA0} | 331 |Control Panel | 332 |Vista-11 | 333 |
::{58E3C745-D971-4081-9034-86E34B30836A} | 336 |Speech Recognition | 337 |Vista-11 | 338 |
::{59031A47-3F72-44A7-89C5-5595FE6B30EE} | 341 |User Folder | 342 |Vista-11 | 343 |
::{5EA4F148-308C-46D7-98A9-49041B1DD468} | 346 |Mobility Center | 347 |Vista-11 | 348 |
::{60632754-C523-4B62-B45C-4172DA012619} | 351 |User Accounts | 352 |Vista-11 | 353 |
::{62D8ED13-C9D0-4CE8-A914-47DD628FB1B0} | 356 |Region and Language | 357 |7-11 | 358 |
::{645FF040-5081-101B-9F08-00AA002F954E} | 361 |Recycle Bin | 362 |XP-11 | 363 |
::{67718415-C450-4F3C-BF8A-B487642DC39B} | 366 |Windows Features | 367 |Vista-10 | 368 |
::{679F85CB-0220-4080-B29B-5540CC05AAB6} | 371 |Quick access | 372 |10-11 | 373 |
::{67CA7650-96E6-4FDD-BB43-A8E774F73A57} | 376 |HomeGroup | 377 |7-11 | 378 |
::{6C8EEC18-8D75-41B2-A177-8831D59D2D50} | 381 |Mouse Properties | 382 |7-11 | 383 |
::{6DFD7C5C-2451-11D3-A299-00C04F8EF6AF} | 386 |Folder Options | 387 |XP-11 | 388 |
::{7007ACC7-3202-11D1-AAD2-00805FC1270E} | 391 |Network Connections | 392 |XP-11 | 393 |
::{725BE8F7-668E-4C7B-8F90-46BDB0936430} | 396 |Keyboard Properties | 397 |7-11 | 398 |
::{74246BFC-4C96-11D0-ABEF-0020AF6B0B7A} | 401 |Device Manager | 402 |Vista-11 | 403 |
::{78CB147A-98EA-4AA6-B0DF-C8681F69341C} | 406 |Windows Cardspace | 407 |Vista-7 | 408 |
::{78F3955E-3B90-4184-BD14-5397C15F1EFC} | 411 |Performance Information and Tools | 412 |Vista-7 | 413 |
::{7A9D77BD-5403-11D2-8785-2E0420524153} | 416 |User Accounts (netplwiz) | 417 |XP-11 | 418 |
::{7B81BE6A-CE2B-4676-A29E-EB907A5126C5} | 421 |Programs and Features | 422 |Vista-11 | 423 |
::{7BD29E00-76C1-11CF-9DD0-00A0C9034933} | 426 |Temporary Internet Files | 427 |XP | 428 |
::{7BE9D83C-A729-4D97-B5A7-1B7313C39E0A} | 431 |Programs Folder | 432 |XP-8 | 433 |
::{80F3F1D5-FECA-45F3-BC32-752C152E456E} | 436 |Tablet PC Settings | 437 |7-10 | 438 |
::{85BBD920-42A0-1069-A2E4-08002B30309D} | 441 |Briefcase | 442 |XP | 443 |
::{863AA9FD-42DF-457B-8E4D-0DE1B8015C60} | 446 |Printers | 447 |7-11 | 448 |
::{871C5380-42A0-1069-A2EA-08002B30309D} | 451 |Internet Explorer | 452 |XP-10 | 453 |
::{87D66A43-7B11-4A28-9811-C86EE395ACF7} | 456 |Indexing Options | 457 |7-11 | 458 |
::{8E908FC9-BECC-40F6-915B-F4CA0E70D03D} | 461 |Network and Sharing Center | 462 |Vista-11 | 463 |
::{93412589-74D4-4E4E-AD0E-E0CB621440FD} | 466 |Font Settings | 467 |7-11 | 468 |
::{9343812E-1C37-4A49-A12E-4B2D810D956B} | 471 |Search Results | 472 |Vista-10 | 473 |
::{96AE8D84-A250-4520-95A5-A47A7E3C548B} | 476 |Parental Controls | 477 |7-8 | 478 |
::{992CFFA0-F557-101A-88EC-00DD010CCC48} | 481 |Network Connections | 482 |XP-11 | 483 |
::{9C60DE1E-E5FC-40F4-A487-460851A8D915} | 486 |AutoPlay | 487 |Vista-11 | 488 |
::{9C73F5E5-7AE7-4E32-A8E8-8D23B85255BF} | 491 |Sync Center | 492 |Vista-11 | 493 |
::{9FE63AFD-59CF-4419-9775-ABCC3849F861} | 496 |Recovery | 497 |7-10 | 498 |
::{A0275511-0E86-4ECA-97C2-ECD8F1221D08} | 501 |Infrared | 502 |7-10 | 503 |
::{A0953C92-50DC-43BF-BE83-3742FED03C9C} | 506 |Videos | 507 |8-11 | 508 |
::{A304259D-52B8-4526-8B1A-A1D6CECC8243} | 511 |iSCCI Initiator | 512 |Vista-11 | 513 |
::{A3DD4F92-658A-410F-84FD-6FBBBEF2FFFE} | 516 |Internet Options | 517 |7-11 | 518 |
::{A6482830-08EB-41E2-84C1-73920C2BADB9} | 521 |Removable Storage Devices | 522 |8-11 | 523 |
::{A8A91A66-3A7D-4424-8D24-04E180695C7A} | 526 |Devices and Printers | 527 |7-11 | 528 |
::{A8CDFF1C-4878-43BE-B5FD-F8091C1C60D0} | 531 |Documents | 532 |8-11 | 533 |
::{AFDB1F70-2A4C-11D2-9039-00C04F8EEB3E} | 536 |Offline Files Folder | 537 |XP-10 | 538 |
::{B155BDF8-02F0-451E-9A26-AE317CFD7779} | 541 |delegate folder that appears in Computer | 542 |Vista-10 | 543 |
::{B2C761C6-29BC-4F19-9251-E6195265BAF1} | 546 |Color Management | 547 |Vista-11 | 548 |
::{B4BFCC3A-DB2C-424C-B029-7FE99A87C641} | 551 |Desktop | 552 |8-11 | 553 |
::{B4FB3F98-C1EA-428D-A78A-D1F5659CBA93} | 556 |Other Users Folder Media Streaming Options |
557 | 7-11 | 558 |
::{B98A2BEA-7D42-4558-8BD1-832F41BAC6FD} | 561 |Backup and Restore | 562 |Vista-7 | 563 |
::{BB06C0E4-D293-4F75-8A90-CB05B6477EEE} | 566 |System | 567 |Vista-11 | 568 |
::{BB64F8A7-BEE7-4E1A-AB8D-7D8273F7FDB6} | 571 |Action Center Security and Maintenance (append \pageSettings for Problem Reporting Settings) |
572 | 7-11 | 573 |
::{BD84B380-8CA2-1069-AB1D-08000948F534} | 576 |Fonts | 577 |XP-11 | 578 |
::{BDEADF00-C265-11D0-BCED-00A0C90AB50F} | 581 |Web Folders | 582 |XP | 583 |
::{BE122A0E-4503-11DA-8BDE-F66BAD1E3F3A} | 586 |Windows Anytime Upgrade | 587 |Vista-8 | 588 |
::{C555438B-3C23-4769-A71F-B6D3D9B6053A} | 591 |Display (DPI) | 592 |7-8 | 593 |
::{C58C4893-3BE0-4B45-ABB5-A63E4B8C8651} | 596 |Troubleshooting | 597 |7-10 | 598 |
::{CB1B7F8C-C50A-4176-B604-9E24DEE8D4D1} | 601 |Welcome Center Getting Started |
602 | Vista-7 | 603 |
::{D17D1D6D-CC3F-4815-8FE3-607E7D5D10B3} | 606 |Text to Speech | 607 |7-11 | 608 |
::{D20EA4E1-3957-11D2-A40B-0C5020524152} | 611 |Fonts | 612 |XP-Vista | 613 |
::{D20EA4E1-3957-11D2-A40B-0C5020524153} | 616 |Administrative Tools Windows Tools |
617 | XP-11 | 618 |
::{D3162B92-9365-467A-956B-92703ACA08AF} | 621 |Documents | 622 |10-11 | 623 |
::{D34A6CA6-62C2-4C34-8A7C-14709C1AD938} | 626 |Common Places FS Folder | 627 |Vista-11 | 628 |
::{D4480A50-BA28-11D1-8E75-00C04FA31A86} | 631 |Add Network Place | 632 |XP-11 | 633 |
::{D450A8A1-9568-45C7-9C0E-B4F9FB4537BD} | 636 |Installed Updates | 637 |Vista-11 | 638 |
::{D555645E-D4F8-4C29-A827-D93C859C4F2A} | 641 |Ease of Access Center | 642 |Vista-11 | 643 |
::{D6277990-4C6A-11CF-8D87-00AA0060F5BF} | 646 |Scheduled Tasks | 647 |XP | 648 |
::{D8559EB9-20C0-410E-BEDA-7ED416AECC2A} | 651 |Windows Defender | 652 |Vista-8 | 653 |
::{D9EF8727-CAC2-4E60-809E-86F80A666C91} | 656 |BitLocker Drive Encryption | 657 |Vista-10 | 658 |
::{E211B736-43FD-11D1-9EFB-0000F8757FCD} | 661 |Scanners and Cameras | 662 |XP | 663 |
::{E2E7934B-DCE5-43C4-9576-7FE4F75E7480} | 666 |Date and Time | 667 |7-11 | 668 |
::{E44E5D18-0652-4508-A4E2-8A090067BCB0} | 671 |Default Programs Default Apps |
672 | Vista-11 | 673 |
::{E7DE9B1A-7533-4556-9484-B26FB486475E} | 676 |Network Map | 677 |Vista-7 | 678 |
::{E95A4861-D57A-4BE1-AD0F-35267E261739} | 681 |Windows SideShow | 682 |Vista-7 | 683 |
::{E9950154-C418-419E-A90A-20C5287AE24B} | 686 |Location and Other Sensors Location Settings |
687 | 7-10 | 688 |
::{ECDB0924-4208-451E-8EE0-373C0956DE16} | 691 |Work Folders | 692 |8-10 | 693 |
::{ED228FDF-9EA8-4870-83B1-96B02CFE0D52} | 696 |Games Explorer | 697 |Vista-10 | 698 |
::{ED50FC29-B964-48A9-AFB3-15EBB9B97F36} | 701 |printhood delegate folder | 702 |Vista-10 | 703 |
::{ED7BA470-8E54-465E-825C-99712043E01C} | 706 |All Tasks (God Mode) | 707 |Vista-11 | 708 |
::{ED834ED6-4B5A-4BFE-8F11-A626DCB6A921} | 711 |Personalization | 712 |Vista-10 | 713 |
::{F02C1A0D-BE21-4350-88B0-7367FC96EF3C} | 716 |Network | 717 |Vista-11 | 718 |
::{F2DDFC82-8F12-4CDD-B7DC-D4FE1425AA4D} | 721 |Sound | 722 |7-11 | 723 |
::{F6B6E965-E9B2-444B-9286-10C9152EDBC5} | 726 |File History | 727 |8-10 | 728 |
::{F82DF8F7-8B9F-442E-A48C-818EA735FF9B} | 731 |Pen and Touch | 732 |7-10 | 733 |
::{F86FA3AB-70D2-4FC7-9C99-FCBF05467F3A} | 736 |Videos | 737 |10-11 | 738 |
::{F8C2AB3B-17BC-41DA-9758-339D7DBF2D88} | 741 |Previous Versions Results Folder | 742 |7-11 | 743 |
::{F942C606-0914-47AB-BE56-1321B8035096} | 746 |Storage Spaces | 747 |8-10 | 748 |
::{FF393560-C2A7-11CF-BFF4-444553540000} | 751 |History | 752 |XP | 753 |
18 | | Color name | 19 |RGB value | 20 |
---|---|---|
23 | | Black | 24 |000000 | 25 |
28 | | Silver | 29 |C0C0C0 | 30 |
33 | | Gray | 34 |808080 | 35 |
38 | | White | 39 |FFFFFF | 40 |
43 | | Maroon | 44 |800000 | 45 |
48 | | Red | 49 |FF0000 | 50 |
53 | | Purple | 54 |800080 | 55 |
58 | | Fuchsia | 59 |FF00FF | 60 |
63 | | Green | 64 |008000 | 65 |
68 | | Lime | 69 |00FF00 | 70 |
73 | | Olive | 74 |808000 | 75 |
78 | | Yellow | 79 |FFFF00 | 80 |
83 | | Navy | 84 |000080 | 85 |
88 | | Blue | 89 |0000FF | 90 |
93 | | Teal | 94 |008080 | 95 |
98 | | Aqua | 99 |00FFFF | 100 |
DPI scaling is a function performed either by the operating system or by the application, to increase the visual size of content proportionate to the "dots per inch" setting of the display. Generally it allows content to appear at the same physical size on systems with different display resolutions, or to at least be usable on very high-resolution displays. Sometimes a user may increase the DPI setting just to make content larger and more comfortable to read.
16 |A_ScreenDPI typically returns the DPI setting which the primary display had at the time the script started. This is known as the "system DPI", although processes started at different times can have different values.
17 |There are two types of DPI scaling that relate to AutoHotkey: Gui DPI Scaling and OS DPI Scaling.
18 | 19 |Automatic scaling is performed by the Gui and GuiControl methods/properties by default, so that GUI scripts with hard-coded positions, sizes and margins will tend to scale as appropriate on high DPI screens. If this interferes with the script, or if the script will do its own scaling, the automatic scaling can be disabled. For more details, see the -DPIScale option.
21 | 22 |For applications which are not DPI-aware, the operating system automatically scales coordinates passed to and returned from certain system functions. This type of scaling typically affects AutoHotkey in two scenarios:
24 |The exact scaling done depends on which system function is being called, the DPI awareness of the script and potentially the DPI awareness of the target window.
29 | 30 |On Windows 8.1 and later, secondary screens can have different DPI settings, and "per-monitor DPI-aware" applications are expected to scale their windows according to the DPI of whichever screen they are currently on, adapting dynamically when the window moves between screens.
32 |For applications which are not per-monitor DPI-aware, the system performs bitmap scaling to allow windows to change sizes when they move between screens, and hides this from the application by reporting coordinates and sizes scaled to the global DPI setting that the application expects to have. For instance, on an 11 inch 4K screen, a GUI designed to display at 96 dpi (100 %) would be almost impossible to use, whereas upscaling it by 200 % would make it usable.
33 |AutoHotkey v2.0 is not designed to perform per-monitor scaling, and therefore has not been marked as per-monitor DPI-aware. This is a boon, for instance, when moving a GUI window between a large external screen with 100 % DPI and a smaller screen with 200 % DPI. However, automatic scaling does have negative implications.
34 |In order of the system's automatic scaling to work, system functions such as MoveWindow and GetWindowRect automatically scale the coordinates that they accept or return. When AutoHotkey uses these functions to work with external windows, this often produces unexpected results if the coordinates are not on the primary screen. To add further confusion, some functions scale coordinates based on which screen the script's last active window was displayed on.
35 | 36 |On Windows 10 version 1607 and later, the SetThreadDpiAwarenessContext system function can be used to change the program's DPI awareness setting at runtime. For instance, enabling per-monitor DPI awareness disables the scaling performed by the system, so built-in functions such as WinMove and WinGetPos will accept or return coordinates in pixels, untouched by DPI scaling. However, if a GUI is sized for a screen with 100 % DPI and then moved to a screen with 200 % DPI, it will not adjust automatically, and may be very hard to use.
38 |To enable per-monitor DPI awareness, call the following function prior to using functions that are normally affected by DPI scaling:
39 |DllCall("SetThreadDpiAwarenessContext", "ptr", -3, "ptr")40 |
On Windows 10 version 1703 and later, -3 can be replaced with -4 to enable the "Per Monitor v2" mode. This enables scaling of dialogs, menus, tooltips and some other things. However, it also causes the non-client area (title bar) to scale, which may cause the window's client area to be too small unless the script is designed to adjust for it (such as by responding to the WM_DPICHANGED message). This can be avoided by setting the context to -3 before creating the GUI, but -4 before creating any tooltips, menus or dialogs.
41 | 42 |When the window procedure for a window is called by the system, it automatically sets the current DPI awareness context to whichever context was in use when the window was created. The context for a new script thread therefore depends on whether it was launched directly from AutoHotkey's message loop or via a window procedure.
44 |A per-monitor DPI aware GUI window is expected to adjust automatically when it receives a WM_DPICHANGED message. AutoHotkey v2.0 GUI windows do not respond to this message by default. If correctly implementing this type of dynamic scaling is too difficult, a simpler alternative is to temporarily disable per-monitor DPI awareness immediately prior to creating the GUI. For example:
53 |; Set the "system DPI aware" mode which is the default in AutoHotkey v2.0: 54 | try dac := DllCall("SetThreadDpiAwarenessContext", 'ptr', -2, 'ptr') 55 | ; Create the GUI, which will permanently be "system DPI aware": 56 | MyGui := Gui() 57 | ; Restore the previous mode for any subsequent function calls: 58 | IsSet(dac) && DllCall("SetThreadDpiAwarenessContext", 'ptr', dac, 'ptr') 59 |60 |
The additional lines have no effect if the OS does not support SetThreadDpiAwarenessContext or the program was already in system DPI aware mode.
61 |If only some of the GUI's controls do not scale well, system DPI aware (or DPI unaware) controls can be hosted on a per-monitor DPI aware window. Mixed hosting must be enabled prior to creating the window (requires Windows 10 version 1803 or later):
62 |; Create a GUI window which can host less-aware child windows: 63 | try dhb := DllCall("SetThreadDpiHostingBehavior", 'int', 1) 64 | MyGui := Gui() 65 | IsSet(dhb) && DllCall("SetThreadDpiHostingBehavior", 'int', dhb) 66 | 67 | ; Add a "system DPI aware" control: 68 | try dac := DllCall("SetThreadDpiAwarenessContext", 'ptr', -2, 'ptr') 69 | MyListView := MyGui.AddListView() 70 | IsSet(dac) && DllCall("SetThreadDpiAwarenessContext", 'ptr', dac, 'ptr') 71 |72 | 73 |
Per-monitor DPI awareness can be enabled process-wide by setting the "dpiAware" and "dpiAwareness" elements in the compiled script's manifest (an embedded XML resource). For details of the proper use and effect of these settings, see Setting default awareness with the application manifest. For example, the manifest in AutoHotkey v2.0.19 includes the following:
75 |<v3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings" 76 | xmlns:ws2="http://schemas.microsoft.com/SMI/2016/WindowsSettings"> 77 | <dpiAware>true</dpiAware> 78 | <ws2:longPathAware>true</ws2:longPathAware> 79 | </v3:windowsSettings>80 |
As explained in the Microsoft documentation, it may be desirable to include both "dpiAware" and "dpiAwareness", which belong to different XML namespaces. As "longPathAware" and "dpiAwareness" belong to the same namespace, the XML can be optimized by moving some things around. The following enables per-monitor DPI awareness (v2 if available, otherwise v1):
81 |<v3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings"> 82 | <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware> 83 | <dpiAwareness>PerMonitorV2</dpiAwareness> 84 | <longPathAware>true</longPathAware> 85 | </v3:windowsSettings>86 | 87 |
The program's default DPI awareness can be overridden by compatibility settings, which can be set in the properties of an AutoHotkey executable file, in the properties of a shortcut file, or by setting the __COMPAT_LAYER
environment variable to include the keyword DpiUnaware
or the keyword HighDpiAware
. Enabling DPI awareness using this method may have unwanted effects; in particular, MsgBox windows may not adjust automatically when moved between screens.
Any text editor can be used to edit an AutoHotkey script, but editors which are (or can be configured to be) more AutoHotkey-aware tend to make reading, editing and testing scripts much easier. AutoHotkey-aware editors may provide:
17 |Recommendations:
24 |SciTE4AutoHotkey is a custom version of the text editor known as SciTE. Its features include:
31 |SciTE4AutoHotkey can be found here: https://www.autohotkey.com/scite4ahk/
42 | 43 |Visual Studio Code can be configured with a high level of support for AutoHotkey by installing extensions.
45 |AutoHotkey2 Language Support provides many features, including:
46 |Additional notes:
57 |vscode-autohotkey-debug provides support for interactive debugging of v1 and v2 scripts.
62 | 63 |Notepad++ can be configured to support the following features:
65 |See Setup Notepad++ for AutoHotkey for instructions.
72 | 73 |Notepad4 supports the following for AutoHotkey v2 by default:
75 |It is available here: https://github.com/zufuliu/notepad4
83 | 84 |For help finding or configuring other editors, try the Editors sub-forum.
86 |To get an editor added to this page, post in the Suggestions sub-forum or open an Issue or Pull Request at GitHub.
87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /docs/misc/EscapeChar.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |The escape character `
(back-tick or grave accent) is used to indicate that the character immediately following it should be interpreted differently than it normally would. This character is at the upper left corner of most English keyboards.
In AutoHotkey the following escape sequences can be used:
16 | 17 |Sequence | 20 |Result | 21 |
---|---|
`` |
24 | ` (literal accent; i.e. two consecutive escape characters result in a single literal character) |
25 |
`; |
28 |
29 |
Note: It is not necessary to escape a semicolon which has any character other than space or tab to its immediate left, since it would not be interpreted as a comment anyway. 31 | |
32 |
`: |
35 | : (literal colon). This is necessary only in a hotstring's triggering abbreviation. |
36 |
`{ |
39 | { (keyboard key). This is only valid, and is required, when remapping a key to {. | 40 |
`n |
43 | newline (linefeed/LF) | 44 |
`r |
47 | carriage return (CR) | 48 |
`b |
51 | backspace | 52 |
`t |
55 | tab (the more typical horizontal variety) | 56 |
`s |
59 | space | 60 |
`v |
63 | vertical tab -- corresponds to Ascii value 11. It can also be manifest in some applications by typing Ctrl+K. | 64 |
`a |
67 | alert (bell) -- corresponds to Ascii value 7. It can also be manifest in some applications by typing Ctrl+G. | 68 |
`f |
71 | formfeed -- corresponds to Ascii value 12. It can also be manifest in some applications by typing Ctrl+L. | 72 |
`" or `' |
75 | Single-quote marks (') and double-quote marks (") function identically, except that a string enclosed in single-quote marks can contain literal double-quote marks and vice versa. Therefore, to include an actual quote mark inside a literal string, escape the quote mark or enclose the string in the opposite type of quote mark. For example: Var := "The color `"red`" was found." or Var := 'The color "red" was found.' . |
76 |
Reports a multi-line string. The lines are separated by a linefeed character.
82 |MsgBox "Line 1`nLine 2"83 |
For use with Gui.SetFont. The "Exists Since" column indicates the OS version with which the font was introduced. Common monospaced (fixed-width) fonts in this table are Cascadia Mono, Consolas, Courier, Courier New, Fixedsys, Lucida Console, and Terminal. The availability of some fonts may depend on the language of the operating system.
41 |Recommend Fonts are highlighted in yellow. Note that fonts recommended here are fonts which are readable and have been introduced with Windows Vista or earlier. Using such fonts ensures that they are displayed on most operating systems.
42 |By default, the table is sorted by font names in ascending order. To sort the table by another column or in another order, click on a column header.
43 | 44 |Font Name | 48 |Mainly Designed For | 49 |Exists Since | 50 |
---|---|---|
Aharoni | 55 |Hebrew | 56 |2000 | 57 |
Aldhabi | 60 |Arabic | 61 |8 | 62 |
Andalus | 65 |Arabic | 66 |2000 | 67 |
Angsana New | 70 |Thai | 71 |XP | 72 |
AngsanaUPC | 75 |Thai | 76 |XP | 77 |
Aparajita | 80 |Indic | 81 |7 | 82 |
Arabic Typesetting | 85 |Arabic | 86 |Vista | 87 |
Arial | 90 |Latin, Greek, Cyrillic | 91 |95 | 92 |
Arial Black | 95 |Latin, Greek, Cyrillic | 96 |98 | 97 |
Arial Nova | 100 |Latin, Greek, Cyrillic | 101 |10 | 102 |
Bahnschrift | 105 |Latin | 106 |10 | 107 |
Batang | 110 |Korean | 111 |2000 | 112 |
BatangChe | 115 |Korean | 116 |Vista | 117 |
BIZ UDGothic | 120 |Japanese | 121 |10 | 122 |
BIZ UDMincho Medium | 125 |Japanese | 126 |10 | 127 |
BIZ UDPGothic | 130 |Japanese | 131 |10 | 132 |
Browallia New | 135 |Thai | 136 |2000 | 137 |
BrowalliaUPC | 140 |Thai | 141 |2000 | 142 |
Calibri | 145 |Latin, Greek, Cyrillic | 146 |Vista | 147 |
Calibri Light | 150 |Latin, Greek, Cyrillic | 151 |8 | 152 |
Cambria | 155 |Latin, Greek, Cyrillic | 156 |Vista | 157 |
Cambria Math | 160 |Symbols | 161 |Vista | 162 |
Candara | 165 |Latin, Greek, Cyrillic | 166 |Vista | 167 |
Cascadia Code | 170 |Other | 171 |11 | 172 |
Cascadia Mono | 175 |Other | 176 |11 | 177 |
Comic Sans MS | 180 |Latin, Greek, Cyrillic | 181 |95 | 182 |
Consolas | 185 |Latin, Greek, Cyrillic | 186 |Vista | 187 |
Constantia | 190 |Latin, Greek, Cyrillic | 191 |Vista | 192 |
Corbel | 195 |Latin, Greek, Cyrillic | 196 |Vista | 197 |
Cordia New | 200 |Thai | 201 |2000 | 202 |
CordiaUPC | 205 |Thai | 206 |2000 | 207 |
Courier | 210 |Latin, Greek, Cyrillic | 211 |95 | 212 |
Courier New | 215 |Latin, Greek, Cyrillic | 216 |95 | 217 |
DaunPenh | 220 |Other | 221 |Vista | 222 |
David | 225 |Hebrew | 226 |2000 | 227 |
DengXian | 230 |Chinese | 231 |10 | 232 |
DFKai-SB | 235 |Chinese | 236 |2000 | 237 |
DilleniaUPC | 240 |Thai | 241 |2000 | 242 |
DokChampa | 245 |Other | 246 |Vista | 247 |
Dotum | 250 |Korean | 251 |Vista | 252 |
DotumChe | 255 |Korean | 256 |Vista | 257 |
Ebrima | 260 |African | 261 |7 | 262 |
Estrangelo Edessa | 265 |Other | 266 |XP | 267 |
EucrosiaUPC | 270 |Thai | 271 |2000 | 272 |
Euphemia | 275 |Other | 276 |Vista | 277 |
FangSong | 280 |Chinese | 281 |Vista | 282 |
Fixedsys | 285 |Latin | 286 |95 | 287 |
Franklin Gothic Medium | 290 |Latin, Greek, Cyrillic | 291 |XP | 292 |
FrankRuehl | 295 |Hebrew | 296 |2000 | 297 |
FreesiaUPC | 300 |Thai | 301 |2000 | 302 |
Gabriola | 305 |Latin, Greek, Cyrillic | 306 |7 | 307 |
Gadugi | 310 |Other | 311 |8 | 312 |
Gautami | 315 |Other | 316 |XP | 317 |
Georgia | 320 |Latin, Greek, Cyrillic | 321 |2000 | 322 |
Georgia Pro | 325 |Latin, Greek, Cyrillic | 326 |10 | 327 |
Gill Sans Nova | 330 |Latin, Greek, Cyrillic | 331 |10 | 332 |
Gisha | 335 |Hebrew | 336 |Vista | 337 |
Gulim | 340 |Korean | 341 |2000 | 342 |
GulimChe | 345 |Korean | 346 |Vista | 347 |
Gungsuh | 350 |Korean | 351 |Vista | 352 |
GungsuhChe | 355 |Korean | 356 |Vista | 357 |
HoloLens MDL2 Assets | 360 |Symbols | 361 |10 | 362 |
Impact | 365 |Latin, Greek, Cyrillic | 366 |98 | 367 |
Ink Free | 370 |Other | 371 |10 | 372 |
IrisUPC | 375 |Thai | 376 |2000 | 377 |
Iskoola Pota | 380 |Other | 381 |Vista | 382 |
JasmineUPC | 385 |Thai | 386 |2000 | 387 |
Javanese Text | 390 |Javanese | 391 |8.1 | 392 |
KaiTi | 395 |Chinese | 396 |2000 | 397 |
Kalinga | 400 |Other | 401 |Vista | 402 |
Kartika | 405 |Other | 406 |XP | 407 |
Khmer UI | 410 |Other | 411 |7 | 412 |
KodchiangUPC | 415 |Thai | 416 |2000 | 417 |
Kokila | 420 |Other | 421 |7 | 422 |
Lao UI | 425 |Other | 426 |7 | 427 |
Latha | 430 |Indic | 431 |XP | 432 |
Leelawadee | 435 |Thai | 436 |Vista | 437 |
Leelawadee UI | 440 |Thai | 441 |8.1 | 442 |
Levenim MT | 445 |Hebrew | 446 |98 | 447 |
LilyUPC | 450 |Thai | 451 |2000 | 452 |
Lucida Console | 455 |Latin, Greek, Cyrillic | 456 |98 | 457 |
Lucida Sans | 460 |Latin, Greek, Cyrillic | 461 |98 | 462 |
Lucida Sans Unicode | 465 |Latin, Greek, Cyrillic | 466 |98 | 467 |
Malgun Gothic | 470 |Korean | 471 |Vista | 472 |
Mangal | 475 |Indic | 476 |XP | 477 |
Marlett | 480 |Symbols | 481 |95 | 482 |
Meiryo | 485 |Japanese | 486 |Vista | 487 |
Meiryo UI | 490 |Japanese | 491 |7 | 492 |
Microsoft Himalaya | 495 |Other | 496 |Vista | 497 |
Microsoft JhengHei | 500 |Chinese | 501 |Vista | 502 |
Microsoft JhengHei UI | 505 |Chinese | 506 |8 | 507 |
Microsoft New Tai Lue | 510 |Other | 511 |7 | 512 |
Microsoft PhagsPa | 515 |Other | 516 |7 | 517 |
Microsoft Sans Serif | 520 |Latin, Greek, Cyrillic | 521 |2000 | 522 |
Microsoft Tai Le | 525 |Other | 526 |7 | 527 |
Microsoft Uighur | 530 |Other | 531 |Vista | 532 |
Microsoft YaHei | 535 |Chinese | 536 |Vista | 537 |
Microsoft YaHei UI | 540 |Chinese | 541 |8 | 542 |
Microsoft Yi Baiti | 545 |Other | 546 |Vista | 547 |
MingLiU | 550 |Chinese | 551 |Vista | 552 |
MingLiU_HKSCS | 555 |Chinese | 556 |Vista | 557 |
MingLiU_HKSCS-ExtB | 560 |Chinese | 561 |Vista | 562 |
MingLiU-ExtB | 565 |Chinese | 566 |Vista | 567 |
Miriam | 570 |Hebrew | 571 |2000 | 572 |
Miriam Fixed | 575 |Hebrew | 576 |2000 | 577 |
Modern | 580 |Latin | 581 |95 | 582 |
Mongolian Baiti | 585 |Other | 586 |Vista | 587 |
MoolBoran | 590 |Other | 591 |Vista | 592 |
MS Gothic | 595 |Japanese | 596 |2000 | 597 |
MS Mincho | 600 |Japanese | 601 |2000 | 602 |
MS PGothic | 605 |Japanese | 606 |Vista | 607 |
MS PMincho | 610 |Japanese | 611 |Vista | 612 |
MS Serif | 615 |Latin | 616 |95 | 617 |
MS Sans Serif | 620 |Latin | 621 |95 | 622 |
MS UI Gothic | 625 |Japanese | 626 |Vista | 627 |
MV Boli | 630 |Other | 631 |XP | 632 |
Myanmar Text | 635 |Other | 636 |8 | 637 |
Narkisim | 640 |Hebrew | 641 |2000 | 642 |
Neue Haas Grotesk Text Pro | 645 |Latin | 646 |10 | 647 |
Nirmala UI | 650 |Indic | 651 |8 | 652 |
NSimSun | 655 |Chinese | 656 |Vista | 657 |
Nyala | 660 |African | 661 |Vista | 662 |
Palatino Linotype | 665 |Latin, Greek, Cyrillic | 666 |2000 | 667 |
Plantagenet Cherokee | 670 |Other | 671 |Vista | 672 |
PMingLiU | 675 |Chinese | 676 |2000 | 677 |
PMingLiU-ExtB | 680 |Chinese | 681 |Vista | 682 |
Raavi | 685 |Indic | 686 |XP | 687 |
Rockwell Nova | 690 |Latin, Greek, Cyrillic | 691 |10 | 692 |
Rod | 695 |Hebrew | 696 |2000 | 697 |
Roman | 700 |Latin | 701 |98 | 702 |
Sakkal Majalla | 705 |Arabic | 706 |7 | 707 |
Sanskrit Text | 710 |Other | 711 |10 | 712 |
Script | 715 |Latin | 716 |98 | 717 |
Segoe Fluent Icons | 720 |Symbols | 721 |11 | 722 |
Segoe MDL2 Assets | 725 |Symbols | 726 |10 | 727 |
Segoe Print | 730 |Latin, Greek, Cyrillic | 731 |Vista | 732 |
Segoe Script | 735 |Latin, Greek, Cyrillic | 736 |Vista | 737 |
Segoe UI | 740 |Latin, Greek, Cyrillic | 741 |Vista | 742 |
Segoe UI Emoji | 745 |Symbols | 746 |10 | 747 |
Segoe UI Historic | 750 |Other | 751 |10 | 752 |
Segoe UI Variable | 755 |Other | 756 |11 | 757 |
Segoe UI Symbol | 760 |Symbols | 761 |7 | 762 |
Shonar Bangla | 765 |Indic | 766 |7 | 767 |
Shruti | 770 |Indic | 771 |XP | 772 |
SimHei | 775 |Chinese | 776 |2000 | 777 |
Simplified Arabic | 780 |Arabic | 781 |2000 | 782 |
Simplified Arabic Fixed | 785 |Arabic | 786 |2000 | 787 |
SimSun | 790 |Chinese | 791 |2000 | 792 |
SimSun-ExtB | 795 |Chinese | 796 |Vista | 797 |
Sitka Banner | 800 |Latin, Greek, Cyrillic | 801 |8.1 | 802 |
Sitka Display | 805 |Latin, Greek, Cyrillic | 806 |8.1 | 807 |
Sitka Heading | 810 |Latin, Greek, Cyrillic | 811 |8.1 | 812 |
Sitka Small | 815 |Latin, Greek, Cyrillic | 816 |8.1 | 817 |
Sitka Subheading | 820 |Latin, Greek, Cyrillic | 821 |8.1 | 822 |
Sitka Text | 825 |Latin, Greek, Cyrillic | 826 |8.1 | 827 |
Small Fonts | 830 |Latin | 831 |95 | 832 |
Sylfaen | 835 |Other | 836 |XP | 837 |
Symbol | 840 |Symbols | 841 |95 | 842 |
System | 845 |Latin | 846 |95 | 847 |
Tahoma | 850 |Latin, Greek, Cyrillic | 851 |95 | 852 |
Terminal | 855 |Latin | 856 |95 | 857 |
Times New Roman | 860 |Latin, Greek, Cyrillic | 861 |95 | 862 |
Traditional Arabic | 865 |Arabic | 866 |2000 | 867 |
Trebuchet MS | 870 |Latin, Greek, Cyrillic | 871 |2000 | 872 |
Tunga | 875 |Indic | 876 |XP | 877 |
UD Digi Kyokasho N-B | 880 |Japanese | 881 |10 | 882 |
UD Digi Kyokasho NK-B | 885 |Japanese | 886 |10 | 887 |
UD Digi Kyokasho NK-R | 890 |Japanese | 891 |10 | 892 |
UD Digi Kyokasho NP-B | 895 |Japanese | 896 |10 | 897 |
UD Digi Kyokasho NP-R | 900 |Japanese | 901 |10 | 902 |
UD Digi Kyokasho N-R | 905 |Japanese | 906 |10 | 907 |
Urdu Typesetting | 910 |Arabic | 911 |8 | 912 |
Utsaah | 915 |Indic | 916 |7 | 917 |
Vani | 920 |Indic | 921 |7 | 922 |
Verdana | 925 |Latin, Greek, Cyrillic | 926 |95 | 927 |
Verdana Pro | 930 |Latin, Greek, Cyrillic | 931 |10 | 932 |
Vijaya | 935 |Indic | 936 |7 | 937 |
Vrinda | 940 |Indic | 941 |XP | 942 |
Webdings | 945 |Symbols | 946 |98 | 947 |
Wingdings | 950 |Symbols | 951 |95 | 952 |
Yu Gothic | 955 |Japanese | 956 |8.1 | 957 |
Yu Gothic UI | 960 |Japanese | 961 |8.1 | 962 |
Yu Mincho | 965 |Japanese | 966 |8.1 | 967 |
"Function object" usually means any of the following:
16 |Function objects can be used with the following:
22 |To determine whether an object appears to be callable, use one of the following:
40 |Value.HasMethod()
works with all AutoHotkey values and objects by default, but allows HasMethod to be overridden for some objects or classes. For COM objects, this will typically fail (throw an exception or produce the wrong result) unless the COM object is actually an AutoHotkey object from another process.HasMethod(Value)
works with all AutoHotkey values and objects and cannot be overridden, but will return false if the presence of a Call method cannot be determined. An exception is thrown if Value is a ComObject.User-defined function objects must define a Call method containing the implementation of the "function".
48 |class YourClassName { 49 | Call(a, b) { ; Declare parameters as needed, or an array*. 50 | ;... 51 | return c 52 | } 53 | ;... 54 | } 55 |56 |
This applies to instances of YourClassName, such as the object returned by YourClassName()
. Replacing Call
with static Call
would instead override what occurs when YourClassName itself is called.
The following example defines a function array which can be called; when called, it calls each element of the array in turn.
59 |class FuncArrayType extends Array { 60 | Call(params*) { 61 | ; Call a list of functions. 62 | for fn in this 63 | fn(params*) 64 | } 65 | } 66 | 67 | ; Create an array of functions. 68 | funcArray := FuncArrayType() 69 | ; Add some functions to the array (can be done at any point). 70 | funcArray.Push(One) 71 | funcArray.Push(Two) 72 | ; Create an object which uses the array as a method. 73 | obj := {method: funcArray} 74 | ; Call the method (and consequently both One and Two). 75 | obj.method("2nd") 76 | ; Call it as a function. 77 | (obj.method)("1st", "2nd") 78 | 79 | One(param1, param2) { 80 | ListVars 81 | MsgBox 82 | } 83 | Two(param1, param2) { 84 | ListVars 85 | MsgBox 86 | }87 | 88 |
Acts like a function, but just passes predefined parameters to another function.
90 |There are two ways that BoundFunc objects can be created:
91 |BoundFunc objects can be called as shown in the example below. When the BoundFunc is called, it calls the function or method to which it is bound, passing a combination of bound parameters and the caller's parameters. Unbound parameter positions are assigned positions from the caller's parameter list, left to right. For example:
96 |fn := RealFn.Bind(1) ; Bind first parameter only 97 | fn(2) ; Shows "1, 2" 98 | fn.Call(3) ; Shows "1, 3" 99 | 100 | fn := RealFn.Bind( , 1) ; Bind second parameter only 101 | fn(2, 0) ; Shows "2, 1, 0" 102 | fn.Call(3) ; Shows "3, 1" 103 | fn(, 4) ; Error: 'a' was omitted 104 | 105 | RealFn(a, b, c?) { 106 | MsgBox a ", " b (IsSet(c) ? ", " c : "") 107 | }108 |
ObjBindMethod can be used to bind to a method even when it isn't possible to retrieve a reference to the method itself. For example:
109 |Shell := ComObject("Shell.Application") 110 | RunBox := ObjBindMethod(Shell, "FileRun") 111 | ; Show the Run dialog. 112 | RunBox113 |
For a more complex example, see SetTimer.
114 |Other properties and methods are inherited from Func, but do not reflect the properties of the target function or method (which is not required to be implemented as a function). The BoundFunc acts as an anonymous variadic function with no other formal parameters, similar to the fat arrow function below:
115 |Func_Bind(fn, bound_args*) { 116 | return (args*) => (args.InsertAt(1, bound_args*), fn(args*)) 117 | }118 | 119 | 120 | 121 | -------------------------------------------------------------------------------- /docs/misc/ImageHandles.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |
To use an icon or bitmap handle in place of an image filename, use the following syntax:
16 |HBITMAP:BitmapHandle 17 | HICON:IconHandle18 |
Replace BitmapHandle or IconHandle with the actual handle value. For example, "hicon:" handle
, where handle is a variable containing an icon handle.
The following things support this syntax:
20 |A bitmap or icon handle is a numeric value which identifies a bitmap or icon in memory. The majority of scripts never need to deal with handles, as in most cases AutoHotkey takes care of loading the image from file and freeing it when it is no longer needed. The syntax shown above is intended for use when the script obtains an icon or bitmap handle from another source, such as by sending the WM_GETICON message to a window. It can also be used in combination with LoadPicture to avoid loading an image from file multiple times.
29 |By default, AutoHotkey treats the handle as though it loaded the image from file - for example, a bitmap used on a Picture control is deleted when the GUI is destroyed, and an image will generally be deleted immediately if it needs to be resized. To avoid this, put an asterisk between the colon and handle. For example: "hbitmap:*" handle
. With the exception of ImageSearch, this forces the function to take a copy of the image.
Shows a menu of the first n files matching a pattern, and their icons.
34 |pattern := A_ScriptDir "\*" 35 | n := 15 36 | 37 | ; Create a menu. 38 | Fmenu := Menu() 39 | 40 | ; Allocate memory for a SHFILEINFOW struct. 41 | fileinfo := Buffer(fisize := A_PtrSize + 688) 42 | 43 | Loop Files, pattern, "FD" 44 | { 45 | ; Add a menu item for each file. 46 | Fmenu.Add(A_LoopFileName, (*) => "") ; Do nothing. 47 | 48 | ; Get the file's icon. 49 | if DllCall("shell32\SHGetFileInfoW", "WStr", A_LoopFileFullPath 50 | , "UInt", 0, "Ptr", fileinfo, "UInt", fisize, "UInt", 0x100) 51 | { 52 | hicon := NumGet(fileinfo, 0, "Ptr") 53 | ; Set the menu item's icon. 54 | Fmenu.SetIcon(A_Index "&", "HICON:" hicon) 55 | ; Because we used ":" and not ":*", the icon will be automatically 56 | ; freed when the program exits or if the menu or item is deleted. 57 | } 58 | } 59 | until A_Index = n 60 | Fmenu.Show() 61 |62 |
See also LoadPicture example #1.
64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /docs/misc/Labels.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |A label identifies a line of code, and can be used as a Goto target or to specify a loop to break out of or continue. A label consist of a name followed by a colon:
26 |this_is_a_label:27 |
Aside from whitespace and comments, no other code can be written on the same line as a label.
28 |Names: Label names are not case-sensitive (for ASCII letters), and may consist of letters, numbers, underscore and non-ASCII characters. For example: MyListView, Menu_File_Open, and outer_loop.
29 |Scope: Each function has its own list of local labels. Inside a function, only that function's labels are visible/accessible to the script.
30 |Target: The target of a label is the next line of executable code. Executable code includes functions, assignments, expressions and blocks, but not directives, labels, hotkeys or hotstrings. In the following example, run_notepad_1
and run_notepad_2
both point at the Run
line:
run_notepad_1: 32 | run_notepad_2: 33 | Run "notepad" 34 | return35 |
Execution: Like directives, labels have no effect when reached during normal execution.
36 | 37 |Hotkey and hotstring definitions look similar to labels, but are not labels.
39 |Hotkeys consist of a hotkey followed by double-colon.
40 |^a::41 |
Hotstrings consist of a colon, zero or more options, another colon, an abbreviation and double-colon.
42 |:*:btw::43 | 44 |
In some cases a variable can be used in place of a label name. In such cases, the name stored in the variable is used to locate the target label. However, performance is slightly reduced because the target label must be "looked up" each time rather than only once when the script is first loaded.
46 | 47 |A label can also be used to identify a loop for the Continue and Break statements. This allows the script to easily continue or break out of any number of nested loops.
49 | 50 |Functions, IsLabel, Goto, Break, Continue
52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /docs/misc/Languages.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |The following list contains language names, each of which is associated with a language code (also known as a locale identifier, LCID) that can be contained in the A_Language variable. The language code itself is the last four digits on the left side of the first comma below. For example, if A_Language contains 0436, the system's default language is Afrikaans (South Africa).
16 |Note: Codes that contain letters might use either uppercase or lowercase.
17 |You can compare A_Language directly to one or more of the 4-digit codes below; for example: if (A_Language = "0436")
. Alternatively, you can paste the entire list into a script and then access the name of the current language as demonstrated at the bottom of the list.
LCID := Map( 19 | "0036", "Afrikaans", ; af 20 | "0436", "Afrikaans (South Africa)", ; af-ZA 21 | "001C", "Albanian", ; sq 22 | "041C", "Albanian (Albania)", ; sq-AL 23 | "0484", "Alsatian (France)", ; gsw-FR 24 | "005E", "Amharic", ; am 25 | "045E", "Amharic (Ethiopia)", ; am-ET 26 | "0001", "Arabic", ; ar 27 | "1401", "Arabic (Algeria)", ; ar-DZ 28 | "3C01", "Arabic (Bahrain)", ; ar-BH 29 | "0C01", "Arabic (Egypt)", ; ar-EG 30 | "0801", "Arabic (Iraq)", ; ar-IQ 31 | "2C01", "Arabic (Jordan)", ; ar-JO 32 | "3401", "Arabic (Kuwait)", ; ar-KW 33 | "3001", "Arabic (Lebanon)", ; ar-LB 34 | "1001", "Arabic (Libya)", ; ar-LY 35 | "1801", "Arabic (Morocco)", ; ar-MA 36 | "2001", "Arabic (Oman)", ; ar-OM 37 | "4001", "Arabic (Qatar)", ; ar-QA 38 | "0401", "Arabic (Saudi Arabia)", ; ar-SA 39 | "2801", "Arabic (Syria)", ; ar-SY 40 | "1C01", "Arabic (Tunisia)", ; ar-TN 41 | "3801", "Arabic (United Arab Emirates)", ; ar-AE 42 | "2401", "Arabic (Yemen)", ; ar-YE 43 | "002B", "Armenian", ; hy 44 | "042B", "Armenian (Armenia)", ; hy-AM 45 | "004D", "Assamese", ; as 46 | "044D", "Assamese (India)", ; as-IN 47 | "002C", "Azerbaijani", ; az 48 | "742C", "Azerbaijani (Cyrillic)", ; az-Cyrl 49 | "082C", "Azerbaijani (Cyrillic, Azerbaijan)", ; az-Cyrl-AZ 50 | "782C", "Azerbaijani (Latin)", ; az-Latn 51 | "042C", "Azerbaijani (Latin, Azerbaijan)", ; az-Latn-AZ 52 | "0045", "Bangla", ; bn 53 | "0845", "Bangla (Bangladesh)", ; bn-BD 54 | "006D", "Bashkir", ; ba 55 | "046D", "Bashkir (Russia)", ; ba-RU 56 | "002D", "Basque", ; eu 57 | "042D", "Basque (Basque)", ; eu-ES 58 | "0023", "Belarusian", ; be 59 | "0423", "Belarusian (Belarus)", ; be-BY 60 | "0445", "Bengali (India)", ; bn-IN 61 | "781A", "Bosnian", ; bs 62 | "641A", "Bosnian (Cyrillic)", ; bs-Cyrl 63 | "201A", "Bosnian (Cyrillic, Bosnia and Herzegovina)", ; bs-Cyrl-BA 64 | "681A", "Bosnian (Latin)", ; bs-Latn 65 | "141A", "Bosnian (Latin, Bosnia & Herzegovina)", ; bs-Latn-BA 66 | "007E", "Breton", ; br 67 | "047E", "Breton (France)", ; br-FR 68 | "0002", "Bulgarian", ; bg 69 | "0402", "Bulgarian (Bulgaria)", ; bg-BG 70 | "0055", "Burmese", ; my 71 | "0455", "Burmese (Myanmar)", ; my-MM 72 | "0003", "Catalan", ; ca 73 | "0403", "Catalan (Catalan)", ; ca-ES 74 | "005F", "Central Atlas Tamazight", ; tzm 75 | "045F", "Central Atlas Tamazight (Arabic, Morocco)", ; tzm-Arab-MA 76 | "7C5F", "Central Atlas Tamazight (Latin)", ; tzm-Latn 77 | "085F", "Central Atlas Tamazight (Latin, Algeria)", ; tzm-Latn-DZ 78 | "785F", "Central Atlas Tamazight (Tifinagh)", ; tzm-Tfng 79 | "105F", "Central Atlas Tamazight (Tifinagh, Morocco)", ; tzm-Tfng-MA 80 | "0092", "Central Kurdish", ; ku 81 | "7C92", "Central Kurdish", ; ku-Arab 82 | "0492", "Central Kurdish (Iraq)", ; ku-Arab-IQ 83 | "005C", "Cherokee", ; chr 84 | "7C5C", "Cherokee", ; chr-Cher 85 | "045C", "Cherokee (Cherokee, United States)", ; chr-Cher-US 86 | "7804", "Chinese", ; zh 87 | "0004", "Chinese (Simplified)", ; zh-Hans 88 | "0804", "Chinese (Simplified, China)", ; zh-CN 89 | "1004", "Chinese (Simplified, Singapore)", ; zh-SG 90 | "7C04", "Chinese (Traditional)", ; zh-Hant 91 | "0C04", "Chinese (Traditional, Hong Kong SAR)", ; zh-HK 92 | "1404", "Chinese (Traditional, Macao SAR)", ; zh-MO 93 | "0404", "Chinese (Traditional, Taiwan)", ; zh-TW 94 | "0083", "Corsican", ; co 95 | "0483", "Corsican (France)", ; co-FR 96 | "001A", "Croatian", ; hr 97 | "101A", "Croatian (Bosnia & Herzegovina)", ; hr-BA 98 | "041A", "Croatian (Croatia)", ; hr-HR 99 | "0005", "Czech", ; cs 100 | "0405", "Czech (Czechia)", ; cs-CZ 101 | "0006", "Danish", ; da 102 | "0406", "Danish (Denmark)", ; da-DK 103 | "0065", "Divehi", ; dv 104 | "0465", "Divehi (Maldives)", ; dv-MV 105 | "0013", "Dutch", ; nl 106 | "0813", "Dutch (Belgium)", ; nl-BE 107 | "0413", "Dutch (Netherlands)", ; nl-NL 108 | "0C51", "Dzongkha (Bhutan)", ; dz-BT 109 | "0066", "Edo", ; bin 110 | "0466", "Edo (Nigeria)", ; bin-NG 111 | "0009", "English", ; en 112 | "0C09", "English (Australia)", ; en-AU 113 | "2809", "English (Belize)", ; en-BZ 114 | "1009", "English (Canada)", ; en-CA 115 | "2409", "English (Caribbean)", ; en-029 116 | "3C09", "English (Hong Kong SAR)", ; en-HK 117 | "4009", "English (India)", ; en-IN 118 | "3809", "English (Indonesia)", ; en-ID 119 | "1809", "English (Ireland)", ; en-IE 120 | "2009", "English (Jamaica)", ; en-JM 121 | "4409", "English (Malaysia)", ; en-MY 122 | "1409", "English (New Zealand)", ; en-NZ 123 | "3409", "English (Philippines)", ; en-PH 124 | "4809", "English (Singapore)", ; en-SG 125 | "1C09", "English (South Africa)", ; en-ZA 126 | "2C09", "English (Trinidad & Tobago)", ; en-TT 127 | "4C09", "English (United Arab Emirates)", ; en-AE 128 | "0809", "English (United Kingdom)", ; en-GB 129 | "0409", "English (United States)", ; en-US 130 | "3009", "English (Zimbabwe)", ; en-ZW 131 | "0025", "Estonian", ; et 132 | "0425", "Estonian (Estonia)", ; et-EE 133 | "0038", "Faroese", ; fo 134 | "0438", "Faroese (Faroe Islands)", ; fo-FO 135 | "0064", "Filipino", ; fil 136 | "0464", "Filipino (Philippines)", ; fil-PH 137 | "000B", "Finnish", ; fi 138 | "040B", "Finnish (Finland)", ; fi-FI 139 | "000C", "French", ; fr 140 | "080C", "French (Belgium)", ; fr-BE 141 | "2C0C", "French (Cameroon)", ; fr-CM 142 | "0C0C", "French (Canada)", ; fr-CA 143 | "1C0C", "French (Caribbean)", ; fr-029 144 | "300C", "French (Côte d’Ivoire)", ; fr-CI 145 | "040C", "French (France)", ; fr-FR 146 | "3C0C", "French (Haiti)", ; fr-HT 147 | "140C", "French (Luxembourg)", ; fr-LU 148 | "340C", "French (Mali)", ; fr-ML 149 | "180C", "French (Monaco)", ; fr-MC 150 | "380C", "French (Morocco)", ; fr-MA 151 | "200C", "French (Réunion)", ; fr-RE 152 | "280C", "French (Senegal)", ; fr-SN 153 | "100C", "French (Switzerland)", ; fr-CH 154 | "240C", "French Congo (DRC)", ; fr-CD 155 | "0067", "Fulah", ; ff 156 | "7C67", "Fulah (Latin)", ; ff-Latn 157 | "0467", "Fulah (Latin, Nigeria)", ; ff-Latn-NG 158 | "0867", "Fulah (Latin, Senegal)", ; ff-Latn-SN 159 | "0056", "Galician", ; gl 160 | "0456", "Galician (Galician)", ; gl-ES 161 | "0037", "Georgian", ; ka 162 | "0437", "Georgian (Georgia)", ; ka-GE 163 | "0007", "German", ; de 164 | "0C07", "German (Austria)", ; de-AT 165 | "0407", "German (Germany)", ; de-DE 166 | "1407", "German (Liechtenstein)", ; de-LI 167 | "1007", "German (Luxembourg)", ; de-LU 168 | "0807", "German (Switzerland)", ; de-CH 169 | "0008", "Greek", ; el 170 | "0408", "Greek (Greece)", ; el-GR 171 | "0074", "Guarani", ; gn 172 | "0474", "Guarani (Paraguay)", ; gn-PY 173 | "0047", "Gujarati", ; gu 174 | "0447", "Gujarati (India)", ; gu-IN 175 | "0068", "Hausa", ; ha 176 | "7C68", "Hausa (Latin)", ; ha-Latn 177 | "0468", "Hausa (Latin, Nigeria)", ; ha-Latn-NG 178 | "0075", "Hawaiian", ; haw 179 | "0475", "Hawaiian (United States)", ; haw-US 180 | "000D", "Hebrew", ; he 181 | "040D", "Hebrew (Israel)", ; he-IL 182 | "0039", "Hindi", ; hi 183 | "0439", "Hindi (India)", ; hi-IN 184 | "000E", "Hungarian", ; hu 185 | "040E", "Hungarian (Hungary)", ; hu-HU 186 | "0069", "Ibibio", ; ibb 187 | "0469", "Ibibio (Nigeria)", ; ibb-NG 188 | "000F", "Icelandic", ; is 189 | "040F", "Icelandic (Iceland)", ; is-IS 190 | "0070", "Igbo", ; ig 191 | "0470", "Igbo (Nigeria)", ; ig-NG 192 | "0021", "Indonesian", ; id 193 | "0421", "Indonesian (Indonesia)", ; id-ID 194 | "005D", "Inuktitut", ; iu 195 | "7C5D", "Inuktitut (Latin)", ; iu-Latn 196 | "085D", "Inuktitut (Latin, Canada)", ; iu-Latn-CA 197 | "785D", "Inuktitut (Syllabics)", ; iu-Cans 198 | "045D", "Inuktitut (Syllabics, Canada)", ; iu-Cans-CA 199 | "003C", "Irish", ; ga 200 | "083C", "Irish (Ireland)", ; ga-IE 201 | "0034", "isiXhosa", ; xh 202 | "0434", "isiXhosa (South Africa)", ; xh-ZA 203 | "0035", "isiZulu", ; zu 204 | "0435", "isiZulu (South Africa)", ; zu-ZA 205 | "0010", "Italian", ; it 206 | "0410", "Italian (Italy)", ; it-IT 207 | "0810", "Italian (Switzerland)", ; it-CH 208 | "0011", "Japanese", ; ja 209 | "0411", "Japanese (Japan)", ; ja-JP 210 | "006F", "Kalaallisut", ; kl 211 | "046F", "Kalaallisut (Greenland)", ; kl-GL 212 | "004B", "Kannada", ; kn 213 | "044B", "Kannada (India)", ; kn-IN 214 | "0071", "Kanuri", ; kr 215 | "0471", "Kanuri (Latin, Nigeria)", ; kr-Latn-NG 216 | "0060", "Kashmiri", ; ks 217 | "0460", "Kashmiri (Arabic)", ; ks-Arab 218 | "1000", "Kashmiri (Arabic)", ; ks-Arab-IN 219 | "0860", "Kashmiri (Devanagari)", ; ks-Deva-IN 220 | "003F", "Kazakh", ; kk 221 | "043F", "Kazakh (Kazakhstan)", ; kk-KZ 222 | "0053", "Khmer", ; km 223 | "0453", "Khmer (Cambodia)", ; km-KH 224 | "0087", "Kinyarwanda", ; rw 225 | "0487", "Kinyarwanda (Rwanda)", ; rw-RW 226 | "0041", "Kiswahili", ; sw 227 | "0441", "Kiswahili (Kenya)", ; sw-KE 228 | "0057", "Konkani", ; kok 229 | "0457", "Konkani (India)", ; kok-IN 230 | "0012", "Korean", ; ko 231 | "0412", "Korean (Korea)", ; ko-KR 232 | "0040", "Kyrgyz", ; ky 233 | "0440", "Kyrgyz (Kyrgyzstan)", ; ky-KG 234 | "0086", "Kʼicheʼ", ; quc 235 | "7C86", "Kʼicheʼ (Latin)", ; quc-Latn 236 | "0486", "Kʼicheʼ (Latin, Guatemala)", ; quc-Latn-GT 237 | "0054", "Lao", ; lo 238 | "0454", "Lao (Laos)", ; lo-LA 239 | "0076", "Latin", ; la 240 | "0476", "Latin (Vatican City)", ; la-VA 241 | "0026", "Latvian", ; lv 242 | "0426", "Latvian (Latvia)", ; lv-LV 243 | "0027", "Lithuanian", ; lt 244 | "0427", "Lithuanian (Lithuania)", ; lt-LT 245 | "7C2E", "Lower Sorbian", ; dsb 246 | "082E", "Lower Sorbian (Germany)", ; dsb-DE 247 | "006E", "Luxembourgish", ; lb 248 | "046E", "Luxembourgish (Luxembourg)", ; lb-LU 249 | "002F", "Macedonian", ; mk 250 | "042F", "Macedonian (North Macedonia)", ; mk-MK 251 | "003E", "Malay", ; ms 252 | "083E", "Malay (Brunei)", ; ms-BN 253 | "043E", "Malay (Malaysia)", ; ms-MY 254 | "004C", "Malayalam", ; ml 255 | "044C", "Malayalam (India)", ; ml-IN 256 | "003A", "Maltese", ; mt 257 | "043A", "Maltese (Malta)", ; mt-MT 258 | "0058", "Manipuri", ; mni 259 | "0458", "Manipuri (Bangla, India)", ; mni-IN 260 | "0081", "Maori", ; mi 261 | "0481", "Maori (New Zealand)", ; mi-NZ 262 | "007A", "Mapuche", ; arn 263 | "047A", "Mapuche (Chile)", ; arn-CL 264 | "004E", "Marathi", ; mr 265 | "044E", "Marathi (India)", ; mr-IN 266 | "007C", "Mohawk", ; moh 267 | "047C", "Mohawk (Canada)", ; moh-CA 268 | "0050", "Mongolian", ; mn 269 | "7850", "Mongolian", ; mn-Cyrl 270 | "0450", "Mongolian (Mongolia)", ; mn-MN 271 | "7C50", "Mongolian (Traditional Mongolian)", ; mn-Mong 272 | "0850", "Mongolian (Traditional Mongolian, China)", ; mn-Mong-CN 273 | "0C50", "Mongolian (Traditional Mongolian, Mongolia)", ; mn-Mong-MN 274 | "0061", "Nepali", ; ne 275 | "0861", "Nepali (India)", ; ne-IN 276 | "0461", "Nepali (Nepal)", ; ne-NP 277 | "003B", "Northern Sami", ; se 278 | "0014", "Norwegian", ; no 279 | "7C14", "Norwegian Bokmål", ; nb 280 | "0414", "Norwegian Bokmål (Norway)", ; nb-NO 281 | "7814", "Norwegian Nynorsk", ; nn 282 | "0814", "Norwegian Nynorsk (Norway)", ; nn-NO 283 | "0082", "Occitan", ; oc 284 | "0482", "Occitan (France)", ; oc-FR 285 | "0048", "Odia", ; or 286 | "0448", "Odia (India)", ; or-IN 287 | "0072", "Oromo", ; om 288 | "0472", "Oromo (Ethiopia)", ; om-ET 289 | "0079", "Papiamento", ; pap 290 | "0479", "Papiamento (Caribbean)", ; pap-029 291 | "0063", "Pashto", ; ps 292 | "0463", "Pashto (Afghanistan)", ; ps-AF 293 | "0029", "Persian", ; fa 294 | "008C", "Persian", ; fa 295 | "048C", "Persian (Afghanistan)", ; fa-AF 296 | "0429", "Persian (Iran)", ; fa-IR 297 | "0015", "Polish", ; pl 298 | "0415", "Polish (Poland)", ; pl-PL 299 | "0016", "Portuguese", ; pt 300 | "0416", "Portuguese (Brazil)", ; pt-BR 301 | "0816", "Portuguese (Portugal)", ; pt-PT 302 | "05FE", "Pseudo (Pseudo Asia)", ; qps-ploca 303 | "09FF", "Pseudo (Pseudo Mirrored)", ; qps-plocm 304 | "0901", "Pseudo (Pseudo Selfhost)", ; qps-Latn-x-sh 305 | "0501", "Pseudo (Pseudo)", ; qps-ploc 306 | "0046", "Punjabi", ; pa 307 | "7C46", "Punjabi", ; pa-Arab 308 | "0446", "Punjabi (India)", ; pa-IN 309 | "0846", "Punjabi (Pakistan)", ; pa-Arab-PK 310 | "006B", "Quechua", ; quz 311 | "046B", "Quechua (Bolivia)", ; quz-BO 312 | "086B", "Quechua (Ecuador)", ; quz-EC 313 | "0C6B", "Quechua (Peru)", ; quz-PE 314 | "0018", "Romanian", ; ro 315 | "0818", "Romanian (Moldova)", ; ro-MD 316 | "0418", "Romanian (Romania)", ; ro-RO 317 | "0017", "Romansh", ; rm 318 | "0417", "Romansh (Switzerland)", ; rm-CH 319 | "0019", "Russian", ; ru 320 | "0819", "Russian (Moldova)", ; ru-MD 321 | "0419", "Russian (Russia)", ; ru-RU 322 | "0085", "Sakha", ; sah 323 | "0485", "Sakha (Russia)", ; sah-RU 324 | "703B", "Sami (Inari)", ; smn 325 | "7C3B", "Sami (Lule)", ; smj 326 | "743B", "Sami (Skolt)", ; sms 327 | "783B", "Sami (Southern)", ; sma 328 | "243B", "Sami, Inari (Finland)", ; smn-FI 329 | "103B", "Sami, Lule (Norway)", ; smj-NO 330 | "143B", "Sami, Lule (Sweden)", ; smj-SE 331 | "0C3B", "Sami, Northern (Finland)", ; se-FI 332 | "043B", "Sami, Northern (Norway)", ; se-NO 333 | "083B", "Sami, Northern (Sweden)", ; se-SE 334 | "203B", "Sami, Skolt (Finland)", ; sms-FI 335 | "183B", "Sami, Southern (Norway)", ; sma-NO 336 | "1C3B", "Sami, Southern (Sweden)", ; sma-SE 337 | "004F", "Sanskrit", ; sa 338 | "044F", "Sanskrit (India)", ; sa-IN 339 | "0091", "Scottish Gaelic", ; gd 340 | "0491", "Scottish Gaelic (United Kingdom)", ; gd-GB 341 | "7C1A", "Serbian", ; sr 342 | "6C1A", "Serbian (Cyrillic)", ; sr-Cyrl 343 | "1C1A", "Serbian (Cyrillic, Bosnia and Herzegovina)", ; sr-Cyrl-BA 344 | "301A", "Serbian (Cyrillic, Montenegro)", ; sr-Cyrl-ME 345 | "0C1A", "Serbian (Cyrillic, Serbia and Montenegro (Former))", ; sr-Cyrl-CS 346 | "281A", "Serbian (Cyrillic, Serbia)", ; sr-Cyrl-RS 347 | "701A", "Serbian (Latin)", ; sr-Latn 348 | "181A", "Serbian (Latin, Bosnia & Herzegovina)", ; sr-Latn-BA 349 | "2C1A", "Serbian (Latin, Montenegro)", ; sr-Latn-ME 350 | "081A", "Serbian (Latin, Serbia and Montenegro (Former))", ; sr-Latn-CS 351 | "241A", "Serbian (Latin, Serbia)", ; sr-Latn-RS 352 | "0030", "Sesotho", ; st 353 | "0430", "Sesotho (South Africa)", ; st-ZA 354 | "006C", "Sesotho sa Leboa", ; nso 355 | "046C", "Sesotho sa Leboa (South Africa)", ; nso-ZA 356 | "0032", "Setswana", ; tn 357 | "0832", "Setswana (Botswana)", ; tn-BW 358 | "0432", "Setswana (South Africa)", ; tn-ZA 359 | "0059", "Sindhi", ; sd 360 | "7C59", "Sindhi", ; sd-Arab 361 | "0459", "Sindhi (Devanagari, India)", ; sd-Deva-IN 362 | "0859", "Sindhi (Pakistan)", ; sd-Arab-PK 363 | "005B", "Sinhala", ; si 364 | "045B", "Sinhala (Sri Lanka)", ; si-LK 365 | "001B", "Slovak", ; sk 366 | "041B", "Slovak (Slovakia)", ; sk-SK 367 | "0024", "Slovenian", ; sl 368 | "0424", "Slovenian (Slovenia)", ; sl-SI 369 | "0077", "Somali", ; so 370 | "0477", "Somali (Somalia)", ; so-SO 371 | "000A", "Spanish", ; es 372 | "2C0A", "Spanish (Argentina)", ; es-AR 373 | "400A", "Spanish (Bolivia)", ; es-BO 374 | "340A", "Spanish (Chile)", ; es-CL 375 | "240A", "Spanish (Colombia)", ; es-CO 376 | "140A", "Spanish (Costa Rica)", ; es-CR 377 | "5C0A", "Spanish (Cuba)", ; es-CU 378 | "1C0A", "Spanish (Dominican Republic)", ; es-DO 379 | "300A", "Spanish (Ecuador)", ; es-EC 380 | "440A", "Spanish (El Salvador)", ; es-SV 381 | "100A", "Spanish (Guatemala)", ; es-GT 382 | "480A", "Spanish (Honduras)", ; es-HN 383 | "580A", "Spanish (Latin America)", ; es-419 384 | "080A", "Spanish (Mexico)", ; es-MX 385 | "4C0A", "Spanish (Nicaragua)", ; es-NI 386 | "180A", "Spanish (Panama)", ; es-PA 387 | "3C0A", "Spanish (Paraguay)", ; es-PY 388 | "280A", "Spanish (Peru)", ; es-PE 389 | "500A", "Spanish (Puerto Rico)", ; es-PR 390 | "0C0A", "Spanish (Spain, International Sort)", ; es-ES 391 | "040A", "Spanish (Spain, Traditional Sort)", ; es-ES_tradnl 392 | "540A", "Spanish (United States)", ; es-US 393 | "380A", "Spanish (Uruguay)", ; es-UY 394 | "200A", "Spanish (Venezuela)", ; es-VE 395 | "001D", "Swedish", ; sv 396 | "081D", "Swedish (Finland)", ; sv-FI 397 | "041D", "Swedish (Sweden)", ; sv-SE 398 | "0084", "Swiss German", ; gsw 399 | "005A", "Syriac", ; syr 400 | "045A", "Syriac (Syria)", ; syr-SY 401 | "0028", "Tajik", ; tg 402 | "7C28", "Tajik (Cyrillic)", ; tg-Cyrl 403 | "0428", "Tajik (Cyrillic, Tajikistan)", ; tg-Cyrl-TJ 404 | "0049", "Tamil", ; ta 405 | "0449", "Tamil (India)", ; ta-IN 406 | "0849", "Tamil (Sri Lanka)", ; ta-LK 407 | "0044", "Tatar", ; tt 408 | "0444", "Tatar (Russia)", ; tt-RU 409 | "004A", "Telugu", ; te 410 | "044A", "Telugu (India)", ; te-IN 411 | "001E", "Thai", ; th 412 | "041E", "Thai (Thailand)", ; th-TH 413 | "0051", "Tibetan", ; bo 414 | "0451", "Tibetan (China)", ; bo-CN 415 | "0073", "Tigrinya", ; ti 416 | "0873", "Tigrinya (Eritrea)", ; ti-ER 417 | "0473", "Tigrinya (Ethiopia)", ; ti-ET 418 | "001F", "Turkish", ; tr 419 | "041F", "Turkish (Turkey)", ; tr-TR 420 | "0042", "Turkmen", ; tk 421 | "0442", "Turkmen (Turkmenistan)", ; tk-TM 422 | "0022", "Ukrainian", ; uk 423 | "0422", "Ukrainian (Ukraine)", ; uk-UA 424 | "002E", "Upper Sorbian", ; hsb 425 | "042E", "Upper Sorbian (Germany)", ; hsb-DE 426 | "0020", "Urdu", ; ur 427 | "0820", "Urdu (India)", ; ur-IN 428 | "0420", "Urdu (Pakistan)", ; ur-PK 429 | "0080", "Uyghur", ; ug 430 | "0480", "Uyghur (China)", ; ug-CN 431 | "0043", "Uzbek", ; uz 432 | "7843", "Uzbek (Cyrillic)", ; uz-Cyrl 433 | "0843", "Uzbek (Cyrillic, Uzbekistan)", ; uz-Cyrl-UZ 434 | "7C43", "Uzbek (Latin)", ; uz-Latn 435 | "0443", "Uzbek (Latin, Uzbekistan)", ; uz-Latn-UZ 436 | "0803", "Valencian (Spain)", ; ca-ES-valencia 437 | "0033", "Venda", ; ve 438 | "0433", "Venda (South Africa)", ; ve-ZA 439 | "002A", "Vietnamese", ; vi 440 | "042A", "Vietnamese (Vietnam)", ; vi-VN 441 | "0052", "Welsh", ; cy 442 | "0452", "Welsh (United Kingdom)", ; cy-GB 443 | "0062", "Western Frisian", ; fy 444 | "0462", "Western Frisian (Netherlands)", ; fy-NL 445 | "0088", "Wolof", ; wo 446 | "0488", "Wolof (Senegal)", ; wo-SN 447 | "0031", "Xitsonga", ; ts 448 | "0431", "Xitsonga (South Africa)", ; ts-ZA 449 | "0078", "Yi", ; ii 450 | "0478", "Yi (China)", ; ii-CN 451 | "003D", "Yiddish", ; yi 452 | "043D", "Yiddish (World)", ; yi-001 453 | "006A", "Yoruba", ; yo 454 | "046A", "Yoruba (Nigeria)" ; yo-NG 455 | ) 456 | 457 | the_language := LCID[A_Language] ; Get the name of the system's default language. 458 | MsgBox the_language ; Display the language name.459 |
The following script was used to create the list above:
460 |G := Gui() 461 | LV := G.Add("ListView", "w500 r20", ["LCID", "Display Name", "Locale Name"]) 462 | G.Show() 463 | 464 | LOCALE_ALLOW_NEUTRAL_NAMES := 0x08000000 465 | LOCALE_SENGLISHDISPLAYNAME := 0x72 466 | LOCALE_SLOCALIZEDDISPLAYNAME := 0x2 467 | loop 0xFFFF 468 | { 469 | LCID := Format("{:04X}", A_Index) 470 | if (LCID ~= "(04|08|0C|14|20|24|28|2C|30|34|38|3C|40|44|48|4C)00") 471 | continue ; Skip default and transient LCIDs. 472 | LocaleName := LCIDToLocaleName(A_Index, LOCALE_ALLOW_NEUTRAL_NAMES) 473 | if not LocaleName 474 | continue ; Skip unknown LCIDs. 475 | DisplayName := GetLocaleInfo(LocaleName, LOCALE_SENGLISHDISPLAYNAME) 476 | ; DisplayName := GetLocaleInfo(LocaleName, LOCALE_SLOCALIZEDDISPLAYNAME) 477 | LV.Add(, LCID, DisplayName, LocaleName) 478 | ; A_Clipboard .= LCID "`t" DisplayName "`t" LocaleName "`n" 479 | } 480 | LV.ModifyCol() ; Auto-size each column to fit its contents. 481 | 482 | LCIDToLocaleName(LCID, Flags := 0) 483 | { 484 | reqBufSize := DllCall("LCIDToLocaleName", "UInt", LCID, "Ptr", 0, "UInt", 0, "UInt", Flags) 485 | out := Buffer(reqBufSize*2) 486 | DllCall("LCIDToLocaleName", "UInt", LCID, "Ptr", out, "UInt", out.Size, "UInt", Flags) 487 | return StrGet(out) 488 | } 489 | 490 | GetLocaleInfo(LocaleName, LCType) 491 | { 492 | reqBufSize := DllCall("GetLocaleInfoEx", "Str", LocaleName, "UInt", LCType, "Ptr", 0, "UInt", 0) 493 | out := Buffer(reqBufSize*2) 494 | DllCall("GetLocaleInfoEx", "Str", LocaleName, "UInt", LCType, "Ptr", out, "UInt", out.Size) 495 | return StrGet(out) 496 | }497 | 498 | 499 | 500 | -------------------------------------------------------------------------------- /docs/misc/LongPaths.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |
In general, programs are affected by two kinds of path length limitations:
16 |These limitations are often referred to as "MAX_PATH limitations", after the constant MAX_PATH
, which has the value 260. One character is generally reserved for a null terminator, leaving 259 characters for the actual path.
AutoHotkey removes the second kind in most cases, which enables the script to work around the first kind. There are two ways to do this:
22 |\\?\
enables it to exceed the usual limit. However, some system functions do not support it (or long paths in general). See Known Limitations for details.If supported by the underlying system function, the \\?\
prefix -- for example, in \\?\C:\My Folder
-- increases the limit to 32,767 characters. However, it does this by skipping path normalization. Some elements of the path which would normally be removed or altered by normalization instead become part of the file's actual path. Care must be taken as this can allow the creation of paths that "normal" programs cannot access.
In particular, normalization:
30 |dir\file.ext
, \file.ext
and C:file.ext
(note the absence of a slash).\..
and \.
./
with \
and eliminating redundant separators.dir.\file
) or trailing spaces and periods (dir\filename . .
).A path can be normalized explicitly by passing it to GetFullPathName via the function defined below, before applying the prefix. For example:
37 |MsgBox "\\?\" NormalizePath("..\file.ext")38 |
NormalizePath(path) { 39 | cc := DllCall("GetFullPathName", "str", path, "uint", 0, "ptr", 0, "ptr", 0, "uint") 40 | buf := Buffer(cc*2) 41 | DllCall("GetFullPathName", "str", path, "uint", cc, "ptr", buf, "ptr", 0) 42 | return StrGet(buf) 43 | }44 |
A path with the \\?\
prefix can also be normalized by this function. However, in that case the working directory is never used, and the root is \\?\
(for example, \\?\C:\..
resolves to \\?\
whereas C:\..
resolves to C:\
).
Even when the path itself is not limited to 259 characters, each component (file or directory name) cannot exceed the hard limit imposed by the file system (usually 255 characters).
48 |These do not support long paths due to limitations of the underlying system function(s):
49 |SetWorkingDir and A_WorkingDir support long paths only when Windows 10 long path awareness is enabled, since the \\?\
prefix cannot be used. If the working directory exceeds MAX_PATH, it becomes impossible to launch programs with Run. These limitations are imposed by the OS.
It does not appear to be possible to run an executable with a full path which exceeds MAX_PATH. That being the case, it would not be possible to fully test any changes aimed at supporting longer executable paths. Therefore, MAX_PATH limits have been left in place for the following:
63 |Long #Include paths shown in error messages may be truncated arbitrarily.
71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /docs/misc/Macros.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |A macro is a series of scripted actions that is "played" upon demand. The most common activity of a macro is to send simulated keystrokes and mouse clicks to one or more windows. Such windows respond to each keystroke and mouse click as though you had performed it manually, which allows repetitive tasks to be automated with high speed and reliability.
17 |One of the most convenient ways to play back a macro is to assign it to a hotkey or hotstring. For example, the following hotkey would create an empty e-mail message and prepare it for a certain type recipient, allowing you to personalize it prior to sending:
18 |^!s:: ; Control+Alt+S hotkey. 19 | { 20 | if not WinExist("Inbox - Microsoft Outlook") 21 | return ; Outlook isn't open to the right section, so do nothing. 22 | WinActivate ; Activate the window found by the above function. 23 | Send "^n" ; Create new/blank e-mail via Control+N. 24 | WinWaitActive "Untitled Message" 25 | Send "{Tab 2}Product Recall for ACME Rocket Skates" ; Set the subject line. 26 | Send "{Tab}Dear Sir or Madam,{Enter 2}We have recently discovered a minor defect ..." ; etc. 27 | } ; This brace marks the end of the hotkey.28 |
Hotkey macros like the above are especially useful for tasks you perform several times per day. By contrast, macros used less often can each be kept in a separate script accessible by means of a shortcut in the Start Menu or on the desktop.
29 |To start creating your own macros and hotkeys right away, please read the Quick-start Tutorial.
30 | 31 | 32 | -------------------------------------------------------------------------------- /docs/misc/Override.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |You can disable all built-in Windows hotkeys except Win+L and Win+U by making the following change to the registry (this should work on all OSes but a reboot is probably required):
16 |HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer 17 | NoWinKeys REG_DWORD 0x00000001 (1)18 |
But read on if you want to do more than just disable them all.
19 |Hotkeys owned by another application can be overridden or disabled simply by assigning them to an action in the script. The most common use for this feature is to change the hotkeys that are built into Windows itself. For example, if you wish Win+E (the shortcut key that launches Windows Explorer) to perform some other action, use this:
20 |#e::MsgBox "This hotkey is now owned by the script."21 |
In the next example, the Win+R hotkey, which is used to open the RUN window, is completely disabled:
22 |#r::return23 |
Similarly, to disable both Win, use this:
24 |LWin::return 25 | RWin::return26 |
To disable or change an application's non-global hotkey (that is, a shortcut key that only works when that application is the active window), consider the following example which disables Ctrl+P (Print) only for Notepad, leaving the key in effect for all other types of windows:
27 |$^p:: 28 | { 29 | if WinActive("ahk_class Notepad") 30 | return ; i.e. do nothing, which causes Ctrl+P to do nothing in Notepad. 31 | Send "^p" 32 | }33 |
In the above example, the $ prefix is needed so that the hotkey can "send itself" without activating itself (which would otherwise trigger a warning dialog about an infinite loop). See also: Context-sensitive Hotkeys.
34 |You can try out any of the above examples by copying them into a new text file such as "Override.ahk", then launching the file. Alternatively, if your browser supports it, you can download any of them as a script file by clicking the ↓ button which appears in the top-right of the code block when you hover your mouse over it.
35 | 36 | 37 | -------------------------------------------------------------------------------- /docs/misc/Performance.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |The following functions may affect performance depending on the nature of the script: SendMode, SetKeyDelay, SetMouseDelay, SetWinDelay, SetControlDelay, and SetDefaultMouseSpeed.
16 |Each script is semi-compiled while it is being loaded and syntax-checked. In addition to detecting some errors early, this also greatly improves runtime performance.
18 |Here are some of the technical details of the optimization process (semi-compiling):
19 |In addition, during script execution, binary numbers are cached in variables to avoid conversions to/from strings.
28 | 29 | 30 | -------------------------------------------------------------------------------- /docs/misc/RegEx-QuickRef.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Match anywhere: By default, a regular expression matches a substring anywhere inside the string to be searched. For example, the regular expression abc matches abc123, 123abc, and 123abcxyz. To require the match to occur only at the beginning or end, use an anchor.
23 |Escaped characters: Most characters like abc123 can be used literally inside a regular expression. However, any of the characters in the set \.*?+[{|()^$
must be preceded by a backslash to be seen as literal. For example, \. is a literal period and \\ is a literal backslash. Escaping can be avoided by using \Q...\E. For example: \QLiteral Text\E.
Case-sensitive: By default, regular expressions are case-sensitive. This can be changed via the "i" option. For example, the pattern i)abc searches for "abc" without regard to case. See below for other modifiers.
25 | 26 |At the very beginning of a regular expression, specify zero or more of the following options followed by a close-parenthesis. For example, the pattern im)abc would search for "abc" with the case-insensitive and multiline options (the parenthesis may be omitted when there are no options). Although this syntax breaks from tradition, it requires no special delimiters (such as forward-slash), and thus there is no need to escape such delimiters inside the pattern. In addition, performance is improved because the options are easier to parse.
28 |Option | 31 |Description | 32 |
---|---|
i | 35 |Case-insensitive matching, which treats the letters A through Z as identical to their lowercase counterparts. | 36 |
m | 39 |Multiline. Views Haystack as a collection of individual lines (if it contains newlines) rather than as a single continuous line. Specifically, it changes the following: 40 |1) Circumflex (^) matches immediately after all internal newlines -- as well as at the start of Haystack where it always matches (but it does not match after a newline at the very end of Haystack). 41 |2) Dollar-sign ($) matches before any newlines in Haystack (as well as at the very end where it always matches). 42 |For example, the pattern m)^abc$ matches xyz`r`nabc. But without the "m" option, it wouldn't match. 43 |The "D" option is ignored when "m" is present. |
44 |
s | 47 |DotAll. This causes a period (.) to match all characters including newlines (normally, it does not match newlines). However, two dots are required to match a CRLF newline sequence (`r`n), not one. Regardless of this option, a negative class such as [^a] always matches newlines. | 48 |
x | 51 |Ignores whitespace characters in the pattern except when escaped or inside a character class. The characters `n and `t are among those ignored because by the time they get to PCRE, they are already raw/literal whitespace characters (by contrast, \n and \t are not ignored because they are PCRE escape sequences). The "x" option also ignores characters between a non-escaped # outside a character class and the next newline character, inclusive. This makes it possible to include comments inside complicated patterns. However, this applies only to data characters; whitespace may never appear within special character sequences such as (?(, which begins a conditional subpattern. | 52 |
A | 55 |Forces the pattern to be anchored; that is, it can match only at the start of Haystack. Under most conditions, this is equivalent to explicitly anchoring the pattern by means such as "^". | 56 |
D | 59 |Forces dollar-sign ($) to match at the very end of Haystack, even if Haystack's last item is a newline. Without this option, $ instead matches right before the final newline (if there is one). Note: This option is ignored when the "m" option is present. | 60 |
J | 63 |Allows duplicate named subpatterns. This can be useful for patterns in which only one of a collection of identically-named subpatterns can match. Note: If more than one instance of a particular name matches something, only the leftmost one is stored. Also, variable names are not case-sensitive. | 64 |
U | 67 |Ungreedy. Makes the quantifiers *, ?, + and {min,max} consume only those characters absolutely necessary to form a match, leaving the remaining ones available for the next part of the pattern. When the "U" option is not in effect, an individual quantifier can be made non-greedy by following it with a question mark. Conversely, when "U" is in effect, the question mark makes an individual quantifier greedy. | 68 |
X | 71 |PCRE_EXTRA. Enables PCRE features that are incompatible with Perl. Currently, the only such feature is that any backslash in a pattern that is followed by a letter that has no special meaning causes an exception to be thrown. This option helps reserve unused backslash sequences for future use. Without this option, a backslash followed by a letter with no special meaning is treated as a literal (e.g. \g and g are both recognized as a literal g). Regardless of this option, non-alphabetic backslash sequences that have no special meaning are always treated as literals (e.g. \/ and / are both recognized as forward-slash). | 72 |
S | 75 |Studies the pattern to try improve its performance. This is useful when a particular pattern (especially a complex one) will be executed many times. If PCRE finds a way to improve performance, that discovery is stored alongside the pattern in the cache for use by subsequent executions of the same pattern (subsequent uses of that pattern should also specify the S option because finding a match in the cache requires that the option letters exactly match, including their order). | 76 |
C | 79 |Enables the auto-callout mode. See Regular Expression Callouts for more info. | 80 |
`a | 83 |Enables recognition of additional newline markers. By default, only `r`n, `n and `r are recognized. With this option enabled, `v/VT/vertical tab/chr(0xB), `f/FF/formfeed/chr(0xC), NEL/next-line/chr(0x85), LS/line separator/chr(0x2028) and PS/paragraph separator/chr(0x2029) are also recognized. 84 |The `a, `n and `r options affect the behavior of anchors (^ and $) and the dot/period pattern. 85 |`a also puts (*BSR_UNICODE) into effect, which causes \R to match any kind of newline. By default, \R matches `n, `r and `r`n; this behaviour can be restored by combining options as follows: `a)(*BSR_ANYCRLF) 86 | |
87 |
`n | 90 |Causes a solitary linefeed (`n) to be the only recognized newline marker (see above). | 91 |
`r | 94 |Causes a solitary carriage return (`r) to be the only recognized newline marker (see above). | 95 |
Note: Spaces and tabs may optionally be used to separate each option from the next.
98 | 99 |Element | 103 |Description | 104 |
---|---|
. | 107 |By default, a dot matches any single character except `r (carriage return) or `n (linefeed), but this can be changed by using the DotAll (s), linefeed (`n), carriage return (`r), or `a options. For example, ab. matches abc and abz and ab_. | 108 |
* | 111 |An asterisk matches zero or more of the preceding character, class, or subpattern. For example, a* matches ab and aaab. It also matches at the very beginning of any string that contains no "a" at all. 112 |Wildcard: The dot-star pattern .* is one of the most permissive because it matches zero or more occurrences of any character (except newline: `r and `n). For example, abc.*123 matches abcAnything123 as well as abc123. |
113 |
? | 116 |A question mark matches zero or one of the preceding character, class, or subpattern. Think of this as "the preceding item is optional". For example, colou?r matches both color and colour because the "u" is optional. | 117 |
+ | 120 |A plus sign matches one or more of the preceding character, class, or subpattern. For example a+ matches ab and aaab. But unlike a* and a?, the pattern a+ does not match at the beginning of strings that lack an "a" character. | 121 |
{min,max} | 124 |Matches between min and max occurrences of the preceding character, class, or subpattern. For example, a{1,2} matches ab but only the first two a's in aaab. 125 |Also, {3} means exactly 3 occurrences, and {3,} means 3 or more occurrences. Note: The specified numbers must be less than 65536, and the first must be less than or equal to the second. |
126 |
[...] | 129 |Classes of characters: The square brackets enclose a list or range of characters (or both). For example, [abc] means "any single character that is either a, b or c". Using a dash in between creates a range; for example, [a-z] means "any single character that is between lowercase a and z (inclusive)". Lists and ranges may be combined; for example [a-zA-Z0-9_] means "any single character that is alphanumeric or underscore". 130 |A character class may be followed by *, ?, +, or {min,max}. For example, [0-9]+ matches one or more occurrence of any digit; thus it matches xyz123 but not abcxyz. 131 |The following POSIX named sets are also supported via the form [[:xxx:]], where xxx is one of the following words: alnum, alpha, ascii (0-127), blank (space or tab), cntrl (control character), digit (0-9), xdigit (hex digit), print, graph (print excluding space), punct, lower, upper, space (whitespace), word (same as \w). 132 |Within a character class, characters do not need to be escaped except when they have special meaning inside a class; e.g. [\^a], [a\-b], [a\]], and [\\a]. |
133 |
[^...] | 136 |Matches any single character that is not in the class. For example, [^/]* matches zero or more occurrences of any character that is not a forward-slash, such as http://. Similarly, [^0-9xyz] matches any single character that isn't a digit and isn't the letter x, y, or z. | 137 |
\d | 140 |Matches any single digit (equivalent to the class [0-9]). Conversely, capital \D means "any non-digit". This and the other two below can also be used inside a class; for example, [\d.-] means "any single digit, period, or minus sign". | 141 |
\s | 144 |Matches any single whitespace character, mainly space, tab, and newline (`r and `n). Conversely, capital \S means "any non-whitespace character". | 145 |
\w | 148 |Matches any single "word" character, namely alphanumeric or underscore. This is equivalent to [a-zA-Z0-9_]. Conversely, capital \W means "any non-word character". | 149 |
^ $ |
152 | Circumflex (^) and dollar sign ($) are called anchors because they don't consume any characters; instead, they tie the pattern to the beginning or end of the string being searched. 153 |^ may appear at the beginning of a pattern to require the match to occur at the very beginning of a line. For example, ^abc matches abc123 but not 123abc. 154 |$ may appear at the end of a pattern to require the match to occur at the very end of a line. For example, abc$ matches 123abc but not abc123. 155 |The two anchors may be combined. For example, ^abc$ matches only abc (i.e. there must be no other characters before or after it). 156 |If the text being searched contains multiple lines, the anchors can be made to apply to each line rather than the text as a whole by means of the "m" option. For example, m)^abc$ matches 123`r`nabc`r`n789. But without the "m" option, it wouldn't match. |
157 |
\b | 160 |\b means "word boundary", which is like an anchor because it doesn't consume any characters. It requires the current character's status as a word character (\w) to be the opposite of the previous character's. It is typically used to avoid accidentally matching a word that appears inside some other word. For example, \bcat\b doesn't match catfish, but it matches cat regardless of what punctuation and whitespace surrounds it. Capital \B is the opposite: it requires that the current character not be at a word boundary. | 161 |
| | 164 |The vertical bar separates two or more alternatives. A match occurs if any of the alternatives is satisfied. For example, gray|grey matches both gray and grey. Similarly, the pattern gr(a|e)y does the same thing with the help of the parentheses described below. | 165 |
(...) | 168 |Items enclosed in parentheses are most commonly used to: 169 |
|
175 |
\t \r etc. |
178 | These escape sequences stand for special characters. The most common ones are \t (tab), \r (carriage return), and \n (linefeed). In AutoHotkey, an accent (`) may optionally be used in place of the backslash in these cases. Escape sequences in the form \xhh are also supported, in which hh is the hex code of any ANSI character between 00 and FF. 179 |\R matches |
180 |
\p{xx} \P{xx} \X |
183 | Unicode character properties. \p{xx} matches a character with the xx property while \P{xx} matches any character without the xx property. For example, \pL matches any letter and \p{Lu} matches any upper-case letter. \X matches any number of characters that form an extended Unicode sequence. 184 |For a full list of supported property names and other details, search for "\p{xx}" at www.pcre.org/pcre.txt. |
185 |
(*UCP) | 188 |For performance, \d, \D, \s, \S, \w, \W, \b and \B recognize only ASCII characters by default. If the pattern begins with (*UCP), Unicode properties will be used to determine which characters match. For example, \w becomes equivalent to [\p{L}\p{N}_] and \d becomes equivalent to \p{Nd}. 189 | |
190 |
Greed: By default, *, ?, +, and {min,max} are greedy because they consume all characters up through the last possible one that still satisfies the entire pattern. To instead have them stop at the first possible character, follow them with a question mark. For example, the pattern <.+> (which lacks a question mark) means: "search for a <, followed by one or more of any character, followed by a >". To stop this pattern from matching the entire string <em>text</em>, append a question mark to the plus sign: <.+?>. This causes the match to stop at the first '>' and thus it matches only the first tag <em>.
193 |Look-ahead and look-behind assertions: The groups (?=...), (?!...), (?<=...), and (?<!...) are called assertions because they demand a condition to be met but don't consume any characters. For example, abc(?=.*xyz) is a look-ahead assertion that requires the string xyz to exist somewhere to the right of the string abc (if it doesn't, the entire pattern is not considered a match). (?=...) is called a positive look-ahead because it requires that the specified pattern exist. Conversely, (?!...) is a negative look-ahead because it requires that the specified pattern not exist. Similarly, (?<=...) and (?<!...) are positive and negative look-behinds (respectively) because they look to the left of the current position rather than the right. Look-behinds are more limited than look-aheads because they do not support quantifiers of varying size such as *, ?, and +. The escape sequence \K is similar to a look-behind assertion because it causes any previously-matched characters to be omitted from the final matched string. For example, foo\Kbar matches "foobar" but reports that it has matched "bar".
194 |Related: Regular expressions are supported by RegExMatch, RegExReplace, and SetTitleMatchMode.
195 |Final note: Although this page touches upon most of the commonly-used RegEx features, there are quite a few other features you may want to explore such as conditional subpatterns. The complete PCRE manual is at www.pcre.org/pcre.txt
196 | 197 | 198 | 199 | -------------------------------------------------------------------------------- /docs/misc/RegExCallout.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |RegEx callouts provide a means of temporarily passing control to the script in the middle of regular expression pattern matching. For detailed information about the PCRE-standard callout feature, see pcre.txt.
16 | 17 |RegEx callouts are currently supported only by RegExMatch and RegExReplace.
18 | 19 |The syntax for a RegEx callout in AutoHotkey is (?CNumber:Function), where both Number and Function are optional. Colon ':' is allowed only if Function is specified, and is optional if Number is omitted. If Function is specified but is not the name of a function object, a compile error occurs and pattern-matching does not begin.
31 | 32 |If Function is omitted, the default RegEx callout function named pcre_callout must be defined. If pcre_callout is not defined, RegEx callouts which omit Function are ignored.
33 | 34 |MyFunction(Match, CalloutNumber, FoundPos, Haystack, NeedleRegEx) 37 | { 38 | ... 39 | }40 |
RegEx callout functions may define up to 5 parameters:
41 |These names are suggestive only. Actual names may vary.
49 | 50 |Warning: Changing the input parameters of RegExReplace or RegExMatch during a call is unsupported and may cause unpredictable behaviour.
51 | 52 |Pattern-matching may proceed or fail depending on the return value of the RegEx callout function:
53 |For example:
61 |Haystack := "The quick brown fox jumps over the lazy dog." 62 | RegExMatch(Haystack, "i)(The) (\w+)\b(?CCallout)") 63 | Callout(m, *) { 64 | MsgBox "m[0]=" m[0] "`nm[1]=" m[1] "`nm[2]=" m[2] 65 | return 1 66 | }67 |
In the above example, Callout is called once for each substring which matches the part of the pattern preceding the RegEx callout. \b is used to exclude incomplete words in matches such as The quic, The qui, The qu, etc.
68 |If any of the input parameters to a RegEx function is modified during a callout, the behaviour is undefined.
69 | 70 |Additional information is available by accessing the pcre_callout_block structure via A_EventInfo.
73 |version := NumGet(A_EventInfo, 0, "Int") 74 | callout_number := NumGet(A_EventInfo, 4, "Int") 75 | offset_vector := NumGet(A_EventInfo, 8, "Ptr") 76 | subject := NumGet(A_EventInfo, 8 + A_PtrSize, "Ptr") 77 | subject_length := NumGet(A_EventInfo, 8 + A_PtrSize*2, "Int") 78 | start_match := NumGet(A_EventInfo, 12 + A_PtrSize*2, "Int") 79 | current_position := NumGet(A_EventInfo, 16 + A_PtrSize*2, "Int") 80 | capture_top := NumGet(A_EventInfo, 20 + A_PtrSize*2, "Int") 81 | capture_last := NumGet(A_EventInfo, 24 + A_PtrSize*2, "Int") 82 | pad := A_PtrSize=8 ? 4 : 0 ; Compensate for 64-bit data alignment. 83 | callout_data := NumGet(A_EventInfo, 28 + pad + A_PtrSize*2, "Ptr") 84 | pattern_position := NumGet(A_EventInfo, 28 + pad + A_PtrSize*3, "Int") 85 | next_item_length := NumGet(A_EventInfo, 32 + pad + A_PtrSize*3, "Int") 86 | if (version >= 2) 87 | mark := StrGet(NumGet(A_EventInfo, 36 + pad + A_PtrSize*3, "Int"), "UTF-8") 88 |89 |
For more information, see pcre.txt, NumGet and A_PtrSize.
90 | 91 |Including C in the options of the pattern enables the auto-callout mode. In this mode, RegEx callouts equivalent to (?C255) are inserted before each item in the pattern. For example, the following template may be used to debug regular expressions:
94 |; Call RegExMatch with auto-callout option C. 95 | RegExMatch("xxxabc123xyz", "C)abc.*xyz") 96 | 97 | ; Define the default RegEx callout function. 98 | pcre_callout(Match, CalloutNumber, FoundPos, Haystack, NeedleRegEx) 99 | { 100 | ; See pcre.txt for descriptions of these fields. 101 | start_match := NumGet(A_EventInfo, 12 + A_PtrSize*2, "Int") 102 | current_position := NumGet(A_EventInfo, 16 + A_PtrSize*2, "Int") 103 | pad := A_PtrSize=8 ? 4 : 0 104 | pattern_position := NumGet(A_EventInfo, 28 + pad + A_PtrSize*3, "Int") 105 | next_item_length := NumGet(A_EventInfo, 32 + pad + A_PtrSize*3, "Int") 106 | 107 | ; Point out >>current match<<. 108 | _HAYSTACK:=SubStr(Haystack, 1, start_match) 109 | . ">>" SubStr(Haystack, start_match + 1, current_position - start_match) 110 | . "<<" SubStr(Haystack, current_position + 1) 111 | 112 | ; Point out >>next item to be evaluated<<. 113 | _NEEDLE:= SubStr(NeedleRegEx, 1, pattern_position) 114 | . ">>" SubStr(NeedleRegEx, pattern_position + 1, next_item_length) 115 | . "<<" SubStr(NeedleRegEx, pattern_position + 1 + next_item_length) 116 | 117 | ListVars 118 | ; Press Pause to continue. 119 | Pause 120 | }121 | 122 |
RegEx callouts are executed on the current quasi-thread, but the previous value of A_EventInfo will be restored after the RegEx callout function returns.
125 |PCRE is optimized to abort early in some cases if it can determine that a match is not possible. For all RegEx callouts to be called in such cases, it may be necessary to disable these optimizations by specifying (*NO_START_OPT) at the start of the pattern.
126 | 127 | 128 | 129 | -------------------------------------------------------------------------------- /docs/misc/Remap.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Limitation: AutoHotkey's remapping feature described below is generally not as pure and effective as remapping directly via the Windows registry. For the advantages and disadvantages of each approach, see registry remapping.
28 |The syntax for the built-in remapping feature is OriginKey::DestinationKey
. For example, a script consisting only of the following line would make A behave like B:
a::b31 |
The above example does not alter B itself. B would continue to send the "b" keystroke unless you remap it to something else as shown in the following example:
32 |a::b 33 | b::a34 |
The examples above use lowercase, which is recommended for most purposes because it also remaps the corresponding uppercase letters (that is, it will send uppercase when CapsLock is "on" or Shift is held down). By contrast, specifying an uppercase letter on the right side forces uppercase. For example, the following line would produce an uppercase B when you type either "a" or "A" (as long as CapsLock is off):
35 |a::B36 |
Conversely, any modifiers included on the left side but not the right side are automatically released when the key is sent. For example, the following two lines would produce a lowercase "b" when you press either Shift+A or Ctrl+A:
37 |A::b 38 | ^a::b39 | 40 |
To remap the mouse instead of the keyboard, use the same approach. For example:
42 |Example | 45 |Description | 46 |
---|---|
MButton::Shift |
49 | Makes the middle button behave like Shift. | 50 |
XButton1::LButton |
53 | Makes the fourth mouse button behave like the left mouse button. | 54 |
RAlt::RButton |
57 | Makes the right Alt behave like the right mouse button. | 58 |
Example | 65 |Description | 66 |
---|---|
CapsLock::Ctrl |
69 | Makes CapsLock become Ctrl. To retain the ability to turn CapsLock on and off, add the remapping +CapsLock::CapsLock first. This toggles CapsLock on and off when you hold down Shift and press CapsLock. Because both remappings allow additional modifier keys to be held down, the more specific +CapsLock::CapsLock remapping must be placed first for it to work. |
70 |
XButton2::^LButton |
73 | Makes the fifth mouse button (XButton2) produce a control-click. | 74 |
RAlt::AppsKey |
77 | Makes the right Alt become Menu (which is the key that opens the context menu). | 78 |
RCtrl::RWin |
81 | Makes the right Ctrl become the right Win. | 82 |
Ctrl::Alt |
85 | Makes both Ctrl behave like Alt. However, see alt-tab issues. | 86 |
^x::^c |
89 | Makes Ctrl+X produce Ctrl+C. It also makes Ctrl+Alt+X produce Ctrl+Alt+C, etc. | 90 |
RWin::Return |
93 | Disables the right Win by having it simply return. | 94 |
You can try out any of these examples by copying them into a new text file such as "Remap.ahk", then launching the file.
97 |See the Key List for a complete list of key and mouse button names.
98 |The #HotIf directive can be used to make selected remappings active only in the windows you specify (or while any given condition is met). For example:
100 |#HotIf WinActive("ahk_class Notepad") 101 | a::b ; Makes the 'a' key send a 'b' key, but only in Notepad. 102 | #HotIf ; This puts subsequent remappings and hotkeys in effect for all windows.103 |
Remapping a key or button is "complete" in the following respects:
104 |b::a
would produce Ctrl+A if you press Ctrl+B.Although a remapped key can trigger normal hotkeys, by default it cannot trigger mouse hotkeys or hook hotkeys (use ListHotkeys to discover which hotkeys are "hook"). For example, if the remapping a::b
is in effect, pressing Ctrl+Alt+A would trigger the ^!b
hotkey only if ^!b
is not a hook hotkey. If ^!b
is a hook hotkey, you can define ^!a
as a hotkey if you want Ctrl+Alt+A to perform the same action as Ctrl+Alt+B. For example:
a::b 112 | ^!a:: 113 | ^!b::ToolTip "You pressed " ThisHotkey 114 |115 |
Alternatively, #InputLevel can be used to override the default behaviour. For example:
116 |#InputLevel 1 117 | a::b 118 | 119 | #InputLevel 0 120 | ^!b::ToolTip "You pressed " ThisHotkey 121 |122 |
If SendMode is used during script startup, it affects all remappings. However, since remapping uses Send "{Blind}" and since the SendPlay mode does not fully support {Blind}, some remappings might not function properly in SendPlay mode (especially Ctrl, Shift, Alt, and Win). To work around this, avoid using SendMode "Play"
during script startup when you have remappings; then use the function SendPlay vs. Send in other places throughout the script. Alternatively, you could translate your remappings into hotkeys (as described below) that explicitly call SendEvent vs. Send.
If DestinationKey is meant to be {
, it has to be escaped, for example, x::`{
. Otherwise it is interpreted as the opening brace for the hotkey's function.
When a script is launched, each remapping is translated into a pair of hotkeys. For example, a script containing a::b
actually contains the following two hotkeys instead:
*a:: 126 | { 127 | SetKeyDelay -1 ; If the destination key is a mouse button, SetMouseDelay is used instead. 128 | Send "{Blind}{b DownR}" ; DownR is like Down except that other Send functions in the script won't assume "b" should stay down during their Send. 129 | } 130 | 131 | *a up:: 132 | { 133 | SetKeyDelay -1 ; See note below for why press-duration is not specified with either of these SetKeyDelays. 134 | Send "{Blind}{b Up}" 135 | }136 |
However, the above hotkeys vary under the following circumstances:
137 |Send "{Blind}{LAlt DownR}"
is replaced by Send "{Blind}{LCtrl up}{LAlt DownR}"
. The same is true if the source is the right Ctrl, except that {RCtrl up}
is used. This is done to ensure that the system translates Alt-key combinations as though Ctrl is not being held down, but it also causes the remapping to override any prior {Ctrl down}. [v2.0.8+]: The unsuppressed Ctrl key-up is still sent for backward-compatibility, but is no longer needed for its original purpose. The side effect can be avoided by replacing the remapping with an explicit pair of hotkeys as demonstrated above.RCtrl::RButton
), the hotkeys above use SetMouseDelay in place of SetKeyDelay. In addition, the first hotkey above is replaced by the following, which prevents the keyboard's auto-repeat feature from generating repeated mouse clicks:
140 | *RCtrl:: 141 | { 142 | SetMouseDelay -1 143 | if not GetKeyState("RButton") ; i.e. the right mouse button isn't down yet. 144 | Send "{Blind}{RButton DownR}" 145 | }146 |
!#^+
are applied to the source key and not the destination key, they are inserted after the word "Blind" to allow those modifiers to be released by Send. For example, ^a::b
would use {Blind^}
. <^a::b
would also use {Blind^}
, which may produce unexpected results if used in combination with RCtrl. For details, see Blind mode.Note that SetKeyDelay's second parameter (press duration) is omitted in the hotkeys above. This is because press-duration does not apply to down-only or up-only events such as {b down}
and {b up}
. However, it does apply to changes in the state of the modifier keys (Shift, Ctrl, Alt, and Win), which affects remappings such as a::B
or a::^b
. Consequently, any press-duration a script puts into effect during script startup will apply to all such remappings.
Since remappings are translated into hotkeys as described above, the Suspend function affects them. Similarly, the Hotkey function can disable or modify a remapping. For example, the following two functions would disable the remapping a::b
.
Hotkey "*a", "Off" 153 | Hotkey "*a up", "Off"154 |
Alt-tab issues: If you remap a key or mouse button to become Alt, that key will probably not be able to alt-tab properly. A possible work-around is to add the hotkey *Tab::Send "{Blind}{Tab}"
-- but be aware that it will likely interfere with using the real Alt to alt-tab. Therefore, it should be used only when you alt-tab solely by means of remapped keys and/or alt-tab hotkeys.
In addition to the keys and mouse buttons on the Key List page, the source key may also be a virtual key (VKnn) or scan code (SCnnn) as described in the Special Keys section. The same is true for the destination key except that it may optionally specify a scan code after the virtual key. For example, sc01e::vk42sc030
is equivalent to a::b
on most keyboard layouts.
To disable a key rather than remapping it, make it a hotkey that simply returns. For example, F1::return
would disable F1.
The following keys are not supported by the built-in remapping method:
158 |vk13
or the corresponding scan code.x::+sc01A
and y::+sc01B
.The keyboard can be used to move the mouse cursor as demonstrated by the fully-featured Keyboard-To-Mouse script. Since that script offers smooth cursor movement, acceleration, and other features, it is the recommended approach if you plan to do a lot of mousing with the keyboard. By contrast, the following example is a simpler demonstration:
165 |*#up::MouseMove 0, -10, 0, "R" ; Win+UpArrow hotkey => Move cursor upward 166 | *#Down::MouseMove 0, 10, 0, "R" ; Win+DownArrow => Move cursor downward 167 | *#Left::MouseMove -10, 0, 0, "R" ; Win+LeftArrow => Move cursor to the left 168 | *#Right::MouseMove 10, 0, 0, "R" ; Win+RightArrow => Move cursor to the right 169 | 170 | *<#RCtrl:: ; LeftWin + RightControl => Left-click (hold down Control/Shift to Control-Click or Shift-Click). 171 | { 172 | SendEvent "{Blind}{LButton down}" 173 | KeyWait "RCtrl" ; Prevents keyboard auto-repeat from repeating the mouse click. 174 | SendEvent "{Blind}{LButton up}" 175 | } 176 | 177 | *<#AppsKey:: ; LeftWin + AppsKey => Right-click 178 | { 179 | SendEvent "{Blind}{RButton down}" 180 | KeyWait "AppsKey" ; Prevents keyboard auto-repeat from repeating the mouse click. 181 | SendEvent "{Blind}{RButton up}" 182 | }183 |
Advantages:
185 |Disadvantages:
190 |How to Apply Changes to the Registry: There are at least two methods to remap keys via the registry:
197 |Joy
, which stands for joystick. However, they usually also work for other game controllers such as gamepads or steering wheels.Below are three approaches, starting at the simplest and ending with the most complex. The most complex method works in the broadest variety of circumstances (such as games that require a key or mouse button to be held down).
48 | 49 |This method sends simple keystrokes and mouse clicks. For example:
51 |Joy1::Send "{Left}" ; Have button #1 send a left-arrow keystroke. 52 | Joy2::Click ; Have button #2 send a click of left mouse button. 53 | Joy3::Send "a{Esc}{Space}{Enter}" ; Have button #3 send the letter "a" followed by Escape, Space, and Enter. 54 | Joy4::Send "Sincerely,{Enter}John Smith" ; Have button #4 send a two-line signature.55 |
To have a button perform more than one line, put them beneath the button name and enclose them in braces. For example:
56 |Joy5:: 57 | { 58 | Run "notepad" 59 | WinWait "Untitled - Notepad" 60 | WinActivate 61 | Send "This is the text that will appear in Notepad.{Enter}" 62 | }63 |
For details, see How to Write Hotkeys.
64 |See the Key List for the complete list of keys and mouse/controller buttons.
65 | 66 |This method is necessary in cases where a key or mouse button must be held down for the entire time that you're holding down a controller button. The following example makes the controller's second button become the left-arrow key:
68 |Joy2:: 69 | { 70 | Send "{Left down}" ; Hold down the left-arrow key. 71 | KeyWait "Joy2" ; Wait for the user to release the controller button. 72 | Send "{Left up}" ; Release the left-arrow key. 73 | }74 | 75 |
This method is necessary in cases where you have more than one controller hotkey of the type described in Method #2, and you sometimes press and release such hotkeys simultaneously. The following example makes the controller's third button become the left mouse button:
77 |Joy3:: 78 | { 79 | Send "{LButton down}" ; Hold down the left mouse button. 80 | SetTimer WaitForButtonUp3, 10 81 | } 82 | 83 | WaitForButtonUp3() 84 | { 85 | if GetKeyState("Joy3") ; The button is still, down, so keep waiting. 86 | return 87 | ; Otherwise, the button has been released. 88 | Send "{LButton up}" ; Release the left mouse button. 89 | SetTimer , 0 90 | } 91 |92 | 93 |
Some programs or games might require a key to be sent repeatedly (as though you are holding it down on the keyboard). The following example achieves this by sending spacebar keystrokes repeatedly while you hold down the controller's second button:
95 |Joy2:: 96 | { 97 | Send "{Space down}" ; Press the spacebar down. 98 | SetTimer WaitForJoy2, 30 ; Reduce the number 30 to 20 or 10 to send keys faster. Increase it to send slower. 99 | } 100 | 101 | WaitForJoy2() 102 | { 103 | if not GetKeyState("Joy2") ; The button has been released. 104 | { 105 | Send "{Space up}" ; Release the spacebar. 106 | SetTimer , 0 ; Stop monitoring the button. 107 | return 108 | } 109 | ; Since above didn't "return", the button is still being held down. 110 | Send "{Space down}" ; Send another Spacebar keystroke. 111 | }112 | 113 |
The #HotIf directive can be used to make selected controller buttons perform a different action (or none at all) depending on any condition, such as the type of window that is active.
115 | 116 |The Controller-To-Mouse script converts a controller into a mouse by remapping its buttons and axis control.
118 | 119 |To have a script respond to movement of a stick's axis or POV hat, use SetTimer and GetKeyState.
121 | 122 |The following example makes the stick's X and Y axes behave like the arrow key cluster on a keyboard (left, right, up, and down):
124 |SetTimer WatchAxis, 5 125 | 126 | WatchAxis() 127 | { 128 | static KeyToHoldDown := "" 129 | JoyX := GetKeyState("JoyX") ; Get position of X axis. 130 | JoyY := GetKeyState("JoyY") ; Get position of Y axis. 131 | KeyToHoldDownPrev := KeyToHoldDown ; Prev now holds the key that was down before (if any). 132 | 133 | if JoyX > 70 134 | KeyToHoldDown := "Right" 135 | else if JoyX < 30 136 | KeyToHoldDown := "Left" 137 | else if JoyY > 70 138 | KeyToHoldDown := "Down" 139 | else if JoyY < 30 140 | KeyToHoldDown := "Up" 141 | else 142 | KeyToHoldDown := "" 143 | 144 | if KeyToHoldDown = KeyToHoldDownPrev ; The correct key is already down (or no key is needed). 145 | return ; Do nothing. 146 | 147 | ; Otherwise, release the previous key and press down the new key: 148 | SetKeyDelay -1 ; Avoid delays between keystrokes. 149 | if KeyToHoldDownPrev ; There is a previous key to release. 150 | Send "{" KeyToHoldDownPrev " up}" ; Release it. 151 | if KeyToHoldDown ; There is a key to press down. 152 | Send "{" KeyToHoldDown " down}" ; Press it down. 153 | }154 | 155 |
The following example makes the controller's POV hat behave like the arrow key cluster on a keyboard; that is, the POV hat will send arrow keystrokes (left, right, up, and down):
157 |SetTimer WatchPOV, 5 158 | 159 | WatchPOV() 160 | { 161 | static KeyToHoldDown := "" 162 | POV := GetKeyState("JoyPOV") ; Get position of the POV control. 163 | KeyToHoldDownPrev := KeyToHoldDown ; Prev now holds the key that was down before (if any). 164 | 165 | ; Some controllers might have a smooth/continous POV rather than one in fixed increments. 166 | ; To support them all, use a range: 167 | if POV < 0 ; No angle to report 168 | KeyToHoldDown := "" 169 | else if POV > 31500 ; 315 to 360 degrees: Forward 170 | KeyToHoldDown := "Up" 171 | else if POV >= 0 and POV <= 4500 ; 0 to 45 degrees: Forward 172 | KeyToHoldDown := "Up" 173 | else if POV >= 4501 and POV <= 13500 ; 45 to 135 degrees: Right 174 | KeyToHoldDown := "Right" 175 | else if POV >= 13501 and POV <= 22500 ; 135 to 225 degrees: Down 176 | KeyToHoldDown := "Down" 177 | else ; 225 to 315 degrees: Left 178 | KeyToHoldDown := "Left" 179 | 180 | if KeyToHoldDown = KeyToHoldDownPrev ; The correct key is already down (or no key is needed). 181 | return ; Do nothing. 182 | 183 | ; Otherwise, release the previous key and press down the new key: 184 | SetKeyDelay -1 ; Avoid delays between keystrokes. 185 | if KeyToHoldDownPrev ; There is a previous key to release. 186 | Send "{" KeyToHoldDownPrev " up}" ; Release it. 187 | if KeyToHoldDown ; There is a key to press down. 188 | Send "{" KeyToHoldDown " down}" ; Press it down. 189 | }190 | 191 |
Both examples above can be modified to send the key repeatedly rather than merely holding it down (that is, they can mimic physically holding down a key on the keyboard). To do this, replace the following line:
193 |return ; Do nothing.194 |
With the following:
195 |{ 196 | if KeyToHoldDown 197 | Send "{" KeyToHoldDown " down}" ; Auto-repeat the keystroke. 198 | return 199 | }200 |
A controller other than first may be used by preceding the button or axis name with the number of the controller. For example, 2Joy1
would be the second controller's first button.
To find other useful controller scripts, visit the AutoHotkey forum. A keyword search such as Controller and GetKeyState and Send is likely to produce topics of interest.
203 |This page explains how to send messages to a window or its controls via PostMessage or SendMessage and will answer some questions like:
16 |Requirements: Winspector Spy (can be found here)
23 |As a first example, note that MenuSelect fails to work with the menu bar on Outlook Express's "New Message" window. In other words, this code will not work:
24 |MenuSelect "New Message",, "&Insert", "&Picture..."25 |
But PostMessage can get the job done:
26 |PostMessage 0x0111, 40239, 0, , "New Message"27 |
Works like a charm! But what the heck is that? 0x0111 is the hex code of wm_command message and 40239 is the code that this particular window understands as menu-item 'Insert Picture' selection. Now let me tell you how to find a value such as 40239:
28 |For the next example I'm taking Paint because possibly everyone will have that. Now let's say it's an app where you have to select a tool from a toolbar using AutoHotkey; say the dropper tool is to be selected.
41 |What will you do? Most probably a mouse click at the toolbar button, right? But toolbars can be moved and hidden! This one can be moved/hidden too. So if the target user has done any of this then your script will fail at that point. But the following function will still work:
42 |PostMessage 0x0111, 639,,, "Untitled - Paint"43 |
Another advantage to PostMessage is that the Window can be in the background; by contrast, sending mouse clicks would require it to be active.
44 |Here are some more examples. Note: I'm using WinXP Pro (SP1) ... if you use a different OS then your params may change (only applicable to apps like Wordpad and Notepad that come with windows; for others the params shouldn't vary):
45 |;makes writing color teal in Wordpad 46 | PostMessage 0x0111, 32788, 0, , "Document - WordPad"47 |
;opens about box in Notepad 48 | PostMessage 0x0111, 65, 0, , "Untitled - Notepad"49 |
;toggles word-wrap in Notepad 50 | PostMessage 0x0111, 32, 0, , "Untitled - Notepad"51 |
;play/pause in Windows Media Player 52 | PostMessage 0x0111, 32808, 0, , "Windows Media Player"53 |
;suspend the hotkeys of a running AHK script 54 | DetectHiddenWindows True 55 | ; Use 65306 to Pause and 65303 to Reload instead of Suspend. (see FAQ) 56 | PostMessage 0x0111, 65305,,, "MyScript.ahk - AutoHotkey" 57 |58 |
; Press CapsLock and Numpad2 to reload all AutoHotkey scripts 59 | CapsLock & Numpad2:: 60 | ReloadAllAhkScripts(ThisHotkey) 61 | { 62 | DetectHiddenWindows True 63 | for hwnd in WinGetList("ahk_class AutoHotkey") 64 | { 65 | if (hwnd = A_ScriptHwnd) ; ignore the current window for reloading 66 | continue 67 | PostMessage 0x0111, 65303,,, hwnd 68 | } 69 | Reload 70 | } 71 |72 |
This above was for PostMessage. SendMessage works the same way but additionally waits for a return value, which can be used for things such as getting the currently playing track in Winamp (see Automating Winamp for an example).
73 |Here are some more notes:
74 |DetectHiddenWindows True
Note: There are apps with which this technique doesn't work. I've had mixed luck with VB and Delphi apps. This technique is best used with C, C++ apps. With VB apps the 'LParam' of the same function keeps changing from one run to another. With Delphi apps... the GUI of some apps doesn't even use wm_command. It probably uses mouse pos & clicks.
81 |Go and explore.... and share your experiences in the AutoHotkey Forum. Feedback is welcome!
82 |This tutorial is not meant for total newbies (no offense meant) since these functions are considered advanced features. So if after reading the above you've not made heads or tails of it, please forget it.
83 |-Rajat
84 | 85 | 86 | -------------------------------------------------------------------------------- /docs/misc/SendMessageList.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Windows messages are used to communicate between the operating system and applications, and also between different parts of an application.
16 |A Windows message is simply a numeric code that designates a particular event. For example, if the user presses the left mouse button, the window receives a message that has the following message code: WM_LBUTTONDOWN (0x0201).
17 |Some messages have data associated with them. For example, the WM_LBUTTONDOWN message includes the X and Y coordinates of the mouse cursor.
18 |The following are the ranges of message numbers:
19 |For details, see About Messages and Message Queues (Microsoft Docs).
27 |In AutoHotkey, the message numbers can be used for the MsgNumber parameter of PostMessage, SendMessage, and OnMessage. Below is a list of some values. To discover more about how to use a particular message (e.g. WM_VSCROLL), look it up at Microsoft Docs or with a search engine of your choice. Also, check out the Message Tutorial.
28 |WM_NULL := 0x0000 29 | WM_CREATE := 0x0001 30 | WM_DESTROY := 0x0002 31 | WM_MOVE := 0x0003 32 | WM_SIZE := 0x0005 33 | WM_ACTIVATE := 0x0006 34 | WM_SETFOCUS := 0x0007 35 | WM_KILLFOCUS := 0x0008 36 | WM_ENABLE := 0x000A 37 | WM_SETREDRAW := 0x000B 38 | WM_SETTEXT := 0x000C 39 | WM_GETTEXT := 0x000D 40 | WM_GETTEXTLENGTH := 0x000E 41 | WM_PAINT := 0x000F 42 | WM_CLOSE := 0x0010 43 | WM_QUERYENDSESSION := 0x0011 44 | WM_QUIT := 0x0012 45 | WM_QUERYOPEN := 0x0013 46 | WM_ERASEBKGND := 0x0014 47 | WM_SYSCOLORCHANGE := 0x0015 48 | WM_ENDSESSION := 0x0016 49 | WM_SYSTEMERROR := 0x0017 50 | WM_SHOWWINDOW := 0x0018 51 | WM_CTLCOLOR := 0x0019 52 | WM_WININICHANGE := 0x001A 53 | WM_SETTINGCHANGE := 0x001A 54 | WM_DEVMODECHANGE := 0x001B 55 | WM_ACTIVATEAPP := 0x001C 56 | WM_FONTCHANGE := 0x001D 57 | WM_TIMECHANGE := 0x001E 58 | WM_CANCELMODE := 0x001F 59 | WM_SETCURSOR := 0x0020 60 | WM_MOUSEACTIVATE := 0x0021 61 | WM_CHILDACTIVATE := 0x0022 62 | WM_QUEUESYNC := 0x0023 63 | WM_GETMINMAXINFO := 0x0024 64 | WM_PAINTICON := 0x0026 65 | WM_ICONERASEBKGND := 0x0027 66 | WM_NEXTDLGCTL := 0x0028 67 | WM_SPOOLERSTATUS := 0x002A 68 | WM_DRAWITEM := 0x002B 69 | WM_MEASUREITEM := 0x002C 70 | WM_DELETEITEM := 0x002D 71 | WM_VKEYTOITEM := 0x002E 72 | WM_CHARTOITEM := 0x002F 73 | 74 | WM_SETFONT := 0x0030 75 | WM_GETFONT := 0x0031 76 | WM_SETHOTKEY := 0x0032 77 | WM_GETHOTKEY := 0x0033 78 | WM_QUERYDRAGICON := 0x0037 79 | WM_COMPAREITEM := 0x0039 80 | WM_COMPACTING := 0x0041 81 | WM_WINDOWPOSCHANGING := 0x0046 82 | WM_WINDOWPOSCHANGED := 0x0047 83 | WM_POWER := 0x0048 84 | WM_COPYDATA := 0x004A 85 | WM_CANCELJOURNAL := 0x004B 86 | WM_NOTIFY := 0x004E 87 | WM_INPUTLANGCHANGEREQUEST := 0x0050 88 | WM_INPUTLANGCHANGE := 0x0051 89 | WM_TCARD := 0x0052 90 | WM_HELP := 0x0053 91 | WM_USERCHANGED := 0x0054 92 | WM_NOTIFYFORMAT := 0x0055 93 | WM_CONTEXTMENU := 0x007B 94 | WM_STYLECHANGING := 0x007C 95 | WM_STYLECHANGED := 0x007D 96 | WM_DISPLAYCHANGE := 0x007E 97 | WM_GETICON := 0x007F 98 | WM_SETICON := 0x0080 99 | 100 | WM_NCCREATE := 0x0081 101 | WM_NCDESTROY := 0x0082 102 | WM_NCCALCSIZE := 0x0083 103 | WM_NCHITTEST := 0x0084 104 | WM_NCPAINT := 0x0085 105 | WM_NCACTIVATE := 0x0086 106 | WM_GETDLGCODE := 0x0087 107 | WM_NCMOUSEMOVE := 0x00A0 108 | WM_NCLBUTTONDOWN := 0x00A1 109 | WM_NCLBUTTONUP := 0x00A2 110 | WM_NCLBUTTONDBLCLK := 0x00A3 111 | WM_NCRBUTTONDOWN := 0x00A4 112 | WM_NCRBUTTONUP := 0x00A5 113 | WM_NCRBUTTONDBLCLK := 0x00A6 114 | WM_NCMBUTTONDOWN := 0x00A7 115 | WM_NCMBUTTONUP := 0x00A8 116 | WM_NCMBUTTONDBLCLK := 0x00A9 117 | 118 | WM_KEYFIRST := 0x0100 119 | WM_KEYDOWN := 0x0100 120 | WM_KEYUP := 0x0101 121 | WM_CHAR := 0x0102 122 | WM_DEADCHAR := 0x0103 123 | WM_SYSKEYDOWN := 0x0104 124 | WM_SYSKEYUP := 0x0105 125 | WM_SYSCHAR := 0x0106 126 | WM_SYSDEADCHAR := 0x0107 127 | WM_KEYLAST := 0x0108 128 | 129 | WM_IME_STARTCOMPOSITION := 0x010D 130 | WM_IME_ENDCOMPOSITION := 0x010E 131 | WM_IME_COMPOSITION := 0x010F 132 | WM_IME_KEYLAST := 0x010F 133 | 134 | WM_INITDIALOG := 0x0110 135 | WM_COMMAND := 0x0111 136 | WM_SYSCOMMAND := 0x0112 137 | WM_TIMER := 0x0113 138 | WM_HSCROLL := 0x0114 139 | WM_VSCROLL := 0x0115 140 | WM_INITMENU := 0x0116 141 | WM_INITMENUPOPUP := 0x0117 142 | WM_MENUSELECT := 0x011F 143 | WM_MENUCHAR := 0x0120 144 | WM_ENTERIDLE := 0x0121 145 | 146 | WM_CTLCOLORMSGBOX := 0x0132 147 | WM_CTLCOLOREDIT := 0x0133 148 | WM_CTLCOLORLISTBOX := 0x0134 149 | WM_CTLCOLORBTN := 0x0135 150 | WM_CTLCOLORDLG := 0x0136 151 | WM_CTLCOLORSCROLLBAR := 0x0137 152 | WM_CTLCOLORSTATIC := 0x0138 153 | 154 | WM_MOUSEFIRST := 0x0200 155 | WM_MOUSEMOVE := 0x0200 156 | WM_LBUTTONDOWN := 0x0201 157 | WM_LBUTTONUP := 0x0202 158 | WM_LBUTTONDBLCLK := 0x0203 159 | WM_RBUTTONDOWN := 0x0204 160 | WM_RBUTTONUP := 0x0205 161 | WM_RBUTTONDBLCLK := 0x0206 162 | WM_MBUTTONDOWN := 0x0207 163 | WM_MBUTTONUP := 0x0208 164 | WM_MBUTTONDBLCLK := 0x0209 165 | WM_MOUSEWHEEL := 0x020A 166 | WM_MOUSEHWHEEL := 0x020E 167 | 168 | WM_PARENTNOTIFY := 0x0210 169 | WM_ENTERMENULOOP := 0x0211 170 | WM_EXITMENULOOP := 0x0212 171 | WM_NEXTMENU := 0x0213 172 | WM_SIZING := 0x0214 173 | WM_CAPTURECHANGED := 0x0215 174 | WM_MOVING := 0x0216 175 | WM_POWERBROADCAST := 0x0218 176 | WM_DEVICECHANGE := 0x0219 177 | 178 | WM_MDICREATE := 0x0220 179 | WM_MDIDESTROY := 0x0221 180 | WM_MDIACTIVATE := 0x0222 181 | WM_MDIRESTORE := 0x0223 182 | WM_MDINEXT := 0x0224 183 | WM_MDIMAXIMIZE := 0x0225 184 | WM_MDITILE := 0x0226 185 | WM_MDICASCADE := 0x0227 186 | WM_MDIICONARRANGE := 0x0228 187 | WM_MDIGETACTIVE := 0x0229 188 | WM_MDISETMENU := 0x0230 189 | WM_ENTERSIZEMOVE := 0x0231 190 | WM_EXITSIZEMOVE := 0x0232 191 | WM_DROPFILES := 0x0233 192 | WM_MDIREFRESHMENU := 0x0234 193 | 194 | WM_IME_SETCONTEXT := 0x0281 195 | WM_IME_NOTIFY := 0x0282 196 | WM_IME_CONTROL := 0x0283 197 | WM_IME_COMPOSITIONFULL := 0x0284 198 | WM_IME_SELECT := 0x0285 199 | WM_IME_CHAR := 0x0286 200 | WM_IME_KEYDOWN := 0x0290 201 | WM_IME_KEYUP := 0x0291 202 | 203 | WM_MOUSEHOVER := 0x02A1 204 | WM_NCMOUSELEAVE := 0x02A2 205 | WM_MOUSELEAVE := 0x02A3 206 | 207 | WM_CUT := 0x0300 208 | WM_COPY := 0x0301 209 | WM_PASTE := 0x0302 210 | WM_CLEAR := 0x0303 211 | WM_UNDO := 0x0304 212 | 213 | WM_RENDERFORMAT := 0x0305 214 | WM_RENDERALLFORMATS := 0x0306 215 | WM_DESTROYCLIPBOARD := 0x0307 216 | WM_DRAWCLIPBOARD := 0x0308 217 | WM_PAINTCLIPBOARD := 0x0309 218 | WM_VSCROLLCLIPBOARD := 0x030A 219 | WM_SIZECLIPBOARD := 0x030B 220 | WM_ASKCBFORMATNAME := 0x030C 221 | WM_CHANGECBCHAIN := 0x030D 222 | WM_HSCROLLCLIPBOARD := 0x030E 223 | WM_QUERYNEWPALETTE := 0x030F 224 | WM_PALETTEISCHANGING := 0x0310 225 | WM_PALETTECHANGED := 0x0311 226 | 227 | WM_HOTKEY := 0x0312 228 | WM_PRINT := 0x0317 229 | WM_PRINTCLIENT := 0x0318 230 | 231 | WM_HANDHELDFIRST := 0x0358 232 | WM_HANDHELDLAST := 0x035F 233 | WM_PENWINFIRST := 0x0380 234 | WM_PENWINLAST := 0x038F 235 | WM_COALESCE_FIRST := 0x0390 236 | WM_COALESCE_LAST := 0x039F 237 | WM_DDE_FIRST := 0x03E0 238 | WM_DDE_INITIATE := 0x03E0 239 | WM_DDE_TERMINATE := 0x03E1 240 | WM_DDE_ADVISE := 0x03E2 241 | WM_DDE_UNADVISE := 0x03E3 242 | WM_DDE_ACK := 0x03E4 243 | WM_DDE_DATA := 0x03E5 244 | WM_DDE_REQUEST := 0x03E6 245 | WM_DDE_POKE := 0x03E7 246 | WM_DDE_EXECUTE := 0x03E8 247 | WM_DDE_LAST := 0x03E8 248 | 249 | WM_USER := 0x0400 250 | WM_APP := 0x8000251 | 252 | 253 | -------------------------------------------------------------------------------- /docs/misc/Styles.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |
This page lists some styles and extended styles which can be set or retrieved with the methods Gui.Opt and GuiControl.Opt, and with the built-in functions WinSetStyle, WinSetExStyle, WinGetStyle, WinGetExStyle, ControlSetStyle, ControlSetExStyle, ControlGetStyle and ControlGetExStyle.
15 | 16 |By default, a GUI window uses WS_POPUP, WS_CAPTION, WS_SYSMENU, and WS_MINIMIZEBOX. For a GUI window, WS_CLIPSIBLINGS is always enabled and cannot be disabled.
29 |Style | 32 |Hex | 33 |Description | 34 |
---|---|---|
WS_BORDER | 37 |0x800000 | 38 |+/-Border. Creates a window that has a thin-line border. | 39 |
WS_POPUP | 42 |0x80000000 | 43 |Creates a pop-up window. This style cannot be used with the WS_CHILD style. | 44 |
WS_CAPTION | 47 |0xC00000 | 48 |+/-Caption. Creates a window that has a title bar. This style is a numerical combination of WS_BORDER and WS_DLGFRAME. | 49 |
WS_CLIPSIBLINGS | 52 |0x4000000 | 53 |Clips child windows relative to each other; that is, when a particular child window receives a WM_PAINT message, the WS_CLIPSIBLINGS style clips all other overlapping child windows out of the region of the child window to be updated. If WS_CLIPSIBLINGS is not specified and child windows overlap, it is possible, when drawing within the client area of a child window, to draw within the client area of a neighboring child window. | 54 |
WS_DISABLED | 57 |0x8000000 | 58 |+/-Disabled. Creates a window that is initially disabled. | 59 |
WS_DLGFRAME | 62 |0x400000 | 63 |Creates a window that has a border of a style typically used with dialog boxes. | 64 |
WS_GROUP | 67 |0x20000 | 68 |+/-Group. Indicates that this control is the first one in a group of controls. This style is automatically applied to manage the "only one at a time" behavior of radio buttons. In the rare case where two groups of radio buttons are added consecutively (with no other control types in between them), this style may be applied manually to the first control of the second radio group, which splits it off from the first. | 69 |
WS_HSCROLL | 72 |0x100000 | 73 |Creates a window that has a horizontal scroll bar. | 74 |
WS_MAXIMIZE | 77 |0x1000000 | 78 |Creates a window that is initially maximized. | 79 |
WS_MAXIMIZEBOX | 82 |0x10000 | 83 |+/-MaximizeBox. Creates a window that has a maximize button. Cannot be combined with the WS_EX_CONTEXTHELP style. The WS_SYSMENU style must also be specified. | 84 |
WS_MINIMIZE | 87 |0x20000000 | 88 |Creates a window that is initially minimized. | 89 |
WS_MINIMIZEBOX | 92 |0x20000 | 93 |+/-MinimizeBox. Creates a window that has a minimize button. Cannot be combined with the WS_EX_CONTEXTHELP style. The WS_SYSMENU style must also be specified. | 94 |
WS_OVERLAPPED | 97 |0x0 | 98 |Creates an overlapped window. An overlapped window has a title bar and a border. Same as the WS_TILED style. | 99 |
WS_OVERLAPPEDWINDOW | 102 |0xCF0000 | 103 |Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles. Same as the WS_TILEDWINDOW style. | 104 |
WS_POPUPWINDOW | 107 |0x80880000 | 108 |Creates a pop-up window with WS_BORDER, WS_POPUP, and WS_SYSMENU styles. The WS_CAPTION and WS_POPUPWINDOW styles must be combined to make the window menu visible. | 109 |
WS_SIZEBOX | 112 |0x40000 | 113 |+/-Resize. Creates a window that has a sizing border. Same as the WS_THICKFRAME style. | 114 |
WS_SYSMENU | 117 |0x80000 | 118 |+/-SysMenu. Creates a window that has a window menu on its title bar. The WS_CAPTION style must also be specified. | 119 |
WS_TABSTOP | 122 |0x10000 | 123 |+/-Tabstop. Specifies a control that can receive the keyboard focus when the user presses Tab. Pressing Tab changes the keyboard focus to the next control with the WS_TABSTOP style. | 124 |
WS_THICKFRAME | 127 |0x40000 | 128 |Creates a window that has a sizing border. Same as the WS_SIZEBOX style. | 129 |
WS_VSCROLL | 132 |0x200000 | 133 |Creates a window that has a vertical scroll bar. | 134 |
WS_VISIBLE | 137 |0x10000000 | 138 |Creates a window that is initially visible. | 139 |
WS_CHILD | 142 |0x40000000 | 143 |Creates a child window. A window with this style cannot have a menu bar. This style cannot be used with the WS_POPUP style. | 144 |
These styles affect the Text control. It has neither default styles nor forced styles.
149 |Style | 152 |Hex | 153 |Description | 154 |
---|---|---|
SS_BLACKFRAME | 157 |0x7 | 158 |Specifies a box with a frame drawn in the same color as the window frames. This color is black in the default color scheme. | 159 |
SS_BLACKRECT | 162 |0x4 | 163 |Specifies a rectangle filled with the current window frame color. This color is black in the default color scheme. | 164 |
SS_CENTER | 167 |0x1 | 168 |+/-Center. Specifies a simple rectangle and centers the text in the rectangle. The control automatically wraps words that extend past the end of a line to the beginning of the next centered line. | 169 |
SS_CENTERIMAGE | 172 |0x200 | 173 |
174 | If the control contains a single line of text, the text is centered vertically within the available height of the control. 175 | |
176 |
SS_ETCHEDFRAME | 179 |0x12 | 180 |Draws the frame of the static control using the EDGE_ETCHED edge style. | 181 |
SS_ETCHEDHORZ | 184 |0x10 | 185 |Draws the top and bottom edges of the static control using the EDGE_ETCHED edge style. | 186 |
SS_ETCHEDVERT | 189 |0x11 | 190 |Draws the left and right edges of the static control using the EDGE_ETCHED edge style. | 191 |
SS_GRAYFRAME | 194 |0x8 | 195 |Specifies a box with a frame drawn with the same color as the screen background (desktop). This color is gray in the default color scheme. | 196 |
SS_GRAYRECT | 199 |0x5 | 200 |Specifies a rectangle filled with the current screen background color. This color is gray in the default color scheme. | 201 |
SS_LEFT | 204 |0x0 | 205 |+/-Left. This is the default. It specifies a simple rectangle and left-aligns the text in the rectangle. The text is formatted before it is displayed. Words that extend past the end of a line are automatically wrapped to the beginning of the next left-aligned line. Words that are longer than the width of the control are truncated. | 206 |
SS_LEFTNOWORDWRAP | 209 |0xC | 210 |+/-Wrap. Specifies a rectangle and left-aligns the text in the rectangle. Tabs are expanded, but words are not wrapped. Text that extends past the end of a line is clipped. | 211 |
SS_NOPREFIX | 214 |0x80 | 215 |Prevents interpretation of any ampersand (&) characters in the control's text as accelerator prefix characters. This can be useful when file names or other strings that might contain an ampersand (&) must be displayed within a text control. | 216 |
SS_NOTIFY | 219 |0x100 | 220 |Sends the parent window the STN_CLICKED notification when the user clicks the control. | 221 |
SS_RIGHT | 224 |0x2 | 225 |+/-Right. Specifies a rectangle and right-aligns the specified text in the rectangle. | 226 |
SS_SUNKEN | 229 |0x1000 | 230 |Draws a half-sunken border around a static control. | 231 |
SS_WHITEFRAME | 234 |0x9 | 235 |Specifies a box with a frame drawn with the same color as the window background. This color is white in the default color scheme. | 236 |
SS_WHITERECT | 239 |0x6 | 240 |Specifies a rectangle filled with the current window background color. This color is white in the default color scheme. | 241 |
These styles affect the Edit control. By default, it uses WS_TABSTOP and WS_EX_CLIENTEDGE (extended style E0x200). It has no forced styles.
246 |If an Edit control is auto-detected as multi-line due to its starting contents containing multiple lines, its height being taller than 1 row, or its row-count having been explicitly specified as greater than 1, the following styles will be applied by default: WS_VSCROLL, ES_WANTRETURN, and ES_AUTOVSCROLL.
247 |If an Edit control is auto-detected as a single line, it defaults to having ES_AUTOHSCROLL.
248 |Style | 251 |Hex | 252 |Description | 253 |
---|---|---|
ES_AUTOHSCROLL | 256 |0x80 | 257 |+/-Wrap for multi-line edits, and +/-Limit for single-line edits. Automatically scrolls text to the right by 10 characters when the user types a character at the end of the line. When the user presses Enter, the control scrolls all text back to the zero position. | 258 |
ES_AUTOVSCROLL | 261 |0x40 | 262 |Scrolls text up one page when the user presses Enter on the last line. | 263 |
ES_CENTER | 266 |0x1 | 267 |+/-Center. Centers text in a multiline edit control. | 268 |
ES_LOWERCASE | 271 |0x10 | 272 |+/-Lowercase. Converts all characters to lowercase as they are typed into the edit control. | 273 |
ES_NOHIDESEL | 276 |0x100 | 277 |Negates the default behavior for an edit control. The default behavior hides the selection when the control loses the input focus and inverts the selection when the control receives the input focus. If you specify ES_NOHIDESEL, the selected text is inverted, even if the control does not have the focus. | 278 |
ES_NUMBER | 281 |0x2000 | 282 |+/-Number. Prevents the user from typing anything other than digits in the control. | 283 |
ES_OEMCONVERT | 286 |0x400 | 287 |This style is most useful for edit controls that contain file names. | 288 |
ES_MULTILINE | 291 |0x4 | 292 |+/-Multi. Designates a multiline edit control. The default is a single-line edit control. | 293 |
ES_PASSWORD | 296 |0x20 | 297 |+/-Password. Displays a masking character in place of each character that is typed into the edit control, which conceals the text. | 298 |
ES_READONLY | 301 |0x800 | 302 |+/-ReadOnly. Prevents the user from typing or editing text in the edit control. | 303 |
ES_RIGHT | 306 |0x2 | 307 |+/-Right. Right-aligns text in a multiline edit control. | 308 |
ES_UPPERCASE | 311 |0x8 | 312 |+/-Uppercase. Converts all characters to uppercase as they are typed into the edit control. | 313 |
ES_WANTRETURN | 316 |0x1000 | 317 |+/-WantReturn. Specifies that a carriage return be inserted when the user presses Enter while typing text into a multiline edit control in a dialog box. If you do not specify this style, pressing Enter has the same effect as pressing the dialog box's default push button. This style has no effect on a single-line edit control. | 318 |
These styles affect the UpDown control. By default, it uses UDS_ARROWKEYS, UDS_ALIGNRIGHT, UDS_SETBUDDYINT, and UDS_AUTOBUDDY. It has no forced styles.
323 |Style | 326 |Hex | 327 |Description | 328 |
---|---|---|
UDS_WRAP | 331 |0x1 | 332 |Named option "Wrap". Causes the control to wrap around to the other end of its range when the user attempts to go beyond the minimum or maximum. Without Wrap, the control stops when the minimum or maximum is reached. | 333 |
UDS_SETBUDDYINT | 336 |0x2 | 337 |Causes the UpDown control to set the text of the buddy control (using the WM_SETTEXT message) when the position changes. However, if the buddy is a ListBox, the ListBox's current selection is changed instead. | 338 |
UDS_ALIGNRIGHT | 341 |0x4 | 342 |Named option "Right" (default). Positions UpDown on the right side of its buddy control. | 343 |
UDS_ALIGNLEFT | 346 |0x8 | 347 |Named option "Left". Positions UpDown on the left side of its buddy control. | 348 |
UDS_AUTOBUDDY | 351 |0x10 | 352 |Automatically selects the previous control in the z-order as the UpDown control's buddy control. | 353 |
UDS_ARROWKEYS | 356 |0x20 | 357 |Allows the user to press ↑ or ↓ on the keyboard to increase or decrease the UpDown control's position. | 358 |
UDS_HORZ | 361 |0x40 | 362 |Named option "Horz". Causes the control's arrows to point left and right instead of up and down. | 363 |
UDS_NOTHOUSANDS | 366 |0x80 | 367 |Does not insert a thousands separator between every three decimal digits in the buddy control. | 368 |
UDS_HOTTRACK | 371 |0x100 | 372 |Causes the control to exhibit "hot tracking" behavior. That is, it highlights the control's buttons as the mouse passes over them. This flag may be ignored if the desktop theme overrides it. | 373 |
These styles affect the Picture control. It has no default styles. The style SS_ICON (for icons and cursors) or SS_BITMAP (for other image types) is always enabled and cannot be disabled.
378 |Style | 381 |Hex | 382 |Description | 383 |
---|---|---|
SS_REALSIZECONTROL | 386 |0x40 | 387 |Adjusts the bitmap to fit the size of the control. | 388 |
SS_CENTERIMAGE | 391 |0x200 | 392 |
393 | Centers the bitmap in the control. If the bitmap is too large, it will be clipped. 394 | |
395 |
These styles affect the Button, CheckBox, Radio, or GroupBox controls.
400 |By default, each of these controls except GroupBox uses the styles BS_MULTILINE (unless it has no explicitly set width or height, nor any CR/LF characters in their text) and WS_TABSTOP (however, Radio controls other than the first of each radio group lack WS_TABSTOP).
401 |The following styles are always enabled and cannot be disabled:
402 |Style | 411 |Hex | 412 |Description | 413 |
---|---|---|
BS_AUTO3STATE | 416 |0x6 | 417 |Creates a button that is the same as a three-state check box, except that the box changes its state when the user selects it. The state cycles through checked, indeterminate, and cleared. | 418 |
BS_AUTOCHECKBOX | 421 |0x3 | 422 |Creates a button that is the same as a check box, except that the check state automatically toggles between checked and cleared each time the user selects the check box. | 423 |
BS_AUTORADIOBUTTON | 426 |0x9 | 427 |Creates a button that is the same as a radio button, except that when the user selects it, the system automatically sets the button's check state to checked and automatically sets the check state for all other buttons in the same group to cleared. | 428 |
BS_LEFT | 431 |0x100 | 432 |+/-Left. Left-aligns the text. | 433 |
BS_PUSHBUTTON | 436 |0x0 | 437 |Creates a push button that posts a WM_COMMAND message to the owner window when the user selects the button. | 438 |
BS_PUSHLIKE | 441 |0x1000 | 442 |Makes a checkbox or radio button look and act like a push button. The button looks raised when it isn't pushed or checked, and sunken when it is pushed or checked. | 443 |
BS_RIGHT | 446 |0x200 | 447 |+/-Right. Right-aligns the text. | 448 |
BS_RIGHTBUTTON | 451 |0x20 | 452 |+Right (i.e. +Right includes both BS_RIGHT and BS_RIGHTBUTTON, but -Right removes only BS_RIGHT, not BS_RIGHTBUTTON). Positions a checkbox square or radio button circle on the right side of the control's available width instead of the left. | 453 |
BS_BOTTOM | 456 |0x800 | 457 |Places the text at the bottom of the control's available height. | 458 |
BS_CENTER | 461 |0x300 | 462 |+/-Center. Centers the text horizontally within the control's available width. | 463 |
BS_DEFPUSHBUTTON | 466 |0x1 | 467 |+/-Default. Creates a push button with a heavy black border. If the button is in a dialog box, the user can select the button by pressing Enter, even when the button does not have the input focus. This style is useful for enabling the user to quickly select the most likely option. | 468 |
BS_MULTILINE | 471 |0x2000 | 472 |+/-Wrap. Wraps the text to multiple lines if the text is too long to fit on a single line in the control's available width. This also allows linefeed (`n) to start new lines of text. | 473 |
BS_NOTIFY | 476 |0x4000 | 477 |Enables a button to send BN_KILLFOCUS and BN_SETFOCUS notification codes to its parent window. Note that buttons send the BN_CLICKED notification code regardless of whether it has this style. To get BN_DBLCLK notification codes, the button must have the BS_RADIOBUTTON or BS_OWNERDRAW style. | 478 |
BS_TOP | 481 |0x400 | 482 |Places text at the top of the control's available height. | 483 |
BS_VCENTER | 486 |0xC00 | 487 |Vertically centers text in the control's available height. | 488 |
BS_FLAT | 491 |0x8000 | 492 |Specifies that the button is two-dimensional; it does not use the default shading to create a 3-D effect. | 493 |
BS_GROUPBOX | 496 |0x7 | 497 |Creates a rectangle in which other controls can be grouped. Any text associated with this style is displayed in the rectangle's upper left corner. | 498 |
These styles affect the DropDownList and ComboBox controls.
503 |By default, each of these controls uses WS_TABSTOP. In addition, a DropDownList control uses WS_VSCROLL, and a ComboBox control uses WS_VSCROLL and CBS_AUTOHSCROLL.
504 |The following styles are always enabled and cannot be disabled:
505 |Style | 512 |Hex | 513 |Description | 514 |
---|---|---|
CBS_AUTOHSCROLL | 517 |0x40 | 518 |+/-Limit. Automatically scrolls the text in an edit control to the right when the user types a character at the end of the line. If this style is not set, only text that fits within the rectangular boundary is enabled. | 519 |
CBS_DISABLENOSCROLL | 522 |0x800 | 523 |Shows a disabled vertical scroll bar in the drop-down list when it does not contain enough items to scroll. Without this style, the scroll bar is hidden when the drop-down list does not contain enough items. | 524 |
CBS_DROPDOWN | 527 |0x2 | 528 |Similar to CBS_SIMPLE, except that the list box is not displayed unless the user selects an icon next to the edit control. | 529 |
CBS_DROPDOWNLIST | 532 |0x3 | 533 |Similar to CBS_DROPDOWN, except that the edit control is replaced by a static text item that displays the current selection in the list box. | 534 |
CBS_LOWERCASE | 537 |0x4000 | 538 |+/-Lowercase. Converts to lowercase any uppercase characters that are typed into the edit control of a combo box. | 539 |
CBS_NOINTEGRALHEIGHT | 542 |0x400 | 543 |Specifies that the combo box will be exactly the size specified by the application when it created the combo box. Usually, Windows CE sizes a combo box so that it does not display partial items. | 544 |
CBS_OEMCONVERT | 547 |0x80 | 548 |Converts text typed in the combo box edit control from the Windows CE character set to the OEM character set and then back to the Windows CE set. This style is most useful for combo boxes that contain file names. It applies only to combo boxes created with the CBS_DROPDOWN style. | 549 |
CBS_SIMPLE | 552 |0x1 | 553 |+/-Simple (ComboBox only). Displays the drop-down list at all times. The current selection in the list is displayed in the edit control. | 554 |
CBS_SORT | 557 |0x100 | 558 |+/-Sort. Sorts the items in the drop-list alphabetically. | 559 |
CBS_UPPERCASE | 562 |0x2000 | 563 |+/-Uppercase. Converts to uppercase any lowercase characters that are typed into the edit control of a ComboBox. | 564 |
These styles affect the ListBox control. By default, it uses WS_TABSTOP, LBS_USETABSTOPS, WS_VSCROLL, and WS_EX_CLIENTEDGE (extended style E0x200). The style LBS_NOTIFY (supports detection of double-clicks) is always enabled and cannot be disabled.
569 |Style | 572 |Hex | 573 |Description | 574 |
---|---|---|
LBS_DISABLENOSCROLL | 577 |0x1000 | 578 |Shows a disabled vertical scroll bar for the list box when the box does not contain enough items to scroll. If you do not specify this style, the scroll bar is hidden when the list box does not contain enough items. | 579 |
LBS_NOINTEGRALHEIGHT | 582 |0x100 | 583 |Specifies that the list box will be exactly the size specified by the application when it created the list box. | 584 |
LBS_EXTENDEDSEL | 587 |0x800 | 588 |+/-Multi. Allows multiple selections via control-click and shift-click. | 589 |
LBS_MULTIPLESEL | 592 |0x8 | 593 |A simplified version of multi-select in which control-click and shift-click are not necessary because normal left clicks serve to extend the selection or de-select a selected item. | 594 |
LBS_NOSEL | 597 |0x4000 | 598 |+/-ReadOnly. Specifies that the user can view list box strings but cannot select them. | 599 |
LBS_NOTIFY | 602 |0x1 | 603 |Causes the list box to send a notification code to the parent window whenever the user clicks a list box item (LBN_SELCHANGE), double-clicks an item (LBN_DBLCLK), or cancels the selection (LBN_SELCANCEL). | 604 |
LBS_SORT | 607 |0x2 | 608 |+/-Sort. Sorts the items in the list box alphabetically. | 609 |
LBS_USETABSTOPS | 612 |0x80 | 613 |Enables a ListBox to recognize and expand tab characters when drawing its strings. The default tab positions are 32 dialog box units apart. A dialog box unit is equal to one-fourth of the current dialog box base-width unit. | 614 |
These styles affect the ListView control. By default, it uses WS_TABSTOP, LVS_REPORT, LVS_SHOWSELALWAYS, LVS_EX_FULLROWSELECT, LVS_EX_HEADERDRAGDROP, and WS_EX_CLIENTEDGE (extended style E0x200). It has no forced styles.
619 |Style | 622 |Hex | 623 |Description | 624 |
---|---|---|
LVS_ALIGNLEFT | 627 |0x800 | 628 |Items are left-aligned in icon and small icon view. | 629 |
LVS_ALIGNTOP | 632 |0x0 | 633 |Items are aligned with the top of the list-view control in icon and small icon view. This is the default. | 634 |
LVS_AUTOARRANGE | 637 |0x100 | 638 |Icons are automatically kept arranged in icon and small icon view. | 639 |
LVS_EDITLABELS | 642 |0x200 | 643 |+/-ReadOnly. Specifying -ReadOnly (or +0x200) allows the user to edit the first field of each row in place. | 644 |
LVS_ICON | 647 |0x0 | 648 |+Icon. Specifies large-icon view. | 649 |
LVS_LIST | 652 |0x3 | 653 |+List. Specifies list view. | 654 |
LVS_NOCOLUMNHEADER | 657 |0x4000 | 658 |+/-Hdr. Avoids displaying column headers in report view. | 659 |
LVS_NOLABELWRAP | 662 |0x80 | 663 |Item text is displayed on a single line in icon view. By default, item text may wrap in icon view. | 664 |
LVS_NOSCROLL | 667 |0x2000 | 668 |Scrolling is disabled. All items must be within the client area. This style is not compatible with the LVS_LIST or LVS_REPORT styles. | 669 |
LVS_NOSORTHEADER | 672 |0x8000 | 673 |+/-NoSortHdr. Column headers do not work like buttons. This style can be used if clicking a column header in report view does not carry out an action, such as sorting. | 674 |
LVS_OWNERDATA | 677 |0x1000 | 678 |This style specifies a virtual list-view control (not directly supported by AutoHotkey). | 679 |
LVS_OWNERDRAWFIXED | 682 |0x400 | 683 |The owner window can paint items in report view in response to WM_DRAWITEM messages (not directly supported by AutoHotkey). | 684 |
LVS_REPORT | 687 |0x1 | 688 |+Report. Specifies report view. | 689 |
LVS_SHAREIMAGELISTS | 692 |0x40 | 693 |The image list will not be deleted when the control is destroyed. This style enables the use of the same image lists with multiple list-view controls. | 694 |
LVS_SHOWSELALWAYS | 697 |0x8 | 698 |The selection, if any, is always shown, even if the control does not have keyboard focus. | 699 |
LVS_SINGLESEL | 702 |0x4 | 703 |+/-Multi. Only one item at a time can be selected. By default, multiple items can be selected. | 704 |
LVS_SMALLICON | 707 |0x2 | 708 |+IconSmall. Specifies small-icon view. | 709 |
LVS_SORTASCENDING | 712 |0x10 | 713 |+/-Sort. Rows are sorted in ascending order based on the contents of the first field. | 714 |
LVS_SORTDESCENDING | 717 |0x20 | 718 |+/-SortDesc. Same as above but in descending order. | 719 |
Extended ListView styles require the LV prefix when used with the Gui methods/properties. Some extended styles introduced in Windows XP or later versions are not listed here. For a full list, see Microsoft Docs: Extended List-View Styles.
722 |Extended Style | 725 |Hex | 726 |Description | 727 |
---|---|---|
LVS_EX_BORDERSELECT | 730 |LV0x8000 | 731 |When an item is selected, the border color of the item changes rather than the item being highlighted (might be non-functional in recent operating systems). | 732 |
LVS_EX_CHECKBOXES | 735 |LV0x4 | 736 |
737 | +/-Checked. Displays a checkbox with each item. When set to this style, the control creates and sets a state image list with two images using DrawFrameControl. State image 1 is the unchecked box, and state image 2 is the checked box. Setting the state image to zero removes the check box altogether. 738 |Checkboxes are visible and functional with all list-view modes except the tile view mode. Clicking a checkbox in tile view mode only selects the item; the state does not change. 739 | |
740 |
LVS_EX_DOUBLEBUFFER | 743 |LV0x10000 | 744 |
745 | Paints via double-buffering, which reduces flicker. This extended style also enables alpha-blended marquee selection on systems where it is supported. 746 | |
747 |
LVS_EX_FLATSB | 750 |LV0x100 | 751 |Enables flat scroll bars in the list view. | 752 |
LVS_EX_FULLROWSELECT | 755 |LV0x20 | 756 |When a row is selected, all its fields are highlighted. This style is available only in conjunction with the LVS_REPORT style. | 757 |
LVS_EX_GRIDLINES | 760 |LV0x1 | 761 |+/-Grid. Displays gridlines around rows and columns. This style is available only in conjunction with the LVS_REPORT style. | 762 |
LVS_EX_HEADERDRAGDROP | 765 |LV0x10 | 766 |Enables drag-and-drop reordering of columns in a list-view control. This style is only available to list-view controls that use the LVS_REPORT style. | 767 |
LVS_EX_INFOTIP | 770 |LV0x400 | 771 |When a list-view control uses this style, the LVN_GETINFOTIP notification message is sent to the parent window before displaying an item's ToolTip. | 772 |
LVS_EX_LABELTIP | 775 |LV0x4000 | 776 |If a partially hidden label in any list-view mode lacks ToolTip text, the list-view control will unfold the label. If this style is not set, the list-view control will unfold partly hidden labels only for the large icon mode. Note: On some versions of Windows, this style might not work properly if the GUI window is set to be always-on-top. | 777 |
LVS_EX_MULTIWORKAREAS | 780 |LV0x2000 | 781 |If the list-view control has the LVS_AUTOARRANGE style, the control will not autoarrange its icons until one or more work areas are defined (see LVM_SETWORKAREAS). To be effective, this style must be set before any work areas are defined and any items have been added to the control. | 782 |
LVS_EX_ONECLICKACTIVATE | 785 |LV0x40 | 786 |The list-view control sends an LVN_ITEMACTIVATE notification message to the parent window when the user clicks an item. This style also enables hot tracking in the list-view control. Hot tracking means that when the cursor moves over an item, it is highlighted but not selected. | 787 |
LVS_EX_REGIONAL | 790 |LV0x200 | 791 |Sets the list-view window region to include only the item icons and text using SetWindowRgn. Any area that is not part of an item is excluded from the window region. This style is only available to list-view controls that use the LVS_ICON style. | 792 |
LVS_EX_SIMPLESELECT | 795 |LV0x100000 | 796 |In icon view, moves the state image of the item to the top right of the large icon rendering. In views other than icon view there is no change. When the user changes the state by using the space bar, all selected items cycle over, not the item with the focus. | 797 |
LVS_EX_SUBITEMIMAGES | 800 |LV0x2 | 801 |Allows images to be displayed for fields beyond the first. This style is available only in conjunction with the LVS_REPORT style. | 802 |
LVS_EX_TRACKSELECT | 805 |LV0x8 | 806 |Enables hot-track selection in a list-view control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay can be changed from the default system setting with a LVM_SETHOVERTIME message. This style applies to all styles of list-view control. You can check whether hot-track selection is enabled by calling SystemParametersInfo. | 807 |
LVS_EX_TWOCLICKACTIVATE | 810 |LV0x80 | 811 |The list-view control sends an LVN_ITEMACTIVATE notification message to the parent window when the user double-clicks an item. This style also enables hot tracking in the list-view control. Hot tracking means that when the cursor moves over an item, it is highlighted but not selected. | 812 |
LVS_EX_UNDERLINECOLD | 815 |LV0x1000 | 816 |Causes those non-hot items that may be activated to be displayed with underlined text. This style requires that LVS_EX_TWOCLICKACTIVATE be set also. | 817 |
LVS_EX_UNDERLINEHOT | 820 |LV0x800 | 821 |Causes those hot items that may be activated to be displayed with underlined text. This style requires that LVS_EX_ONECLICKACTIVATE or LVS_EX_TWOCLICKACTIVATE also be set. | 822 |
These styles affect the TreeView control. By default, it uses WS_TABSTOP, TVS_SHOWSELALWAYS, TVS_HASLINES, TVS_LINESATROOT, TVS_HASBUTTONS, and WS_EX_CLIENTEDGE (extended style E0x200). It has no forced styles.
827 |Style | 830 |Hex | 831 |Description | 832 |
---|---|---|
TVS_CHECKBOXES | 835 |0x100 | 836 |+/-Checked. Displays a checkbox next to each item. | 837 |
TVS_DISABLEDRAGDROP | 840 |0x10 | 841 |Prevents the tree-view control from sending TVN_BEGINDRAG notification messages. | 842 |
TVS_EDITLABELS | 845 |0x8 | 846 |+/-ReadOnly. Allows the user to edit the names of tree-view items. | 847 |
TVS_FULLROWSELECT | 850 |0x1000 | 851 |Enables full-row selection in the tree view. The entire row of the selected item is highlighted, and clicking anywhere on an item's row causes it to be selected. This style cannot be used in conjunction with the TVS_HASLINES style. | 852 |
TVS_HASBUTTONS | 855 |0x1 | 856 |+/-Buttons. Displays plus (+) and minus (-) buttons next to parent items. The user clicks the buttons to expand or collapse a parent item's list of child items. To include buttons with items at the root of the tree view, TVS_LINESATROOT must also be specified. | 857 |
TVS_HASLINES | 860 |0x2 | 861 |+/-Lines. Uses lines to show the hierarchy of items. | 862 |
TVS_INFOTIP | 865 |0x800 | 866 |Obtains ToolTip information by sending the TVN_GETINFOTIP notification. | 867 |
TVS_LINESATROOT | 870 |0x4 | 871 |+/-Lines. Uses lines to link items at the root of the tree-view control. This value is ignored if TVS_HASLINES is not also specified. | 872 |
TVS_NOHSCROLL | 875 |0x8000 | 876 |+/-HScroll. Disables horizontal scrolling in the control. The control will not display any horizontal scroll bars. | 877 |
TVS_NONEVENHEIGHT | 880 |0x4000 | 881 |Sets the height of the items to an odd height with the TVM_SETITEMHEIGHT message. By default, the height of items must be an even value. | 882 |
TVS_NOSCROLL | 885 |0x2000 | 886 |Disables both horizontal and vertical scrolling in the control. The control will not display any scroll bars. | 887 |
TVS_NOTOOLTIPS | 890 |0x80 | 891 |Disables tooltips. | 892 |
TVS_RTLREADING | 895 |0x40 | 896 |Causes text to be displayed from right-to-left (RTL). Usually, windows display text left-to-right (LTR). | 897 |
TVS_SHOWSELALWAYS | 900 |0x20 | 901 |Causes a selected item to remain selected when the tree-view control loses focus. | 902 |
TVS_SINGLEEXPAND | 905 |0x400 | 906 |Causes the item being selected to expand and the item being unselected to collapse upon selection in the tree-view. If the user holds down Ctrl while selecting an item, the item being unselected will not be collapsed. | 907 |
TVS_TRACKSELECT | 910 |0x200 | 911 |Enables hot tracking of the mouse in a tree-view control. | 912 |
These styles affect the DateTime control. By default, it uses DTS_SHORTDATECENTURYFORMAT and WS_TABSTOP. It has no forced styles.
917 |Style | 920 |Hex | 921 |Description | 922 |
---|---|---|
DTS_UPDOWN | 925 |0x1 | 926 |Provides an up-down control to the right of the control to modify date-time values, which replaces the of the drop-down month calendar that would otherwise be available. | 927 |
DTS_SHOWNONE | 930 |0x2 | 931 |Displays a checkbox inside the control that users can uncheck to make the control have no date/time selected. Whenever the control has no date/time, Gui.Submit and GuiControl.Value will retrieve a blank value (empty string). | 932 |
DTS_SHORTDATEFORMAT | 935 |0x0 | 936 |Displays the date in short format. In some locales, it looks like 6/1/05 or 6/1/2005. On older operating systems, a two-digit year might be displayed. This is why DTS_SHORTDATECENTURYFORMAT is the default and not DTS_SHORTDATEFORMAT. | 937 |
DTS_LONGDATEFORMAT | 940 |0x4 | 941 |Format option "LongDate". Displays the date in long format. In some locales, it looks like Wednesday, June 01, 2005. | 942 |
DTS_SHORTDATECENTURYFORMAT | 945 |0xC | 946 |Format option blank/omitted. Displays the date in short format with four-digit year. In some locales, it looks like 6/1/2005. If the system's version of Comctl32.dll is older than 5.8, this style is not supported and DTS_SHORTDATEFORMAT is automatically substituted. | 947 |
DTS_TIMEFORMAT | 950 |0x9 | 951 |Format option "Time". Displays only the time, which in some locales looks like 5:31:42 PM. | 952 |
DTS_APPCANPARSE | 955 |0x10 | 956 |Not yet supported. Allows the owner to parse user input and take necessary action. It enables users to edit within the client area of the control when they press F2. The control sends DTN_USERSTRING notification messages when users are finished. | 957 |
DTS_RIGHTALIGN | 960 |0x20 | 961 |+/-Right. The calendar will drop down on the right side of the control instead of the left. | 962 |
These styles affect the MonthCal control. By default, it uses WS_TABSTOP. It has no forced styles.
967 |Style | 970 |Hex | 971 |Description | 972 |
---|---|---|
MCS_DAYSTATE | 975 |0x1 | 976 |Makes the control send MCN_GETDAYSTATE notifications to request information about which days should be displayed in bold. [Not yet supported] | 977 |
MCS_MULTISELECT | 980 |0x2 | 981 |
982 | Named option "Multi". Allows the user to select a range of dates rather than being limited to a single date. By default, the maximum range is 366 days, which can be changed by sending the MCM_SETMAXSELCOUNT message to the control. For example: 983 |SendMessage 0x1004, 7, 0, "SysMonthCal321", MyGui ; 7 days. 0x1004 is MCM_SETMAXSELCOUNT.984 | |
985 |
MCS_WEEKNUMBERS | 988 |0x4 | 989 |Displays week numbers (1-52) to the left of each row of days. Week 1 is defined as the first week that contains at least four days. | 990 |
MCS_NOTODAYCIRCLE | 993 |0x8 | 994 |Prevents the circling of today's date within the control. | 995 |
MCS_NOTODAY | 998 |0x10 | 999 |Prevents the display of today's date at the bottom of the control. | 1000 |
These styles affect the Slider control. By default, it uses WS_TABSTOP. It has no forced styles.
1005 |Style | 1008 |Hex | 1009 |Description | 1010 |
---|---|---|
TBS_VERT | 1013 |0x2 | 1014 |+/-Vertical. The control is oriented vertically. | 1015 |
TBS_LEFT | 1018 |0x4 | 1019 |+/-Left. The control displays tick marks at the top of the control (or to its left if TBS_VERT is present). Same as TBS_TOP. | 1020 |
TBS_TOP | 1023 |0x4 | 1024 |same as TBS_LEFT. | 1025 |
TBS_BOTH | 1028 |0x8 | 1029 |+/-Center. The control displays tick marks on both sides of the control. This will be both top and bottom when used with TBS_HORZ or both left and right if used with TBS_VERT. | 1030 |
TBS_AUTOTICKS | 1033 |0x1 | 1034 |The control has a tick mark for each increment in its range of values. Use +/-TickInterval to have more flexibility. | 1035 |
TBS_ENABLESELRANGE | 1038 |0x20 | 1039 |
1040 | The control displays a selection range only. The tick marks at the starting and ending positions of a selection range are displayed as triangles (instead of vertical dashes), and the selection range is highlighted (highlighting might require that the theme be removed via To set the selection range, follow this example, which sets the starting position to 55 and the ending position to 66: 1042 |SendMessage 0x040B, 1, 55, "msctls_trackbar321", WinTitle 1043 | SendMessage 0x040C, 1, 66, "msctls_trackbar321", WinTitle1044 | |
1045 |
TBS_FIXEDLENGTH | 1048 |0x40 | 1049 |+/-Thick. Allows the thumb's size to be changed. | 1050 |
TBS_NOTHUMB | 1053 |0x80 | 1054 |The control does not display the moveable bar. | 1055 |
TBS_NOTICKS | 1058 |0x10 | 1059 |+/-NoTicks. The control does not display any tick marks. | 1060 |
TBS_TOOLTIPS | 1063 |0x100 | 1064 |+/-ToolTip. The control supports tooltips. When a control is created using this style, it automatically creates a default ToolTip control that displays the slider's current position. You can change where the tooltips are displayed by using the TBM_SETTIPSIDE message. | 1065 |
TBS_REVERSED | 1068 |0x200 | 1069 |Unfortunately, this style has no effect on the actual behavior of the control, so there is probably no point in using it (instead, use +Invert in the control's options to reverse it). Depending on OS version, this style might require Internet Explorer 5.0 or greater. | 1070 |
TBS_DOWNISLEFT | 1073 |0x400 | 1074 |Unfortunately, this style has no effect on the actual behavior of the control, so there is probably no point in using it. Depending on OS version, this style might require Internet Explorer 5.01 or greater. | 1075 |
These styles affect the Progress control. It has neither default styles nor forced styles.
1080 |Style | 1083 |Hex | 1084 |Description | 1085 |
---|---|---|
PBS_SMOOTH | 1088 |0x1 | 1089 |+/-Smooth. The progress bar displays progress status in a smooth scrolling bar instead of the default segmented bar. When this style is present, the control automatically reverts to the Classic Theme appearance. | 1090 |
PBS_VERTICAL | 1093 |0x4 | 1094 |+/-Vertical. The progress bar displays progress status vertically, from bottom to top. | 1095 |
PBS_MARQUEE | 1098 |0x8 | 1099 |
1100 | The progress bar moves like a marquee; that is, each change to its position causes the bar to slide further along its available length until it wraps around to the other side. A bar with this style has no defined position. Each attempt to change its position will instead slide the bar by one increment. 1101 |This style is typically used to indicate an ongoing operation whose completion time is unknown. 1102 | |
1103 |
These styles affect the Tab control. By default, it uses WS_TABSTOP and TCS_MULTILINE. The style WS_CLIPSIBLINGS is always enabled and cannot be disabled, while TCS_OWNERDRAWFIXED is forced on or off as required by the control's background color and/or text color.
1108 |Style | 1111 |Hex | 1112 |Description | 1113 |
---|---|---|
TCS_SCROLLOPPOSITE | 1116 |0x1 | 1117 |Unneeded tabs scroll to the opposite side of the control when a tab is selected. | 1118 |
TCS_BOTTOM | 1121 |0x2 | 1122 |+/-Bottom. Tabs appear at the bottom of the control instead of the top. | 1123 |
TCS_RIGHT | 1126 |0x2 | 1127 |Tabs appear vertically on the right side of controls that use the TCS_VERTICAL style. | 1128 |
TCS_MULTISELECT | 1131 |0x4 | 1132 |Multiple tabs can be selected by holding down Ctrl when clicking. This style must be used with the TCS_BUTTONS style. | 1133 |
TCS_FLATBUTTONS | 1136 |0x8 | 1137 |Selected tabs appear as being indented into the background while other tabs appear as being on the same plane as the background. This style only affects tab controls with the TCS_BUTTONS style. | 1138 |
TCS_FORCEICONLEFT | 1141 |0x10 | 1142 |Icons are aligned with the left edge of each fixed-width tab. This style can only be used with the TCS_FIXEDWIDTH style. | 1143 |
TCS_FORCELABELLEFT | 1146 |0x20 | 1147 |
1148 | Labels are aligned with the left edge of each fixed-width tab; that is, the label is displayed immediately to the right of the icon instead of being centered. 1149 |This style can only be used with the TCS_FIXEDWIDTH style, and it implies the TCS_FORCEICONLEFT style. 1150 | |
1151 |
TCS_HOTTRACK | 1154 |0x40 | 1155 |Items under the pointer are automatically highlighted. | 1156 |
TCS_VERTICAL | 1159 |0x80 | 1160 |
1161 | +/-Left or +/-Right. Tabs appear at the left side of the control, with tab text displayed vertically. This style is valid only when used with the TCS_MULTILINE style. To make tabs appear on the right side of the control, also use the TCS_RIGHT style. 1162 |This style will not correctly display the tabs if a custom background color or text color is in effect. To workaround this, specify -Background and/or cDefault in the tab control's options. 1163 | |
1164 |
TCS_BUTTONS | 1167 |0x100 | 1168 |+/-Buttons. Tabs appear as buttons, and no border is drawn around the display area. | 1169 |
TCS_SINGLELINE | 1172 |0x0 | 1173 |+/-Wrap. Only one row of tabs is displayed. The user can scroll to see more tabs, if necessary. This style is the default. | 1174 |
TCS_MULTILINE | 1177 |0x200 | 1178 |+/-Wrap. Multiple rows of tabs are displayed, if necessary, so all tabs are visible at once. | 1179 |
TCS_RIGHTJUSTIFY | 1182 |0x0 | 1183 |
1184 | This is the default. The width of each tab is increased, if necessary, so that each row of tabs fills the entire width of the tab control. 1185 |This window style is ignored unless the TCS_MULTILINE style is also specified. 1186 | |
1187 |
TCS_FIXEDWIDTH | 1190 |0x400 | 1191 |All tabs are the same width. This style cannot be combined with the TCS_RIGHTJUSTIFY style. | 1192 |
TCS_RAGGEDRIGHT | 1195 |0x800 | 1196 |Rows of tabs will not be stretched to fill the entire width of the control. This style is the default. | 1197 |
TCS_FOCUSONBUTTONDOWN | 1200 |0x1000 | 1201 |The tab control receives the input focus when clicked. | 1202 |
TCS_OWNERDRAWFIXED | 1205 |0x2000 | 1206 |The parent window is responsible for drawing tabs. | 1207 |
TCS_TOOLTIPS | 1210 |0x4000 | 1211 |The tab control has a tooltip control associated with it. | 1212 |
TCS_FOCUSNEVER | 1215 |0x8000 | 1216 |The tab control does not receive the input focus when clicked. | 1217 |
These styles affect the StatusBar control. By default, it uses SBARS_TOOLTIPS and SBARS_SIZEGRIP (the latter only if the window is resizable). It has no forced styles.
1222 |Style | 1225 |Hex | 1226 |Description | 1227 |
---|---|---|
SBARS_TOOLTIPS | 1230 |0x800 | 1231 |
1232 | Displays a tooltip when the mouse hovers over a part of the status bar that: 1) has too much text to be fully displayed; or 2) has an icon but no text. 1233 |The text of the tooltip can be set via: 1234 |SendMessage 0x0411, 0, StrPtr("Text to display"), "msctls_statusbar321", MyGui ; 0x0411 is SB_SETTIPTEXTW.1235 | The bold 0 above is the zero-based part number. To use a part other than the first, specify 1 for second, 2 for the third, etc. NOTE: The tooltip might never appear on certain OS versions. 1236 | |
1237 |
SBARS_SIZEGRIP | 1240 |0x100 | 1241 |Includes a sizing grip at the right end of the status bar. A sizing grip is similar to a sizing border; it is a rectangular area that the user can click and drag to resize the parent window. | 1242 |
The current thread is defined as the flow of execution invoked by the most recent event; examples include hotkeys, SetTimer subroutines, custom menu items, and GUI events. The current thread can be executing functions within its own subroutine or within other subroutines called by that subroutine.
16 |Although AutoHotkey doesn't actually use multiple threads, it simulates some of that behavior: If a second thread is started -- such as by pressing another hotkey while the previous is still running -- the current thread will be interrupted (temporarily halted) to allow the new thread to become current. If a third thread is started while the second is still running, both the second and first will be in a dormant state, and so on.
17 |When the current thread finishes, the one most recently interrupted will be resumed, and so on, until all the threads finally finish. When resumed, a thread's settings for things such as SendMode and SetKeyDelay are automatically restored to what they were just prior to its interruption; in other words, a thread will experience no side-effects from having been interrupted (except for a possible change in the active window).
18 |Note: The KeyHistory function/menu-item shows how many threads are in an interrupted state and the ListHotkeys function/menu-item shows which hotkeys have threads.
19 |A single script can have multiple simultaneous MsgBox, InputBox, FileSelect, and DirSelect dialogs. This is achieved by launching a new thread (via hotkey, timed subroutine, custom menu item, etc.) while a prior thread already has a dialog displayed.
20 |By default, a given hotkey or hotstring subroutine cannot be run a second time if it is already running. Use #MaxThreadsPerHotkey to change this behavior.
21 |Related: The Thread function sets the priority or interruptibility of threads.
22 | 23 |Any thread (hotkey, timed subroutine, custom menu item, etc.) with a priority lower than that of the current thread cannot interrupt it. During that time, such timers will not run, and any attempt by the user to create a thread (such as by pressing a hotkey or GUI button) will have no effect, nor will it be buffered. Because of this, it is usually best to design high priority threads to finish quickly, or use Critical instead of making them high priority.
25 |The default priority is 0. All threads use the default priority unless changed by one of the following methods:
26 |The OnExit callback function (if any) will always run when called for, regardless of the current thread's priority.
34 | 35 |For most types of events, new threads are permitted to launch only if the current thread is interruptible. A thread can be uninterruptible for a number of reasons, including:
37 |Unlike high-priority threads, events that occur while the thread is uninterruptible are not discarded. For example, if the user presses a hotkey while the current thread is uninterruptible, the hotkey is buffered indefinitely until the current thread finishes or becomes interruptible, at which time the hotkey is launched as a new thread.
47 |Any thread may be interrupted in emergencies. Emergencies consist of:
48 |To avoid these interruptions, temporarily disable such functions.
54 |A critical thread becomes interruptible when a MsgBox or other dialog is displayed. However, unlike Thread Interrupt, the thread becomes critical (and therefore uninterruptible) again after the user dismisses the dialog.
55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /docs/misc/WinTitle.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |Various built-in functions have a WinTitle parameter, used to identify which window (or windows) to operate on. This parameter can be the title or partial title of the window, and/or any other criteria described on this page.
15 | 16 |Specify any string for WinTitle to identify a window by its title. The title of a window is often visible as text in a title bar at the top of the window. If invisible or only partially visible, the full window title can be revealed via WinGetTitle or Window Spy.
36 |The following example activates the calculator:
37 |WinActivate "Calculator"38 |
SetTitleMatchMode controls how a partial or complete title is compared against the title of each window. Depending on the setting, WinTitle can be an exact title, or it can contain a prefix, a substring which occurs anywhere in the title, or a RegEx pattern. This setting also controls whether the ahk_class and ahk_exe criteria are interpreted as RegEx patterns.
39 |Window titles are case-sensitive, except when using the i) modifier in a RegEx pattern.
40 |Hidden windows are only detected if DetectHiddenWindows is turned on, except with WinShow, which always detects hidden windows.
41 |If multiple windows match WinTitle and any other criteria, the topmost matching window is used. If the active window matches the criteria, it usually takes precedence since it is usually above all other windows. However, if an always-on-top window also matches (and the active window is not always-on-top), it may be used instead.
42 |In [v2.0.6+], it is no longer the case that only the first 1023 characters of the specified window title, ahk_class criterion value, and ahk_exe criterion value are considered for matching purposes. Exceeding the length no longer leads to unexpected results, which rarely occurs, but may be encountered more often if a very long RegEx pattern is used.
43 | 44 |Use the letter A
for WinTitle and omit the other three window parameters (WinText, ExcludeTitle and ExcludeText), to operate on the active window.
The following example retrieves and reports the unique ID (HWND) of the active window:
47 |MsgBox WinExist("A")48 |
The following example creates a hotkey which can be pressed to maximize the active window:
49 |#Up::WinMaximize "A" ; Win+Up50 | 51 |
Specify one or more of the following ahk_ criteria (optionally in addition to a window's title), each separated from the next with exactly one space or tab (any other spaces or tabs are treated as a literal part of the previous criterion). An ahk_ criterion always consists of an ahk_ keyword and its criterion value, separated by zero or more spaces or tabs. For example, ahk_class Notepad
identifies a Notepad window.
The ahk_ keyword and its criterion value do not need to be separated by spaces or tabs. This is primarily useful when specifying ahk_ criteria in combination with variables. For example, you could specify "ahk_pid" PID
instead of "ahk_pid " PID
. In all other cases, however, it is recommended to use at least one space or tab as a separation to improve readability.
Use ahk_class ClassName
in WinTitle to identify a window by its window class.
A window class is a set of attributes that the system uses as a template to create a window. In other words, the class name of the window identifies what type of window it is. A window class can be revealed via Window Spy or retrieved by WinGetClass. If the RegEx title matching mode is active, ClassName accepts a regular expression.
58 |Window classes are case-sensitive, except when using the i) modifier in a RegEx pattern.
59 |The following example activates a console window (e.g. cmd.exe):
60 |WinActivate "ahk_class ConsoleWindowClass"61 |
The following example does the same as above, but uses a regular expression (note that the RegEx title matching mode must be turned on beforehand to make it work):
62 |WinActivate "ahk_class ^ConsoleWindowClass$"63 | 64 |
Each window or control has a unique ID, also known as a HWND (short for handle to window). This ID can be used to identify the window or control even if its title or text changes.
66 |Use ahk_id HWND
or a pure HWND (as an Integer or an Object with a HWND property) in WinTitle to identify a window or control by its unique ID.
When using ahk_id HWND
, DetectHiddenWindows affects whether hidden top-level windows are detected, but hidden controls are always detected. When using pure HWNDs, hidden windows are always detected regardless of DetectHiddenWindows. WinWait and WinWaitClose are an exception, where both ahk_id HWND
and pure HWNDs are affected by DetectHiddenWindows.
ahk_id HWND
can also be combined with other criteria that the given window must match. For example, WinExist("ahk_id " ahwnd " ahk_class " aclass)
returns ahwnd if the window is "detected" (according to DetectHiddenWindows) and its window class matches the string contained by aclass.
The ID of a window is typically retrieved via WinExist or WinGetID. The ID of a control is typically retrieved via ControlGetHwnd, MouseGetPos, or DllCall. Gui and GuiControl objects have a Hwnd
property and therefore can be used directly in WinTitle.
The following examples operate on a window by a unique ID stored in VarContainingID:
71 |; Pass an Integer. 72 | WinActivate Integer(VarContainingID) 73 | WinShow A_ScriptHwnd 74 | WinWaitNotActive WinExist("A") 75 | 76 | ; Pass an Object with a HWND property. 77 | WinActivate {Hwnd: VarContainingID} 78 | WinWaitClose myGuiObject 79 | 80 | ; Use the ahk_id prefix. 81 | WinActivate "ahk_id " VarContainingID 82 |83 |
If the object has no HWND property or the property's value is not an integer, a PropertyError or TypeError is thrown.
84 | 85 |Use ahk_pid PID
in WinTitle to identify a window belonging to a specific process. The process identifier (PID) is typically retrieved by WinGetPID, Run or Process functions. The ID of a window's process can be revealed via Window Spy.
The following example activates a window by a process ID stored in VarContainingPID:
88 |WinActivate "ahk_pid " VarContainingPID89 | 90 |
Use ahk_exe ProcessNameOrPath
in WinTitle to identify a window belonging to any process with the given name or path.
While the ahk_pid criterion is limited to one specific process, the ahk_exe criterion considers all processes with name or full path matching a given string. If the RegEx title matching mode is active, ProcessNameOrPath accepts a regular expression which must match the full path of the process. Otherwise, it accepts a case-insensitive name or full path; for example, ahk_exe notepad.exe
covers ahk_exe C:\Windows\Notepad.exe
, ahk_exe C:\Windows\System32\Notepad.exe
and other variations. The name of a window's process can be revealed via Window Spy.
The following example activates a Notepad window by its process name:
94 |WinActivate "ahk_exe notepad.exe"95 |
The following example does the same as above, but uses a regular expression (note that the RegEx title matching mode must be turned on beforehand to make it work):
96 |WinActivate "ahk_exe i)\\notepad\.exe$" ; Match the name part of the full path.97 | 98 |
Use ahk_group GroupName
in WinTitle to identify a window or windows matching the rules contained by a previously defined window group.
WinMinimize, WinMaximize, WinRestore, WinHide, WinShow, WinClose, and WinKill will operate upon all the group's windows. By contrast, the other windowing functions such as WinActivate and WinExist will operate only upon the topmost window of the group.
101 |The following example activates any window matching the criteria defined by a window group:
102 |; Define the group: Windows Explorer windows 103 | GroupAdd "Explorer", "ahk_class ExploreWClass" ; Unused on Vista and later 104 | GroupAdd "Explorer", "ahk_class CabinetWClass" 105 | 106 | ; Activate any window matching the above criteria 107 | WinActivate "ahk_group Explorer"108 | 109 |
By contrast with the ahk_group criterion (which broadens the search), the search may be narrowed by specifying more than one criterion within the WinTitle parameter. In the following example, the script waits for a window whose title contains My File.txt and whose class is Notepad:
111 |WinWait "My File.txt ahk_class Notepad" 112 | WinActivate ; Activate the window it found.113 |
When using this method, the text of the title (if any is desired) should be listed first, followed by one or more additional criteria. Criteria beyond the first should be separated from the previous with exactly one space or tab (any other spaces or tabs are treated as a literal part of the previous criterion).
114 |The ahk_id criterion can be combined with other criteria to test a window's title, class or other attributes:
115 |116 | MouseGetPos ,, &id 117 | if WinExist("ahk_class Notepad ahk_id " id) 118 | MsgBox "The mouse is over Notepad." 119 |120 | 121 | 122 |
This is the window most recently found by WinExist, WinActive, WinWait[Not]Active, WinWait, or WinWaitClose. It can make scripts easier to create and maintain since WinTitle and WinText of the target window do not need to be repeated for every windowing function. In addition, scripts perform better because they don't need to search for the target window again after it has been found the first time.
125 |The last found window can be used by all of the windowing functions except WinWait, WinActivateBottom, GroupAdd, WinGetCount, and WinGetList. To use it, simply omit all four window parameters (WinTitle, WinText, ExcludeTitle, and ExcludeText).
126 |Each thread retains its own value of the last found window, meaning that if the current thread is interrupted by another, when the original thread is resumed it will still have its original value of the last found window, not that of the interrupting thread.
127 |If the last found window is a hidden Gui window, it can be used even when DetectHiddenWindows is turned off. This is often used in conjunction with the GUI's +LastFound option.
128 |The following example opens Notepad, waits until it exists and activates it:
129 |Run "Notepad" 130 | WinWait "Untitled - Notepad" 131 | WinActivate ; Use the window found by WinWait.132 | 133 |
The following example activates and maximizes the Notepad window found by WinExist:
134 |if WinExist("Untitled - Notepad") 135 | { 136 | WinActivate ; Use the window found by WinExist. 137 | WinMaximize ; Same as above. 138 | Send "Some text.{Enter}" 139 | }140 | 141 |
The following example activates the calculator found by WinExist and moves it to a new position:
142 |if not WinExist("Calculator") 143 | { 144 | ; ... 145 | } 146 | else 147 | { 148 | WinActivate ; Use the window found by WinExist. 149 | WinMove 40, 40 ; Same as above. 150 | }151 | 152 | 153 | 154 | -------------------------------------------------------------------------------- /docs/misc/Winamp.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |
This page demonstrates how to control Winamp via hotkey even when it is minimized or inactive. This information has been tested with Winamp 2.78c but should work for other major releases as well. Please post changes and improvements in the forum.
16 |This example makes the Ctrl+Alt+P hotkey equivalent to pressing Winamp's pause/unpause button:
17 |^!p:: 18 | { 19 | if not WinExist("ahk_class Winamp v1.x") 20 | return 21 | ; Otherwise, the above has set the "last found" window for use below. 22 | ControlSend "c" ; Pause/Unpause 23 | }24 |
Here are some of the keyboard shortcuts available in Winamp 2.x (may work in other versions too). The above example can be revised to use any of these keys:
25 |Key to send | 28 |Effect | 29 |
---|---|
c |
32 | Pause/UnPause | 33 |
x |
36 | Play/Restart/UnPause | 37 |
v |
40 | Stop | 41 |
+v |
44 | Stop with Fadeout | 45 |
^v |
48 | Stop after the current track | 49 |
b |
52 | Next Track | 53 |
z |
56 | Previous Track | 57 |
{left} |
60 | Rewind 5 seconds | 61 |
{right} |
64 | Fast-forward 5 seconds | 65 |
{up} |
68 | Turn Volume Up | 69 |
{down} |
72 | Turn Volume Down | 73 |
The following example asks Winamp which track number is currently active:
76 |77 | TrackNumber := SendMessage(0x0400, 0, 120,, "ahk_class Winamp v1.x") 78 | if (TrackNumber != "") 79 | { 80 | TrackNumber += 1 ; Winamp's count starts at 0, so adjust by 1. 81 | MsgBox "Track #" TrackNumber " is active or playing." 82 | }83 | 84 | 85 | -------------------------------------------------------------------------------- /docs/misc/remove-userchoice.reg: -------------------------------------------------------------------------------- 1 | Windows Registry Editor Version 5.00 2 | 3 | [-HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.ahk\UserChoice] 4 | -------------------------------------------------------------------------------- /docs/scripts/ContextSensitiveHelp.ahk: -------------------------------------------------------------------------------- 1 | ; Context Sensitive Help in Any Editor (based on the v1 script by Rajat) 2 | ; https://www.autohotkey.com 3 | ; This script makes Ctrl+2 (or another hotkey of your choice) show the help file 4 | ; page for the selected AutoHotkey function or keyword. If nothing is selected, 5 | ; the function name will be extracted from the beginning of the current line. 6 | 7 | ; The hotkey below uses the clipboard to provide compatibility with the maximum 8 | ; number of editors (since ControlGet doesn't work with most advanced editors). 9 | ; It restores the original clipboard contents afterward, but as plain text, 10 | ; which seems better than nothing. 11 | 12 | $^2:: 13 | { 14 | ; The following values are in effect only for the duration of this hotkey thread. 15 | ; Therefore, there is no need to change them back to their original values 16 | ; because that is done automatically when the thread ends: 17 | SetWinDelay 10 18 | SetKeyDelay 0 19 | 20 | C_ClipboardPrev := A_Clipboard 21 | A_Clipboard := "" 22 | ; Use the highlighted word if there is one (since sometimes the user might 23 | ; intentionally highlight something that isn't a function): 24 | Send "^c" 25 | if !ClipWait(0.1) 26 | { 27 | ; Get the entire line because editors treat cursor navigation keys differently: 28 | Send "{home}+{end}^c" 29 | if !ClipWait(0.2) ; Rare, so no error is reported. 30 | { 31 | A_Clipboard := C_ClipboardPrev 32 | return 33 | } 34 | } 35 | C_Cmd := Trim(A_Clipboard) ; This will trim leading and trailing tabs & spaces. 36 | A_Clipboard := C_ClipboardPrev ; Restore the original clipboard for the user. 37 | Loop Parse, C_Cmd, "`s" ; The first space is the end of the function. 38 | { 39 | C_Cmd := A_LoopField 40 | break ; i.e. we only need one interation. 41 | } 42 | if !WinExist("AutoHotkey Help") 43 | { 44 | ; Determine AutoHotkey's location: 45 | try 46 | ahk_dir := RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\AutoHotkey", "InstallDir") 47 | catch ; Not found, so look for it in some other common locations. 48 | { 49 | if A_AhkPath 50 | SplitPath A_AhkPath,, &ahk_dir 51 | else if FileExist("..\..\AutoHotkey.chm") 52 | ahk_dir := "..\.." 53 | else if FileExist(A_ProgramFiles "\AutoHotkey\AutoHotkey.chm") 54 | ahk_dir := A_ProgramFiles "\AutoHotkey" 55 | else 56 | { 57 | MsgBox "Could not find the AutoHotkey folder." 58 | return 59 | } 60 | } 61 | Run ahk_dir "\AutoHotkey.chm" 62 | WinWait "AutoHotkey Help" 63 | } 64 | ; The above has set the "last found" window which we use below: 65 | WinActivate 66 | WinWaitActive 67 | C_Cmd := StrReplace(C_Cmd, "#", "{#}") 68 | Send "!n{home}+{end}" C_Cmd "{enter}" 69 | } 70 | -------------------------------------------------------------------------------- /docs/scripts/ControllerMouse.ahk: -------------------------------------------------------------------------------- 1 | ; Using a Controller as a Mouse 2 | ; https://www.autohotkey.com 3 | ; This script converts a controller (gamepad, joystick, etc.) into a three-button 4 | ; mouse. It allows each button to drag just like a mouse button and it uses 5 | ; virtually no CPU time. Also, it will move the cursor faster depending on how far 6 | ; you push the stick from center. You can personalize various settings at the 7 | ; top of the script. 8 | ; 9 | ; Note: For Xbox controller 2013 and newer (anything newer than the Xbox 360 10 | ; controller), this script will only work if a window it owns is active, 11 | ; such as a message box, GUI, or the script's main window. 12 | 13 | ; Increase the following value to make the mouse cursor move faster: 14 | ContMultiplier := 0.30 15 | 16 | ; Decrease the following value to require less stick displacement-from-center 17 | ; to start moving the mouse. However, you may need to calibrate your stick 18 | ; -- ensuring it's properly centered -- to avoid cursor drift. A perfectly tight 19 | ; and centered stick could use a value of 1: 20 | ContThreshold := 3 21 | 22 | ; Change the following to true to invert the Y-axis, which causes the mouse to 23 | ; move vertically in the direction opposite the stick: 24 | InvertYAxis := false 25 | 26 | ; Change these values to use controller button numbers other than 1, 2, and 3 for 27 | ; the left, right, and middle mouse buttons. Available numbers are 1 through 32. 28 | ; Use the Controller Test Script to find out your controller's numbers more easily. 29 | ButtonLeft := 1 30 | ButtonRight := 2 31 | ButtonMiddle := 3 32 | 33 | ; If your controller has a POV control, you can use it as a mouse wheel. The 34 | ; following value is the number of milliseconds between turns of the wheel. 35 | ; Decrease it to have the wheel turn faster: 36 | WheelDelay := 250 37 | 38 | ; If your system has more than one controller, increase this value to use a 39 | ; controller other than the first: 40 | ControllerNumber := 1 41 | 42 | ; END OF CONFIG SECTION -- Don't change anything below this point unless you want 43 | ; to alter the basic nature of the script. 44 | 45 | #SingleInstance 46 | 47 | ControllerPrefix := ControllerNumber "Joy" 48 | Hotkey ControllerPrefix . ButtonLeft, ClickButtonLeft 49 | Hotkey ControllerPrefix . ButtonRight, ClickButtonRight 50 | Hotkey ControllerPrefix . ButtonMiddle, ClickButtonMiddle 51 | 52 | ; Calculate the axis displacements that are needed to start moving the cursor: 53 | ContThresholdUpper := 50 + ContThreshold 54 | ContThresholdLower := 50 - ContThreshold 55 | if InvertYAxis 56 | YAxisMultiplier := -1 57 | else 58 | YAxisMultiplier := 1 59 | 60 | SetTimer WatchController, 10 ; Monitor the movement of the stick. 61 | 62 | JoyInfo := GetKeyState(ControllerNumber "JoyInfo") 63 | if InStr(JoyInfo, "P") ; Controller has POV control, so use it as a mouse wheel. 64 | SetTimer MouseWheel, WheelDelay 65 | 66 | ; The functions below do not use KeyWait because that would sometimes trap the 67 | ; WatchController quasi-thread beneath the wait-for-button-up thread, which would 68 | ; effectively prevent mouse-dragging with the controller. 69 | 70 | ClickButtonLeft(*) 71 | { 72 | SetMouseDelay -1 ; Makes movement smoother. 73 | MouseClick "Left",,, 1, 0, "D" ; Hold down the left mouse button. 74 | SetTimer WaitForLeftButtonUp, 10 75 | 76 | WaitForLeftButtonUp() 77 | { 78 | if GetKeyState(A_ThisHotkey) 79 | return ; The button is still, down, so keep waiting. 80 | ; Otherwise, the button has been released. 81 | SetTimer , 0 82 | SetMouseDelay -1 ; Makes movement smoother. 83 | MouseClick "Left",,, 1, 0, "U" ; Release the mouse button. 84 | } 85 | } 86 | 87 | ClickButtonRight(*) 88 | { 89 | SetMouseDelay -1 ; Makes movement smoother. 90 | MouseClick "Right",,, 1, 0, "D" ; Hold down the right mouse button. 91 | SetTimer WaitForRightButtonUp, 10 92 | 93 | WaitForRightButtonUp() 94 | { 95 | if GetKeyState(A_ThisHotkey) 96 | return ; The button is still, down, so keep waiting. 97 | ; Otherwise, the button has been released. 98 | SetTimer , 0 99 | MouseClick "Right",,, 1, 0, "U" ; Release the mouse button. 100 | } 101 | } 102 | 103 | ClickButtonMiddle(*) 104 | { 105 | SetMouseDelay -1 ; Makes movement smoother. 106 | MouseClick "Middle",,, 1, 0, "D" ; Hold down the right mouse button. 107 | SetTimer WaitForMiddleButtonUp, 10 108 | 109 | WaitForMiddleButtonUp() 110 | { 111 | if GetKeyState(A_ThisHotkey) 112 | return ; The button is still, down, so keep waiting. 113 | ; Otherwise, the button has been released. 114 | SetTimer , 0 115 | MouseClick "Middle",,, 1, 0, "U" ; Release the mouse button. 116 | } 117 | 118 | } 119 | 120 | WatchController() 121 | { 122 | global 123 | MouseNeedsToBeMoved := false ; Set default. 124 | JoyX := GetKeyState(ControllerNumber "JoyX") 125 | JoyY := GetKeyState(ControllerNumber "JoyY") 126 | if JoyX > ContThresholdUpper 127 | { 128 | MouseNeedsToBeMoved := true 129 | DeltaX := Round(JoyX - ContThresholdUpper) 130 | } 131 | else if JoyX < ContThresholdLower 132 | { 133 | MouseNeedsToBeMoved := true 134 | DeltaX := Round(JoyX - ContThresholdLower) 135 | } 136 | else 137 | DeltaX := 0 138 | if JoyY > ContThresholdUpper 139 | { 140 | MouseNeedsToBeMoved := true 141 | DeltaY := Round(JoyY - ContThresholdUpper) 142 | } 143 | else if JoyY < ContThresholdLower 144 | { 145 | MouseNeedsToBeMoved := true 146 | DeltaY := Round(JoyY - ContThresholdLower) 147 | } 148 | else 149 | DeltaY := 0 150 | if MouseNeedsToBeMoved 151 | { 152 | SetMouseDelay -1 ; Makes movement smoother. 153 | MouseMove DeltaX * ContMultiplier, DeltaY * ContMultiplier * YAxisMultiplier, 0, "R" 154 | } 155 | } 156 | 157 | MouseWheel() 158 | { 159 | global 160 | JoyPOV := GetKeyState(ControllerNumber "JoyPOV") 161 | if JoyPOV = -1 ; No angle. 162 | return 163 | if (JoyPOV > 31500 or JoyPOV < 4500) ; Forward 164 | Send "{WheelUp}" 165 | else if JoyPOV >= 13500 and JoyPOV <= 22500 ; Back 166 | Send "{WheelDown}" 167 | } 168 | -------------------------------------------------------------------------------- /docs/scripts/ControllerTest.ahk: -------------------------------------------------------------------------------- 1 | ; Controller Test Script 2 | ; https://www.autohotkey.com 3 | ; This script helps determine the button numbers and other attributes 4 | ; of your controller (gamepad, joystick, etc.). It might also reveal 5 | ; if your controller is in need of calibration; that is, whether the 6 | ; range of motion of each of its axes is from 0 to 100 percent as it 7 | ; should be. If calibration is needed, use the operating system's 8 | ; control panel or the software that came with your controller. 9 | 10 | ; May 24, 2023: Replaced ToolTip and MsgBox with GUI. 11 | ; April 14, 2023: Renamed 'joystick' to 'controller'. 12 | ; July 16, 2016: Revised code for AHK v2 compatibility 13 | ; July 6, 2005 : Added auto-detection of joystick number. 14 | ; May 8, 2005 : Fixed: JoyAxes is no longer queried as a means of 15 | ; detecting whether the joystick is connected. Some joysticks are 16 | ; gamepads and don't have even a single axis. 17 | 18 | ; If you want to unconditionally use a specific controller number, change 19 | ; the following value from 0 to the number of the controller (1-16). 20 | ; A value of 0 causes the controller number to be auto-detected: 21 | ControllerNumber := 0 22 | 23 | ; END OF CONFIG SECTION. Do not make changes below this point unless 24 | ; you wish to alter the basic functionality of the script. 25 | 26 | G := Gui("+AlwaysOnTop", "Controller Test Script") 27 | G.Add("Text", "w300", "Note: For Xbox controller 2013 and newer (anything newer than the Xbox 360 controller), this script can only detect controller events if a window it owns is active (like this one).") 28 | E := G.Add("Edit", "w300 h300 +ReadOnly") 29 | G.Show() 30 | 31 | ; Auto-detect the controller number if called for: 32 | if ControllerNumber <= 0 33 | { 34 | Loop 16 ; Query each controller number to find out which ones exist. 35 | { 36 | if GetKeyState(A_Index "JoyName") 37 | { 38 | ControllerNumber := A_Index 39 | break 40 | } 41 | } 42 | if ControllerNumber <= 0 43 | { 44 | E.Value := "The system does not appear to have any controllers." 45 | return 46 | } 47 | } 48 | 49 | #SingleInstance 50 | cont_buttons := GetKeyState(ControllerNumber "JoyButtons") 51 | cont_name := GetKeyState(ControllerNumber "JoyName") 52 | cont_info := GetKeyState(ControllerNumber "JoyInfo") 53 | Loop 54 | { 55 | buttons_down := "" 56 | Loop cont_buttons 57 | { 58 | if GetKeyState(ControllerNumber "Joy" A_Index) 59 | buttons_down .= " " A_Index 60 | } 61 | axis_info := "X" Round(GetKeyState(ControllerNumber "JoyX")) 62 | axis_info .= " Y" Round(GetKeyState(ControllerNumber "JoyY")) 63 | if InStr(cont_info, "Z") 64 | axis_info .= " Z" Round(GetKeyState(ControllerNumber "JoyZ")) 65 | if InStr(cont_info, "R") 66 | axis_info .= " R" Round(GetKeyState(ControllerNumber "JoyR")) 67 | if InStr(cont_info, "U") 68 | axis_info .= " U" Round(GetKeyState(ControllerNumber "JoyU")) 69 | if InStr(cont_info, "V") 70 | axis_info .= " V" Round(GetKeyState(ControllerNumber "JoyV")) 71 | if InStr(cont_info, "P") 72 | axis_info .= " POV" Round(GetKeyState(ControllerNumber "JoyPOV")) 73 | E.Value := cont_name " (#" ControllerNumber "):`n" axis_info "`nButtons Down: " buttons_down 74 | Sleep 100 75 | } 76 | return 77 | -------------------------------------------------------------------------------- /docs/scripts/EasyWindowDrag.ahk: -------------------------------------------------------------------------------- 1 | ; Easy Window Dragging 2 | ; https://www.autohotkey.com 3 | ; Normally, a window can only be dragged by clicking on its title bar. 4 | ; This script extends that so that any point inside a window can be dragged. 5 | ; To activate this mode, hold down CapsLock or the middle mouse button while 6 | ; clicking, then drag the window to a new position. 7 | 8 | ; Note: You can optionally release CapsLock or the middle mouse button after 9 | ; pressing down the mouse button rather than holding it down the whole time. 10 | 11 | ~MButton & LButton:: 12 | CapsLock & LButton:: 13 | EWD_MoveWindow(*) 14 | { 15 | CoordMode "Mouse" ; Switch to screen/absolute coordinates. 16 | MouseGetPos &EWD_MouseStartX, &EWD_MouseStartY, &EWD_MouseWin 17 | WinGetPos &EWD_OriginalPosX, &EWD_OriginalPosY,,, EWD_MouseWin 18 | if !WinGetMinMax(EWD_MouseWin) ; Only if the window isn't maximized 19 | SetTimer EWD_WatchMouse, 10 ; Track the mouse as the user drags it. 20 | 21 | EWD_WatchMouse() 22 | { 23 | if !GetKeyState("LButton", "P") ; Button has been released, so drag is complete. 24 | { 25 | SetTimer , 0 26 | return 27 | } 28 | if GetKeyState("Escape", "P") ; Escape has been pressed, so drag is cancelled. 29 | { 30 | SetTimer , 0 31 | WinMove EWD_OriginalPosX, EWD_OriginalPosY,,, EWD_MouseWin 32 | return 33 | } 34 | ; Otherwise, reposition the window to match the change in mouse coordinates 35 | ; caused by the user having dragged the mouse: 36 | CoordMode "Mouse" 37 | MouseGetPos &EWD_MouseX, &EWD_MouseY 38 | WinGetPos &EWD_WinX, &EWD_WinY,,, EWD_MouseWin 39 | SetWinDelay -1 ; Makes the below move faster/smoother. 40 | WinMove EWD_WinX + EWD_MouseX - EWD_MouseStartX, EWD_WinY + EWD_MouseY - EWD_MouseStartY,,, EWD_MouseWin 41 | EWD_MouseStartX := EWD_MouseX ; Update for the next timer-call to this subroutine. 42 | EWD_MouseStartY := EWD_MouseY 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /docs/scripts/EasyWindowDrag_(KDE).ahk: -------------------------------------------------------------------------------- 1 | ; Easy Window Dragging -- KDE style (based on the v1 script by Jonny) 2 | ; https://www.autohotkey.com 3 | ; This script makes it much easier to move or resize a window: 1) Hold down 4 | ; the ALT key and LEFT-click anywhere inside a window to drag it to a new 5 | ; location; 2) Hold down ALT and RIGHT-click-drag anywhere inside a window 6 | ; to easily resize it; 3) Press ALT twice, but before releasing it the second 7 | ; time, left-click to minimize the window under the mouse cursor, right-click 8 | ; to maximize it, or middle-click to close it. 9 | 10 | ; The Double-Alt modifier is activated by pressing 11 | ; Alt twice, much like a double-click. Hold the second 12 | ; press down until you click. 13 | ; 14 | ; The shortcuts: 15 | ; Alt + Left Button : Drag to move a window. 16 | ; Alt + Right Button : Drag to resize a window. 17 | ; Double-Alt + Left Button : Minimize a window. 18 | ; Double-Alt + Right Button : Maximize/Restore a window. 19 | ; Double-Alt + Middle Button : Close a window. 20 | ; 21 | ; You can optionally release Alt after the first 22 | ; click rather than holding it down the whole time. 23 | 24 | ; This is the setting that runs smoothest on my 25 | ; system. Depending on your video card and cpu 26 | ; power, you may want to raise or lower this value. 27 | SetWinDelay 2 28 | CoordMode "Mouse" 29 | 30 | g_DoubleAlt := false 31 | 32 | !LButton:: 33 | { 34 | global g_DoubleAlt ; Declare it since this hotkey function must modify it. 35 | if g_DoubleAlt 36 | { 37 | MouseGetPos ,, &KDE_id 38 | ; This message is mostly equivalent to WinMinimize, 39 | ; but it avoids a bug with PSPad. 40 | PostMessage 0x0112, 0xf020,,, KDE_id 41 | g_DoubleAlt := false 42 | return 43 | } 44 | ; Get the initial mouse position and window id, and 45 | ; abort if the window is maximized. 46 | MouseGetPos &KDE_X1, &KDE_Y1, &KDE_id 47 | if WinGetMinMax(KDE_id) 48 | return 49 | ; Get the initial window position. 50 | WinGetPos &KDE_WinX1, &KDE_WinY1,,, KDE_id 51 | Loop 52 | { 53 | if !GetKeyState("LButton", "P") ; Break if button has been released. 54 | break 55 | MouseGetPos &KDE_X2, &KDE_Y2 ; Get the current mouse position. 56 | KDE_X2 -= KDE_X1 ; Obtain an offset from the initial mouse position. 57 | KDE_Y2 -= KDE_Y1 58 | KDE_WinX2 := (KDE_WinX1 + KDE_X2) ; Apply this offset to the window position. 59 | KDE_WinY2 := (KDE_WinY1 + KDE_Y2) 60 | WinMove KDE_WinX2, KDE_WinY2,,, KDE_id ; Move the window to the new position. 61 | } 62 | } 63 | 64 | !RButton:: 65 | { 66 | global g_DoubleAlt 67 | if g_DoubleAlt 68 | { 69 | MouseGetPos ,, &KDE_id 70 | ; Toggle between maximized and restored state. 71 | if WinGetMinMax(KDE_id) 72 | WinRestore KDE_id 73 | Else 74 | WinMaximize KDE_id 75 | g_DoubleAlt := false 76 | return 77 | } 78 | ; Get the initial mouse position and window id, and 79 | ; abort if the window is maximized. 80 | MouseGetPos &KDE_X1, &KDE_Y1, &KDE_id 81 | if WinGetMinMax(KDE_id) 82 | return 83 | ; Get the initial window position and size. 84 | WinGetPos &KDE_WinX1, &KDE_WinY1, &KDE_WinW, &KDE_WinH, KDE_id 85 | ; Define the window region the mouse is currently in. 86 | ; The four regions are Up and Left, Up and Right, Down and Left, Down and Right. 87 | if (KDE_X1 < KDE_WinX1 + KDE_WinW / 2) 88 | KDE_WinLeft := 1 89 | else 90 | KDE_WinLeft := -1 91 | if (KDE_Y1 < KDE_WinY1 + KDE_WinH / 2) 92 | KDE_WinUp := 1 93 | else 94 | KDE_WinUp := -1 95 | Loop 96 | { 97 | if !GetKeyState("RButton", "P") ; Break if button has been released. 98 | break 99 | MouseGetPos &KDE_X2, &KDE_Y2 ; Get the current mouse position. 100 | ; Get the current window position and size. 101 | WinGetPos &KDE_WinX1, &KDE_WinY1, &KDE_WinW, &KDE_WinH, KDE_id 102 | KDE_X2 -= KDE_X1 ; Obtain an offset from the initial mouse position. 103 | KDE_Y2 -= KDE_Y1 104 | ; Then, act according to the defined region. 105 | WinMove KDE_WinX1 + (KDE_WinLeft+1)/2*KDE_X2 ; X of resized window 106 | , KDE_WinY1 + (KDE_WinUp+1)/2*KDE_Y2 ; Y of resized window 107 | , KDE_WinW - KDE_WinLeft *KDE_X2 ; W of resized window 108 | , KDE_WinH - KDE_WinUp *KDE_Y2 ; H of resized window 109 | , KDE_id 110 | KDE_X1 := (KDE_X2 + KDE_X1) ; Reset the initial position for the next iteration. 111 | KDE_Y1 := (KDE_Y2 + KDE_Y1) 112 | } 113 | } 114 | 115 | ; "Alt + MButton" may be simpler, but I like an extra measure of security for 116 | ; an operation like this. 117 | !MButton:: 118 | { 119 | global g_DoubleAlt 120 | if g_DoubleAlt 121 | { 122 | MouseGetPos ,, &KDE_id 123 | WinClose KDE_id 124 | g_DoubleAlt := false 125 | return 126 | } 127 | } 128 | 129 | ; This detects "double-clicks" of the alt key. 130 | ~Alt:: 131 | { 132 | global g_DoubleAlt := (A_PriorHotkey = "~Alt" and A_TimeSincePriorHotkey < 400) 133 | Sleep 0 134 | KeyWait "Alt" ; This prevents the keyboard's auto-repeat feature from interfering. 135 | } 136 | -------------------------------------------------------------------------------- /docs/scripts/EncodeHTML.ahk: -------------------------------------------------------------------------------- 1 | ; HTML Entities Encoding 2 | ; https://www.autohotkey.com 3 | ; Similar to the Transform's HTML sub-command, this function converts a 4 | ; string into its HTML equivalent by translating characters whose ASCII 5 | ; values are above 127 to their HTML names (e.g. £ becomes £). In 6 | ; addition, the four characters "&<> are translated to "&<>. 7 | ; Finally, each linefeed (`n) is translated to
This showcase lists some scripts created by different authors which show what AutoHotkey might be capable of. For more ready-to-run scripts and functions, see AutoHotkey v2 Scripts and Functions Forum.
17 | 18 |Based on the v1 script by Rajat
43 |This script makes Ctrl+2 (or another hotkey of your choice) show the help file page for the selected AutoHotkey function or keyword. If nothing is selected, the function name will be extracted from the beginning of the current line.
44 | 45 | 46 |Normally, a window can only be dragged by clicking on its title bar. This script extends that so that any point inside a window can be dragged. To activate this mode, hold down CapsLock or the middle mouse button while clicking, then drag the window to a new position.
48 | 49 | 50 |Based on the v1 script by Jonny
52 |This script makes it much easier to move or resize a window: 1) Hold down Alt and LEFT-click anywhere inside a window to drag it to a new location; 2) Hold down Alt and RIGHT-click-drag anywhere inside a window to easily resize it; 3) Press Alt twice, but before releasing it the second time, left-click to minimize the window under the mouse cursor, right-click to maximize it, or middle-click to close it.
53 | 54 | 55 |Based on the v1 script by Savage
57 |When you click the middle mouse button while certain types of windows are active, this script displays a menu of your favorite folders. Upon selecting a favorite, the script will instantly switch to that folder within the active window. The following window types are supported: 1) Standard file-open or file-save dialogs; 2) Explorer windows; 3) Console (command prompt) windows. The menu can also be optionally shown for unsupported window types, in which case the chosen favorite will be opened as a new Explorer window.
58 | 59 | 60 |This script converts a controller (gamepad, joystick, etc.) into a three-button mouse. It allows each button to drag just like a mouse button and it uses virtually no CPU time. Also, it will move the cursor faster depending on how far you push the stick from center. You can personalize various settings at the top of the script.
62 |Note: For Xbox controller 2013 and newer (anything newer than the Xbox 360 controller), this script will only work if a window it owns is active, such as a message box, GUI, or the script's main window.
63 | 64 | 65 |This script helps determine the button numbers and other attributes of your controller (gamepad, joystick, etc.). It might also reveal if your controller is in need of calibration; that is, whether the range of motion of each of its axes is from 0 to 100 percent as it should be. If calibration is needed, use the operating system's control panel or the software that came with your controller.
67 | 68 | 69 |Based on the v1 script by Jon
71 |This script creates a mock keyboard at the bottom of your screen that shows the keys you are pressing in real time. I made it to help me to learn to touch-type (to get used to not looking at the keyboard). The size of the on-screen keyboard can be customized at the top of the script. Also, you can double-click the tray icon to show or hide the keyboard.
72 | 73 | 74 |This script assigns a hotkey of your choice to hide any window so that it becomes an entry at the bottom of the script's tray menu. Hidden windows can then be unhidden individually or all at once by selecting the corresponding item on the menu. If the script exits for any reason, all the windows that it hid will be unhidden automatically.
76 | 77 | 78 |This is a working example script that uses a timer to change the names of the buttons in a message box. Although the button names are changed, the MsgBox's return value still requires that the buttons be referred to by their original names.
80 | 81 | 82 |This example script makes the special 000 that appears on certain keypads into an equals key. You can change the action by replacing the Send "="
line with line(s) of your choice.
Based on the v1 script by deguix
88 |This script makes mousing with your keyboard almost as easy as using a real mouse (maybe even easier for some tasks). It supports up to five mouse buttons and the turning of the mouse wheel. It also features customizable movement speed, acceleration, and "axis inversion".
89 | 90 | 91 |Based on the v1 script by Phi
93 |Navigating the Start Menu can be a hassle, especially if you have installed many programs over time. 'Seek' lets you specify a case-insensitive key word/phrase that it will use to filter only the matching programs and directories from the Start Menu, so that you can easily open your target program from a handful of matched entries. This eliminates the drudgery of searching and traversing the Start Menu.
94 | 95 | 96 |Based on the v1 script by Rajat
98 |This script displays a popup menu in response to briefly holding down the middle mouse button. Select a menu item by left-clicking it. Cancel the menu by left-clicking outside of it. A recent improvement is that the contents of the menu can change depending on which type of window is active (Notepad and Word are used as examples here).
99 | 100 | 101 |Based on the v1 script by Rajat
103 |This script assigns hotkeys of your choice to raise and lower the master volume.
104 | 105 | 106 |Based on the v1 script by Rajat
108 |This script reduces a window to its title bar and then back to its original size by pressing a single hotkey. Any number of windows can be reduced in this fashion (the script remembers each). If the script exits for any reason, all "rolled up" windows will be automatically restored to their original heights.
109 | 110 | 111 |This script receives notifications from WinLIRC whenever you press a button on your remote control. It can be used to automate Winamp, Windows Media Player, etc. It's easy to configure. For example, if WinLIRC recognizes a button named "VolUp" on your remote control, create a label named VolUp and beneath it use the function SoundSetVolume "+5"
to increase the soundcard's volume by 5 %.
Similar to AutoHotkey v1's Transform HTML, this function converts a string into its HTML equivalent by translating characters whose ASCII values are above 127 to their HTML names (e.g. £
becomes £
). In addition, the four characters "&<>
are translated to "&<>
. Finally, each linefeed (`n
) is translated to <br>`n
(i.e. <br>
followed by a linefeed).
Based on the v1 script by numEric
121 |This script demonstrates how to change an UpDown's increment to a value other than 1 (such as 5 or 0.1).
122 | 123 | 124 |This forum contains many more scripts, but most scripts will not run as-is on AutoHotkey v2.0.
126 |AutoHotkey v1 Scripts and Functions Forum
127 | 128 | 129 | 130 | 131 | 132 | 175 | 176 | 177 | 178 | -------------------------------------------------------------------------------- /docs/search.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |Searching...
13 | 14 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /docs/settings.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |Specify the settings the help should be started with by default. These settings are permanent; this is, they apply for all current and future visits to this help.
40 |43 | 44 | | 45 |46 | 53 | | 54 |
57 | 58 | | 59 |60 | 65 | | 66 |
69 | 70 | | 71 |72 | 76 | | 77 |
80 | 81 | | 82 |83 | 87 | | 88 |
91 | 92 | | 93 |94 | 98 | | 99 |
109 | | 110 | 111 | | 112 |