└── 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 |

404 - File not found

15 |

Looks like the document you're looking for doesn't exist.

16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /docs/AHKL_DBGPClients.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Debugging Clients | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Debugging Clients

14 | 15 |

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 |
    17 |
  • SciTE4AutoHotkey
  • 18 |
  • XDebugClient
  • 19 |
  • Notepad++ DBGp Plugin
  • 20 |
  • Script-based Clients
  • 21 |
  • Command-line Client
  • 22 |
  • Others
  • 23 |
24 | 25 |

SciTE4AutoHotkey

26 |

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 |
    29 |
  • Breakpoints.
  • 30 |
  • Run, Step Over/Into/Out.
  • 31 |
  • View the call stack.
  • 32 |
  • List name and contents of variables in local/global scope.
  • 33 |
  • Hover over variable to show contents.
  • 34 |
  • Inspect or edit variable contents.
  • 35 |
  • View structure of objects.
  • 36 |
37 |

https://www.autohotkey.com/scite4ahk/

38 | 39 |

Visual Studio Code

40 |

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

43 |

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 |
    46 |
  • Allow the debugger engine to report a language other than "php".
  • 47 |
  • Added AutoHotkey syntax highlighting.
  • 48 |
  • Automatically listen for a connection from the debugger engine, rather than waiting for the user to click Start Listening.
  • 49 |
  • Truncate property values at the first null-character, since AutoHotkey currently returns the entire variable contents and XDebugClient has no suitable interface for displaying binary content.
  • 50 |
51 |

Download: Binary; Source Code (also see SharpDevelop, Dockpanel Suite and Advanced TreeView.)

52 |

Usage:

53 |
    54 |
  • Launch XDebugClient.
  • 55 |
  • Launch AutoHotkey /Debug. XDebugClient should automatically open the script file.
  • 56 |
  • Click the left margin to set at least one breakpoint.
  • 57 |
  • Choose Run from the Debug menu, or press F5.
  • 58 |
  • When execution hits a breakpoint, use the Debug menu or shortcut keys to step through or resume the script.
  • 59 |
60 |

Features:

61 |
    62 |
  • Syntax highlighted, read-only view of the source code.
  • 63 |
  • Breakpoints.
  • 64 |
  • Run, Step Over/Into/Out.
  • 65 |
  • View the call stack.
  • 66 |
  • Inspect variables - select a variable name, right-click, Inspect.
  • 67 |
68 |

Issues:

69 |
    70 |
  • The user interface does not respond to user input while the script is running.
  • 71 |
  • No mechanisms are provided to list variables or set their values.
  • 72 |
73 | 74 |

Notepad++ DBGp Plugin

75 |

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 |
    79 |
  • Launch Notepad++.
  • 80 |
  • Configure the DBGp plugin via Plugins, DBGp, Config... 81 |

    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 |
  • 83 |
  • Show the debugger pane via the toolbar or Plugins, DBGp, Debugger.
  • 84 |
  • Open the script file to be debugged.
  • 85 |
  • Set at least one breakpoint.
  • 86 |
  • Launch AutoHotkey /Debug.
  • 87 |
  • Use the debugger toolbar or shortcut keys to control the debugger.
  • 88 |
89 |

Features:

90 |
    91 |
  • Syntax highlighting, if configured by the user.
  • 92 |
  • Breakpoints.
  • 93 |
  • Run, Step Over/Into/Out, Run to cursor, Stop.
  • 94 |
  • View local/global variables.
  • 95 |
  • Watch user-specified variables.
  • 96 |
  • View the call stack.
  • 97 |
  • Hover over a variable to view its contents.
  • 98 |
  • User-configurable shortcut keys - Settings, Shortcut Mapper..., Plugin commands.
  • 99 |
100 |

Issues:

101 |
    102 |
  • Hovering over a single-letter variable name does not work - for instance, hovering over a will attempt to retrieve a or a .
  • 103 |
  • Hovering over text will attempt to retrieve a variable even if the text contains invalid characters.
  • 104 |
  • Notepad++ becomes unstable if property_get fails, which is particularly problematic in light of the above. As a workaround, AutoHotkey sends an empty property instead of an error code when a non-existent or invalid variable is requested.
  • 105 |
106 | 107 |

Script-based Clients

108 |

A script-based DBGp library and example clients are available from GitHub.

    109 |
  • dbgp_console.ahk: Simple command-line client.
  • 110 |
  • dbgp_test.ahk: Demonstrates asynchronous debugging.
  • 111 |
  • dbgp_listvars.ahk: Example client which justs lists the variables of all running scripts.
  • 112 |
113 |

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 |

Command-line Client

118 |

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 |

Others

121 |

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 & New Features | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Changes & New Features

14 |

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 |

2.0.19 - January 25, 2025

18 |

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 |

2.0.18 - July 6, 2024

30 |

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.

32 | 33 |

2.0.17 - June 5, 2024

34 |

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 |

2.0.16 - May 30, 2024

45 |

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 |

2.0.15 - May 16, 2024

53 |

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 |

2.0.14 - May 6, 2024

58 |

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.

62 |

Fixed :B0*O:XY::Z to produce XYZ rather than XZ (suppressing Y).

63 |

Fixed Send to leave any prior {modifier Down} in effect even if the key happens to be physically held down.

64 |

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.

69 |

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"}.

70 |

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.

73 |

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 |

2.0.13 - April 20, 2024

86 |

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".

91 |

Fixed DllCall AStr* arg type to copy back only if address changes.

92 |

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 |

2.0.12 - March 23, 2024

96 |

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.

101 |

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.

104 |

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 |
    108 |
  • OwnProps not skipping cloned properties which require parameters.
  • 109 |
  • Parameters not being passed recursively to parameterless properties (i.e. to allow a.b[c] to evaluate as (a.b)[c]).
  • 110 |
111 |

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 |

2.0.11 - December 23, 2023

115 |

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.

119 |

Fixed ListView.Opt("NoSort").

120 |

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 |

2.0.10 - September 24, 2023

124 |

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.

129 |

Fixed DirExist leaking handles when only files match.

130 | 131 |

2.0.9 - September 17, 2023

132 |

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 |

2.0.8 - September 11, 2023

138 |

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 |
    141 |
  • *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.
  • 142 |
  • *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.
  • 143 |
  • Other potential issues where the system's low-level tracking of a modifier key doesn't match up with the logical state.
  • 144 |
145 |

Fixed some issues affecting continuation sections:

146 |
    147 |
  • Escape sequences in the Join option were translated twice, causing ```` to become one literal ` instead of two, ``n to become a linefeed, and similar.
  • 148 |
  • `" 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.
  • 149 |
150 |

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.

153 | 154 |

2.0.7 - September 2, 2023

155 |

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)

157 |

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)

162 |

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 |

2.0.6 - August 30, 2023

167 |

Fixed some ambiguity with COM calls, such as x.y acting as x.y().

168 |

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.

170 |

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.

172 |

Fixed TypeError thrown by x is y to say "Class" rather than "Object".

173 |

Fixed WinTitle to support criteria longer than 1023 characters.

174 |

Fixed issues when &ref is used on different aliases of the same variable.

175 |

Fixed optional parameter default expressions (other than simple literal values) preventing the use of assume-global/assume-static.

176 | 177 |

2.0.5 - August 12, 2023

178 |

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 |

2.0.4 - July 3, 2023

187 |

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.

189 |

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?.

191 |

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.

197 |

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.

200 |

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 |
    203 |
  • Option removal potentially not affecting the corresponding SC.
  • 204 |
  • Options potentially also being applied to sc000.
  • 205 |
206 |

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.

207 |

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.

209 |

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.

210 |

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 |

2.0.3 - June 19, 2023

216 |

Fixed Hotkey("a", "b") to use the original function of "b", not "a". [PR #318]

217 |

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".

221 |

Fixed a bug with deleting a breakpoint on a static line containing =>.

222 |

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.

227 |

Changed error message for a == b && c() and similar cases to avoid alluding to legacy =.

228 |

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}.

234 |

Fixed a.base := a to throw an error.

235 |

Fixed x.y := unset causing crashes or undefined behaviour.

236 |

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 |
    245 |
  • Support omitting the "v" prefix.
  • 246 |
  • Support operators (> >= < <= =).
  • 247 |
  • Support a single digit for the version.
  • 248 |
249 | Installation 250 |

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 |

2.0.2 - January 2, 2023

259 |

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 |

2.0.1 - January 1, 2023

264 |

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 |

Pre-Release

275 |

For a history of changes prior to the v2.0.0 release, refer to the following (but note some changes were superseded):

276 |
    277 |
  • v2.0 release candidates
  • 278 |
  • v2.0-beta releases
  • 279 |
  • v2.0-alpha releases
  • 280 |
281 | 282 | -------------------------------------------------------------------------------- /docs/Compat.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Binary Compatibility | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Binary Compatibility

14 | 15 |

This document contains some topics which are sometimes important when dealing with external libraries or sending messages to a control or window.

16 | 17 |
    18 |
  • Unicode vs ANSI 19 |
      20 |
    • Buffer
    • 21 |
    • DllCall
    • 22 |
    • NumPut / NumGet
    • 23 |
    24 |
  • 25 |
  • Pointer Size
  • 26 |
27 | 28 |

Unicode vs ANSI

29 |

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 |
    32 |
  • Pass strings to external functions via DllCall.
  • 33 |
  • Pass strings via PostMessage or SendMessage.
  • 34 |
  • Manipulate strings directly via NumPut/NumGet.
  • 35 |
  • Allocate a Buffer to hold a specific number of characters.
  • 36 |
37 |

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 |

Buffer

43 |

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 |

DllCall

52 |

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 | 54 | 55 | 56 | 57 | 58 |
 Char SizeC / Win32 TypesEncoding
WStr16-bitwchar_t*, WCHAR*, LPWSTR, LPCWSTRUTF-16
AStr8-bitchar*, CHAR*, LPSTR, LPCSTRANSI (the system default ANSI code page)
Str--TCHAR*, LPTSTR, LPCTSTREquivalent to WStr in AutoHotkey v2.
59 |

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 |
    63 |
  1. If both Unicode (W) and ANSI (A) versions of the function are available, omit the W or A suffix and use the "Str" type for input parameters or the return value. For example, the DeleteFile function is exported from kernel32.dll as 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.

  2. 68 |
  3. If the function accepts a specific type of string as input, the script may use the appropriate string type: 69 |
    DllCall("DeleteFileA", "AStr", filename)
     70 | DllCall("DeleteFileW", "WStr", filename)
  4. 71 |
  5. If the function has a string parameter used for output, the script must allocate a buffer as described above and pass it to the function. If the parameter accepts input, the script must also convert the input string to the appropriate format; StrPut can be used for this.
  6. 72 |
73 | 74 |

NumPut / NumGet

75 |

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 |

Pointer Size

83 |

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 |
    85 |
  • Offset calculation for fields in structures which contain one or more pointers.
  • 86 |
  • Size calculation for structures containing one or more pointers.
  • 87 |
  • Type names used with DllCall, NumPut or NumGet.
  • 88 |
89 |

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 |














109 | 110 | 111 | -------------------------------------------------------------------------------- /docs/Concepts.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Concepts and Conventions | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |

Concepts and Conventions

13 |

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 |

Table of Contents

17 |
    18 |
  • Values 19 |
      20 |
    • Strings
    • 21 |
    • Numbers
    • 22 |
    • Boolean
    • 23 |
    • Nothing
    • 24 |
    • Objects
    • 25 |
    • Object Protocol
    • 26 |
  • 27 |
  • Variables 28 |
      29 |
    • Uninitialized Variables
    • 30 |
    • Built-in Variables
    • 31 |
    • Environment Variables
    • 32 |
    • Variable References (VarRef)
    • 33 |
    • Caching
    • 34 |
  • 35 |
  • Functions 36 |
      37 |
    • Methods
    • 38 |
  • 39 |
  • Control Flow
  • 40 |
  • Details 41 |
      42 |
    • String Encoding
    • 43 |
    • Pure Numbers
    • 44 |
    • Names
    • 45 |
    • References to Objects
    • 46 |
  • 47 |
48 | 54 | 55 |

Values

56 |

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 |
    59 |
  • Strings (text)
  • 60 |
  • Numbers (integers and floating-point numbers)
  • 61 |
  • Objects
  • 62 |
63 |

The Type function can be used to determine the type of a value.

64 |

Some other related concepts:

65 |
    66 |
  • Boolean
  • 67 |
  • Nothing
  • 68 |
69 | 70 |

Strings

71 |

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 |

Numbers

77 |

AutoHotkey supports these number formats:

78 |
    79 |
  • Decimal integers, such as 123, 00123 or -1.
  • 80 |
  • Hexadecimal integers, such as 0x7B, 0x007B or -0x1.
  • 81 |
  • Decimal floating-point numbers, such as 3.14159.
  • 82 |
83 |

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.

84 |

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.

85 |

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 |

Boolean

90 |

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.

91 |

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.)

92 |

The words true and false are built-in variables containing 1 and 0. They can be used to make a script more readable.

93 | 94 |

Nothing

95 |

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.

98 |

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 |

Objects

102 |

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 |
    105 |
  • Objects are not contained; they are referenced. For example, 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.
  • 106 |
  • Two object references compare equal only if they refer to the same object.
  • 107 |
  • Objects are always considered true when a boolean value is required, such as in if obj, !obj or obj ? x : y.
  • 108 |
  • Each object has a unique address (location in memory), which can be retrieved by the ObjPtr function, but is typically not used directly. This address uniquely identifies the object, but only until the object is freed.
  • 109 |
  • In some cases when an object is used in a context where one was not expected, it might be treated as an empty string. For example, MsgBox(myObject) shows an empty MsgBox. In other cases, a TypeError may be thrown (and this should become the norm in future).
  • 110 |
111 |

Note: All objects which derive from Object have additional shared behaviour, properties and methods.

112 |

Some ways that objects are used include:

113 |
    114 |
  • To contain a collection of items or elements. For example, an Array contains a sequence of items, while a Map associates keys with values. Objects allow a group of values to be treated as one value, to be assigned to a single variable, passed to or returned from a function, and so on.
  • 115 |
  • To represent something real or conceptual. For example: a position on the screen, with X and Y properties; a contact in an address book, with Name, PhoneNumber, EmailAddress and so on. Objects can be used to represent more complex sets of information by combining them with other objects.
  • 116 |
  • To encapsulate a service or set of services, allowing other parts of the script to focus on a task rather than how that task is carried out. For example, a File object provides methods to read data from a file or write data to a file. If a script function which writes information to a file accepts a File object as a parameter, it needs not know how the file was opened. The same function could be reused to write information to some other target, such as a TCP/IP socket or WebSocket (via user-defined objects).
  • 117 |
  • A combination of the above. For example, a Gui represents a GUI window; it provides a script with the means to create and display a graphical user interface; it contains a collection of controls, and provides information about the window via properties such as Title and FocusedCtrl.
  • 118 |
119 |

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 |

Object Protocol

122 |

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 |
    125 |
  • Get a property.
  • 126 |
  • Set a property, denoted by :=.
  • 127 |
  • Call a method, denoted by ().
  • 128 |
129 |

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 |
    132 |
  • The name of the property or method.
  • 133 |
  • Zero or more parameters which may affect what action is carried out, how a value is stored, or which value is returned. For example, a property might take an array index or key.
  • 134 |
135 |

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 |

Variables

150 |

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.

151 |

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 |
    154 |
  • The variable's name.
  • 155 |
  • The variable itself.
  • 156 |
  • The variable's value.
  • 157 |
158 |

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.

161 |

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).

162 | 163 |

Uninitialized Variables

164 |

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?).

167 |

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".

168 | 169 |

Built-in Variables

170 |

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.

171 |

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

176 |

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 |

Variable References (VarRef)

182 |

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.

183 |

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.

184 |

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 Any
186 |

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.

187 |

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.

188 | 189 |

Caching

190 |

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.

191 |

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 |

Related

194 |
    195 |
  • Variables: basic usage and examples.
  • 196 |
  • Variable Capacity and Memory: details about limitations.
  • 197 |
198 | 199 |

Functions

200 |

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 |
204 |
Call a function
205 |

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.

207 |
Parameters
208 |

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.

209 |
Pass parameters
210 |

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.

211 |
Return a value
212 |

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).

213 |
Command
214 |

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.)

215 |
216 |

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 |

Methods

227 |

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.

228 | 229 |

Control Flow

230 |

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 |
232 |
Statement
233 |

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.

234 |
Execute
235 |

Carry out, perform, evaluate, put into effect, etc. Execute basically has the same meaning as in non-programming speak.

236 |
Body
237 |

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.

238 |
239 |

For example, consider this simple set of instructions:

240 |
    241 |
  1. Open Notepad
  2. 242 |
  3. Wait for Notepad to appear on the screen
  4. 243 |
  5. Type "Hello, world!"
  6. 244 |
245 |

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 |
    247 |
  1. If Notepad is not running: 248 |
      249 |
    1. Open Notepad
    2. 250 |
    3. Wait for Notepad to appear on the screen
    4. 251 |
    252 |
  2. 253 |
  3. Otherwise: 254 |
      255 |
    1. Activate Notepad
    2. 256 |
    257 |
  4. 258 |
  5. Type "Hello, world!"
  6. 259 |
260 |

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 |

Details

275 | 276 |

String Encoding

277 |

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 | 279 | 280 | 281 |
Abc
6598990
282 |

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.

285 |

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 |
    287 |
  • 288 |

    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 |
  • 290 |
  • 291 |

    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 |
  • 293 |
294 |

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.

298 |

Techniques for dealing with the differences between ANSI and Unicode versions of AutoHotkey can be found under Unicode vs ANSI.

299 | 300 |

Pure Numbers

301 |

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 |
    303 |
  • 64-bit signed integers (int64).
  • 304 |
  • 64-bit binary floating-point numbers (the double or binary64 format of the IEEE 754 international standard).
  • 305 |
306 |

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 |
    309 |
  • 310 |

    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 |
  • 312 |
  • 313 |

    Floating-point numbers generally support 15 digits of precision.

    314 |
  • 315 |
316 |

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 |

Names

331 |

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.

333 |

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.

336 |

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

337 |

Names of properties, methods and window groups are permitted to be reserved words.

338 | 339 |

References to Objects

340 |

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.

342 |

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 | Frequently Asked Questions (FAQ) | AutoHotkey v2 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Frequently Asked Questions (FAQ)

14 | 15 |

Table of Contents

16 |

General Troubleshooting

17 |
    18 |
  • What can I do if AutoHotkey won't install?
  • 19 |
  • How do I restore the right-click context menu options for .ahk files?
  • 20 |
  • Why doesn't my script work on Windows xxx even though it worked on a previous version?
  • 21 |
  • How do I work around problems caused by User Account Control (UAC)?
  • 22 |
  • I can't edit my script via tray icon because it won't start due to an error. What should I do?
  • 23 |
  • How can I find and fix errors in my code?
  • 24 |
  • Why is the Run function unable to launch my game or program?
  • 25 |
  • Why are the non-ASCII characters in my script displaying or sending incorrectly?
  • 26 |
  • Why don't Hotstrings, Send, and Click work in certain games?
  • 27 |
  • How can performance be improved for games or at other times when the CPU is under heavy load?
  • 28 |
  • My antivirus program flagged AutoHotkey or a compiled script as malware. Is it really a virus?
  • 29 |
30 |

Common Tasks

31 |
    32 |
  • Where can I find the official build, or older releases?
  • 33 |
  • Can I run AHK from a USB drive?
  • 34 |
  • How can the output of a command line operation be retrieved?
  • 35 |
  • How can a script close, pause, suspend or reload other script(s)?
  • 36 |
  • How can a repeating action be stopped without exiting the script?
  • 37 |
  • How can context sensitive help for AutoHotkey functions be used in any editor?
  • 38 |
  • How to detect when a web page is finished loading?
  • 39 |
  • How can dates and times be compared or manipulated?
  • 40 |
  • How can I send the current Date and/or Time?
  • 41 |
  • How can I send text to a window which isn't active or isn't visible?
  • 42 |
  • How can Winamp be controlled even when it isn't active?
  • 43 |
  • How can MsgBox's button names be changed?
  • 44 |
  • How can I change the default editor, which is accessible via context menu or tray icon?
  • 45 |
  • How can I save the contents of my GUI controls?
  • 46 |
  • Can I draw something with AHK?
  • 47 |
  • How can I start an action when a window appears, closes or becomes [in]active?
  • 48 |
49 |

Hotkeys, Hotstrings, and Remapping

50 |
    51 |
  • How do I put my hotkeys and hotstrings into effect automatically every time I start my PC?
  • 52 |
  • I'm having trouble getting my mouse buttons working as hotkeys. Any advice?
  • 53 |
  • How can Tab and Space be defined as hotkeys?
  • 54 |
  • How can keys or mouse buttons be remapped so that they become different keys?
  • 55 |
  • How do I detect the double press of a key or button?
  • 56 |
  • How can a hotkey or hotstring be made exclusive to certain program(s)? In other words, I want a certain key to act as it normally does except when a specific window is active.
  • 57 |
  • How can a prefix key be made to perform its native function rather than doing nothing?
  • 58 |
  • How can the built-in Windows shortcut keys, such as Win+U (Utility Manager) and Win+R (Run), be changed or disabled?
  • 59 |
  • Can I use wildcards or regular expressions in Hotstrings?
  • 60 |
  • How can I use a hotkey that is not in my keyboard layout?
  • 61 |
  • My keypad has a special 000 key. Is it possible to turn it into a hotkey?
  • 62 |
63 | 64 |

General Troubleshooting

65 |

What can I do if AutoHotkey won't install?

66 |

If AutoHotkey cannot be installed the normal way, see How to Install AutoHotkey for more help.

67 | 68 |

How do I restore the right-click context menu options for .ahk files?

69 |

Normally if AutoHotkey is installed, right-clicking an AutoHotkey script (.ahk) file should give the following options:

70 |
    71 |
  • Run script
  • 72 |
  • Compile script (if Ahk2Exe is installed)
  • 73 |
  • Edit script
  • 74 |
  • Run as administrator
  • 75 |
  • Run with UI access (if the prerequisites are met)
  • 76 |
77 |

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\UserChoice
80 |

This can be done by applying this registry patch or by running UX\reset-assoc.ahk from the AutoHotkey installation directory.

81 |

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.

82 | 83 |

Why doesn't my script work on Windows xxx even though it worked on a previous version?

84 |

There are many variations of this problem, such as:

85 |
    86 |
  • I've upgraded my computer/Windows and now my script won't work.
  • 87 |
  • Hotkeys/hotstrings don't work when a program running as admin is active.
  • 88 |
  • Some windows refuse to be automated (e.g. Device Manager ignores Send).
  • 89 |
90 |

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 |

How do I work around problems caused by User Account Control (UAC)?

94 |

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 |
    98 |
  • Recommended: Run with UI access. This requires AutoHotkey to be installed under Program Files. There are several ways to do this, including: 99 |
      100 |
    • Right-click the script in Explorer and select Run with UI access.
    • 101 |
    • Use the UIAccess shell verb with Run, as in Run '*UIAccess "Your script.ahk"'.
    • 102 |
    • Use a command line such as "AutoHotkey32_UIA.exe" "Your script.ahk" (but include full paths where necessary).
    • 103 |
    • Set scripts to run with UI access by default, by checking the appropriate box in the Launch Settings GUI.
    • 104 |
  • 105 |
  • Run the script as administrator. Note that this also causes any programs launched by the script to run as administrator, and may require the user to accept an approval prompt when launching the script.
  • 106 |
  • Disable the local security policy "Run all administrators in Admin Approval Mode" (not recommended).
  • 107 |
  • Disable UAC completely. This is not recommended, and is not feasible on Windows 8 or later.
  • 108 |
109 | 110 |

I can't edit my script via tray icon because it won't start due to an error. What should I do?

111 |

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 [H]

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 |

How can I find and fix errors in my code?

117 |

For simple scripts, see Debugging a Script. To show contents of a variable, use MsgBox or ToolTip. For complex scripts, see Interactive Debugging.

118 |

Why is the Run function unable to launch my game or program?

119 |

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.

122 | 123 |

Why are the non-ASCII characters in my script displaying or sending incorrectly?

124 |

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.

129 |

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 |

Why don't Hotstrings, Send, and Click work in certain games?

132 |

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 |
    135 |
  • 136 |

    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 way
    146 |

    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 |
  • 148 |
  • 149 |

    Increase SetKeyDelay. For example:

    150 |
    SetKeyDelay 0, 50
    151 | SetKeyDelay 0, 50, "Play"
    152 |
  • 153 |
  • 154 |

    Try ControlSend, which might work in cases where the other Send modes fail:

    155 |
    ControlSend "abc",, GameTitle
    156 |
  • 157 |
  • 158 |

    Try the down and up event of a key with the various send methods:

    159 |
    Send "{KEY Down}{KEY Up}"
    160 |
  • 161 |
  • 162 |

    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 |
  • 167 |
168 |

How can performance be improved for games or at other times when the CPU is under heavy load?

169 |

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 |

My antivirus program flagged AutoHotkey or a compiled script as malware. Is it really a virus?

172 |

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 |

Common Tasks

176 | 177 |

Where can I find the official build, or older releases?

178 |

See download page of AutoHotkey.

179 |

Can I run AHK from a USB drive?

180 |

See Portability of AutoHotkey.exe.

181 |

How can the output of a command line operation be retrieved?

182 |

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 |

How can a script close, pause, suspend or reload other script(s)?

188 |

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 |

How can a repeating action be stopped without exiting the script?

197 |

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 1
225 |

How can context sensitive help for AutoHotkey functions be used in any editor?

226 |

Rajat created this script.

227 |

How to detect when a web page is finished loading?

228 |

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 |

How can dates and times be compared or manipulated?

240 |

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 |

How can I send the current Date and/or Time?

244 |

Use FormatTime or built-in variables for date and time.

245 |

How can I send text to a window which isn't active or isn't visible?

246 |

Use ControlSend.

247 |

How can Winamp be controlled even when it isn't active?

248 |

See Automating Winamp.

249 |

How can MsgBox's button names be changed?

250 |

Here is an example.

251 |

How can I change the default editor, which is accessible via context menu or tray icon?

252 |

In the example section of Edit you will find a script that allows you to change the default editor.

253 |

How can I save the contents of my GUI controls?

254 |

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 |

Can I draw something with AHK?

267 |

See GDI+ standard library by tic. It's also possible with some rudimentary methods using Gui, but in a limited way.

268 |

How can I start an action when a window appears, closes or becomes [in]active?

269 |

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 |

Hotkeys, Hotstrings, and Remapping

272 |

How do I put my hotkeys and hotstrings into effect automatically every time I start my PC?

273 |

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 |
    275 |
  1. Find the script file, select it, and press Ctrl+C.
  2. 276 |
  3. Press Win+R to open the Run dialog, then enter 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).
  4. 277 |
  5. Right click inside the window, and click "Paste Shortcut". The shortcut to the script should now be in the Startup folder.
  6. 278 |
279 |

I'm having trouble getting my mouse buttons working as hotkeys. Any advice?

280 |

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.

281 |

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.

282 |

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 |

How can Tab and Space be defined as hotkeys?

284 |

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.

285 |

How can keys or mouse buttons be remapped so that they become different keys?

286 |

This is described on the remapping page.

287 |

How do I detect the double press of a key or button?

288 |

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 |

How can a hotkey or hotstring be made exclusive to certain program(s)? In other words, I want a certain key to act as it normally does except when a specific window is active.

295 |

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 |

How can a prefix key be made to perform its native function rather than doing nothing?

300 |

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 |

How can the built-in Windows shortcut keys, such as Win+U (Utility Manager) and Win+R (Run), be changed or disabled?

306 |

Here are some examples.

307 |

Can I use wildcards or regular expressions in Hotstrings?

308 |

Use the script by polyethene (examples are included).

309 |

How can I use a hotkey that is not in my keyboard layout?

310 |

See Special Keys.

311 |

My keypad has a special 000 key. Is it possible to turn it into a hotkey?

312 |

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.

313 | 314 | 315 | -------------------------------------------------------------------------------- /docs/Functions.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Functions - Definition & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Functions

14 | 15 |

Table of Contents

16 |
    17 |
  • Introduction and Simple Examples
  • 18 |
  • Parameters
  • 19 |
  • ByRef Parameters
  • 20 |
  • Optional Parameters 21 |
      22 |
    • Unset Parameters
    • 23 |
    24 |
  • 25 |
  • Returning Values to Caller
  • 26 |
  • Variadic Functions 27 |
      28 |
    • Variadic Function Calls
    • 29 |
    30 |
  • 31 |
  • Local and Global Variables 32 |
      33 |
    • Local Variables
    • 34 |
    • Global Variables
    • 35 |
    • Static Variables
    • 36 |
    • More About Locals and Globals
    • 37 |
    38 |
  • 39 |
  • Dynamically Calling a Function
  • 40 |
  • Short-circuit Boolean Evaluation
  • 41 |
  • Nested Functions 42 |
      43 |
    • Static Functions
    • 44 |
    • Closures
    • 45 |
    46 |
  • 47 |
  • Return, Exit, and General Remarks
  • 48 |
  • Style and Naming Conventions
  • 49 |
  • Using #Include to Share Functions Among Multiple Scripts
  • 50 |
  • Built-in Functions
  • 51 |
52 |

Introduction and Simple Examples

53 |

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:

59 |
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 |

Parameters

69 |

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().

70 |

Known limitation:

71 |
    72 |
  • If a parameter in a function-call resolves to a variable (e.g. 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.
  • 73 |
74 | 75 |

ByRef Parameters

76 |

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.

88 |

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.

97 |

Known limitations:

98 |
    99 |
  • It is not possible to construct a VarRef for a property of an object (such as foo.bar), A_Clipboard or any other built-in variable, so those cannot be passed ByRef.
  • 100 |
  • If the parameter is optional, it is not possible to determine whether the variable referenced by the parameter is a newly created local variable or one supplied by the caller. One alternative is to use a non-ByRef parameter, but pass it a VarRef anyway, and have the function explicitly dereference it or pass it to another function's ByRef parameter (without using the & operator).
  • 101 |
102 | 103 |

Optional Parameters

104 |

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.

106 |

Append ? or := unset to define a parameter which is unset by default.

107 |

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.

118 | 119 |

Unset Parameters

120 |

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:

121 |
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 |

Returning Values to Caller

143 |

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 |

Variadic Functions

192 |

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.

200 |

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).

201 |

Note: The "variadic" parameter can only appear at the end of the formal parameter list.

202 | 203 |

Variadic Function Calls

204 |

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 |
    209 |
  • The object can be an Array or any other kind of enumerable object (any object with an __Enum method) or an enumerator. If the object is not an Array, __Enum is called with a count of 1 and the enumerator is called with only one parameter at a time.
  • 210 |
  • Array elements with no value (such as the first element in [,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.
  • 211 |
  • This syntax can also be used when calling methods or setting or retrieving properties of objects; for example, Object.Property[Params*].
  • 212 |
213 |

Known limitations:

214 |
    215 |
  • Only the right-most parameter can be expanded this way. For example, MyFunc(x, y*) is supported but MyFunc(x*, y) is not.
  • 216 |
  • There must not be any non-whitespace characters between the asterisk (*) and the symbol which ends the parameter list.
  • 217 |
  • Function call statements cannot be variadic; that is, the parameter list must be enclosed in parentheses (or brackets for a property).
  • 218 |
219 |

Local and Global Variables

220 |

Local Variables

221 |

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 |
    226 |
  • Global variables which are only read by the function, not assigned or used with the reference operator (&).
  • 227 |
  • Nested functions may refer to local and static variables created by an enclosing function.
  • 228 |
229 |

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).

230 | 231 |

Global Variables

232 |

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

256 |

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.

265 |

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 |

More About Locals and Globals

283 |

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, PrevResult
286 |

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.

287 |

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.

288 | 289 |

Dynamically Calling a Function

290 |

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.

291 |

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.

293 |

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.

294 |

If the target value cannot be called due to one of the reasons below, an Error is thrown:

295 |
    296 |
  • If the target value is not of a type that can be called, a MethodError is thrown. Any value with a Call method can be called, so HasMethod(value, "Call") or HasMethod(value) can be used to avoid this error.
  • 297 |
  • Passing too few or too many parameters, which can often be avoided by checking the function's MinParams, MaxParams and IsVariadic properties, either directly or by calling HasMethod(value,, N), where N is the number of parameters that will be passed to the function.
  • 298 |
  • Passing something other than a variable reference (VarRef) to a ByRef or OutputVar parameter, which could be avoided through the use of the IsByRef method.
  • 299 |
300 |

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 |

Short-circuit Boolean Evaluation

303 |

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 |

Nested Functions

315 |

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 |
    330 |
  1. The outer function must refer to the variable in at least one of the following ways: 331 |
      332 |
    1. By declaring it with local, or as a parameter or nested function.
    2. 333 |
    3. As the non-dynamic target of an assignment or the reference operator (&).
    4. 334 |
    335 |
  2. 336 |
  3. The inner function (or a function nested inside it) must refer to the variable non-dynamically.
  4. 337 |
338 |

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.

341 |

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 |

Static Functions

346 |

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:

347 |
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 |

Closures

360 |

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.

395 |

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.

411 |

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 |

Return, Exit, and General Remarks

414 |

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).

416 |

To call a function with one or more blank values (empty strings), use an empty pair of quotes as in this example: FindColor(ColorName, "").

417 |

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 |

Style and Naming Conventions

420 |

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 |

Using #Include to Share Functions Among Multiple Scripts

427 |

The #Include directive may be used to load functions from an external file.

428 | 429 |

Built-in Functions

430 |

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 | Advanced Hotkey Features | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Advanced Hotkey Features

14 | 15 | 16 |

Table of Contents

17 |
    18 |
  • General 19 |
      20 |
    • Remap easy to reach but rarely used keys
    • 21 |
    • Use any keys as modifiers
    • 22 |
    • Make the mouse wheel perform alt-tabbing
    • 23 |
    • Make a keyboard key become a mouse button
    • 24 |
    • Make your hotkeys context-sensitive
    • 25 |
    • Define abbreviations that expand as you type them
    • 26 |
    27 |
  • 28 |
  • Gaming 29 |
      30 |
    • Reduce wear and tear on your fingers
    • 31 |
    • Create mouse hotkeys
    • 32 |
    • Create "pass-through" hotkeys
    • 33 |
    • Automate game actions on the screen
    • 34 |
    • Use the keyboard hook
    • 35 |
    36 |
  • 37 |
  • Related Topics
  • 38 |
39 | 40 |

General

41 | 42 |

Remap easy to reach but rarely used keys

43 |

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::AltTab
47 | 48 |

Use any keys as modifiers

49 |

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.

50 | 51 |

Make the mouse wheel perform alt-tabbing

52 |

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::ShiftAltTab
56 | 57 |

Make a keyboard key become a mouse button

58 |

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 |

Make your hotkeys context-sensitive

61 |

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 |

Define abbreviations that expand as you type them

70 |

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 way
74 | 75 |

Gaming

76 | 77 |

Reduce wear and tear on your fingers

78 |

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

81 |

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::.

82 | 83 |

Create "pass-through" hotkeys

84 |

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::).

85 | 86 |

Automate game actions on the screen

87 |

Use functions such as PixelSearch, PixelGetColor, and ImageSearch to automate game actions.

88 | 89 |

Use the keyboard hook

90 |

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 |

Related Topics

93 |
    94 |
  • Hotkeys
  • 95 |
  • Hotstrings
  • 96 |
  • Remapping Keys
  • 97 |
98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /docs/Hotkeys.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Hotkeys - Definition & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Hotkeys (Mouse, Controller and Keyboard Shortcuts)

15 | 16 | 17 |

Table of Contents

18 |
    19 |
  • Introduction and Simple Examples
  • 20 |
  • Hotkey Modifier Symbols
  • 21 |
  • Context-sensitive Hotkeys
  • 22 |
  • Custom Combinations
  • 23 |
  • Other Features
  • 24 |
  • Mouse Wheel Hotkeys
  • 25 |
  • Hotkey Tips and Remarks
  • 26 |
  • Alt-Tab Hotkeys
  • 27 |
  • Named Function Hotkeys
  • 28 |
29 | 30 |

Introduction and Simple Examples

31 |

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:

39 |
#n::MsgBox ThisHotkey  ; Reports #n
40 |

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:

42 |
^!s::
 43 | {
 44 |     Send "Sincerely,{enter}John Smith"  ; This line sends keystrokes to the active (foremost) window.
 45 | }
46 |

Hotkey Modifier Symbols

47 |

You can use the following modifier symbols to define hotkeys:

48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 60 | 61 | 62 | 63 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 95 | 96 | 97 | 98 | 102 | 103 | 104 | 105 | 118 | 119 | 120 | 121 | 126 | 127 | 128 | 129 | 139 | 140 |
SymbolDescription
# 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 |
! 64 |

Alt

65 |

Note: Pressing a hotkey which includes Alt may result in extra simulated keystrokes (Ctrl by default). See A_MenuMaskKey.

66 |
^Ctrl
+Shift
&An ampersand may be used between any two keys or mouse buttons to combine them into a custom hotkey. See below for details.
<Use the left key of the pair. e.g. <!a is the same as !a except that only the left Alt will trigger it.
>Use the right key of the pair.
<^>!

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."
*

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 *a:: would cause ^a:: to always use the hook.

~

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 |
$ 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 #UseHook somewhere above the definition of this hotkey.

123 |

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 |
UP

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: ^!r Up::MsgBox "You pressed and released Ctrl+Alt+R". It also works with combination hotkeys (e.g. F1 & e Up::)

134 |

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. ~LControl up::)

135 |

"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."
141 |

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::return
151 | 152 |

Context-sensitive Hotkeys

153 |

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 |

Custom Combinations

167 |

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 |
    170 |
  • The prefix key loses its native function, unless it is a standard modifier key or toggleable key such as CapsLock.
  • 171 |
  • If the prefix key is also used as a suffix in another hotkey, by default that hotkey is fired upon release, and is not fired at all if it was used to activate a custom combination. If there is both a key-down hotkey and a key-up hotkey, both hotkeys are fired at once. The fire-on-release effect is disabled if the tilde prefix is applied to the prefix key in at least one active custom combination or the suffix hotkey itself.
  • 172 |
173 |

Note: For combinations with standard modifier keys, it is usually better to use the standard syntax. For example, use <+s:: rather than LShift & s::.

174 |

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.

182 |

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 | \::MsgBox
194 |

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.

195 | 196 |

Other Features

197 |

NumLock, CapsLock, and ScrollLock: These keys may be forced to be "AlwaysOn" or "AlwaysOff". For example: SetNumLockState "AlwaysOn".

198 |

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 |

Mouse Wheel Hotkeys

205 |

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 |
    211 |
  • If the mouse hardware reports distances of less than one notch, A_EventInfo may be less than 120;
  • 212 |
  • If the wheel is being turned quickly (depending on the type of mouse), A_EventInfo may be greater than 120. A hotkey like the following can help analyze your mouse: ~WheelDown::ToolTip A_EventInfo
  • 213 |
214 |

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 |

Hotkey Tips and Remarks

229 |

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.

259 |

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

264 |

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::ShiftAltTab
268 |

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::ShiftAltTab
278 |

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 | #HotIf
283 |

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.

284 | 285 |

General Remarks

286 |

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.

288 |

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.

289 |
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 enabled
292 |

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 | #HotIf
299 | 300 |

Named Function Hotkeys

301 |

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 | Hotstrings - Definition & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Hotstrings

15 | 16 |

Table of Contents

17 |
    18 |
  • Introduction and Simple Examples
  • 19 |
  • Ending Characters
  • 20 |
  • Options
  • 21 |
  • Long Replacements
  • 22 |
  • Context-sensitive Hotstrings
  • 23 |
  • AutoCorrect
  • 24 |
  • Remarks
  • 25 |
  • Named Function Hotstrings
  • 26 |
  • Hotstring Helper
  • 27 |
28 | 29 |

Introduction and Simple Examples

30 |

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 way
33 |

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:

47 |
:X:btw::MsgBox ThisHotkey  ; Reports :X:btw
48 |

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 |

Ending Characters

51 |

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`t
53 |

The ending characters can be changed while the script is running by calling the Hotstring function as demonstrated below:

54 |
Hotstring("EndChars", "-()[]{}:;")
55 | 56 |

Options

57 |

A hotstring's default behavior can be changed in two possible ways:

58 |
    59 |
  1. The #Hotstring directive, which affects all hotstrings physically beneath that point in the script. The following example puts the C and R options into effect: #Hotstring c r.
  2. 60 |
  3. Putting options inside a hotstring's first pair of colons. The following example puts the C and * options (case-sensitive and "ending character not required") into effect for a single hotstring: :c*:j@::john@somedomain.com.
  4. 61 |
62 |

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.com
65 |

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.

67 |

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 |
    73 |
  • SI (SendInput): Key-delay is ignored because a delay is not possible in this mode. The exception to this is when SendInput is unavailable, in which case hotstrings revert to SendPlay mode below (which does obey key-delay).
  • 74 |
  • SP (SendPlay): A delay of length zero is the default, which for SendPlay is the same as -1 (no delay). In this mode, the delay is actually a PressDuration rather than a delay between keystrokes.
  • 75 |
  • SE (SendEvent): A delay of length zero is the default. Zero is recommended for most purposes since it is fast but still cooperates well with other processes (due to internally doing a Sleep 0). Specify k-1 to have no delay at all, which is useful to make auto-replacements faster if your CPU is frequently under heavy load. When set to -1, a script's process-priority becomes an important factor in how fast it can send keystrokes. To raise a script's priority, use ProcessSetPriority "High".
  • 76 |
77 |

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.

78 |

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.

82 |

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 |
    84 |
  • SI stands for SendInput, which typically has superior speed and reliability than the other modes. Another benefit is that like SendPlay below, SendInput postpones anything you type during a hotstring's auto-replacement text. This prevents your keystrokes from being interspersed with those of the replacement. When SendInput is unavailable, hotstrings automatically use SendPlay instead.
  • 85 |
  • SP stands for SendPlay, which may allow hotstrings to work in a broader variety of games.
  • 86 |
  • SE stands for SendEvent.
  • 87 |
88 |

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.

91 |

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 |

Long Replacements

99 |

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::).

107 |

Context-sensitive Hotstrings

108 |

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 |

AutoCorrect

115 |

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 |

Remarks

120 |

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.

122 |

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.

123 |

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.

124 |

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".

125 |

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).

126 |

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.

128 |

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.

129 |

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 |
    142 |
  • They are affected by the Suspend function.
  • 143 |
  • They obey #MaxThreads and #MaxThreadsPerHotkey (but not #MaxThreadsBuffer).
  • 144 |
  • Scripts containing hotstrings are automatically persistent.
  • 145 |
  • Non-auto-replace hotstrings will create a new thread when launched. In addition, they will update the built-in hotkey variables such as A_ThisHotkey.
  • 146 |
147 |

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 |

Named Function Hotstrings

150 |

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 |

Hotstring Helper

172 |

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 | List of Keys (Keyboard, Mouse and Controller) | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

List of Keys (Keyboard, Mouse and Controller)

14 |

Table of Contents

15 |
    16 |
  • Mouse 17 |
      18 |
    • General Buttons
    • 19 |
    • Advanced Buttons
    • 20 |
    • Wheel
    • 21 |
    22 |
  • 23 |
  • Keyboard 24 |
      25 |
    • General Keys
    • 26 |
    • Cursor Control Keys
    • 27 |
    • Numpad Keys
    • 28 |
    • Function Keys
    • 29 |
    • Modifier Keys
    • 30 |
    • Multimedia Keys
    • 31 |
    • Other Keys
    • 32 |
    33 |
  • 34 |
  • Game Controller (Gamepad, Joystick, etc.)
  • 35 |
  • Hand-held Remote Controls
  • 36 |
  • Special Keys
  • 37 |
  • CapsLock and IME
  • 38 |
39 | 40 |

Mouse

41 |

General Buttons

42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 |
NameDescription
LButtonPrimary mouse button. Which physical button this corresponds to depends on system settings; by default it is the left button.
RButtonSecondary mouse button. Which physical button this corresponds to depends on system settings; by default it is the right button.
MButtonMiddle or wheel mouse button
60 |

Advanced Buttons

61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 |
NameDescription
XButton14th mouse button. Typically performs the same function as Browser_Back.
XButton25th mouse button. Typically performs the same function as Browser_Forward.
75 |

Wheel

76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 93 | 94 |
NameDescription
WheelDownTurn the wheel downward (toward you).
WheelUpTurn the wheel upward (away from you).
WheelLeft
WheelRight

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.

95 |

Keyboard

96 |

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 |

General Keys

99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 |
NameDescription
CapsLockCapsLock (caps lock key) 107 |

Note: Windows IME may interfere with the detection and functionality of CapsLock; see CapsLock and IME for details.

108 |
SpaceSpace (space bar)
TabTab (tabulator key)
EnterEnter
Escape (or Esc)Esc
Backspace (or BS)Backspace
131 |

Cursor Control Keys

132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 |
NameDescription
ScrollLockScrollLock (scroll lock key). While Ctrl is held down, ScrollLock produces the key code of CtrlBreak, but can be differentiated from Pause by scan code.
Delete (or Del)Del
Insert (or Ins)Ins
HomeHome
EndEnd
PgUpPgUp (page up key)
PgDnPgDn (page down key)
Up↑ (up arrow key)
Down↓ (down arrow key)
Left← (left arrow key)
Right→ (right arrow key)
182 |

Numpad Keys

183 |

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 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 |
NameDescription
Numpad0 / NumpadIns0 / Ins
Numpad1 / NumpadEnd1 / End
Numpad2 / NumpadDown2 / ↓
Numpad3 / NumpadPgDn3 / PgDn
Numpad4 / NumpadLeft4 / ←
Numpad5 / NumpadClear5 / typically does nothing
Numpad6 / NumpadRight6 / →
Numpad7 / NumpadHome7 / Home
Numpad8 / NumpadUp8 / ↑
Numpad9 / NumpadPgUp9 / PgUp
NumpadDot / NumpadDel. / Del
NumLockNumLock (number lock key). While Ctrl is held down, NumLock produces the key code of Pause, so use ^Pause in hotkeys instead of ^NumLock.
NumpadDiv/ (division)
NumpadMult* (multiplication)
NumpadAdd+ (addition)
NumpadSub- (subtraction)
NumpadEnterEnter
247 |

Function Keys

248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 |
NameDescription
F1 - F24The 12 or more function keys at the top of most keyboards.
258 |

Modifier Keys

259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 313 | 314 |
NameDescription
LWinLeft Win. Corresponds to the <# hotkey prefix.
RWin 271 |

Right Win. Corresponds to the ># hotkey prefix.

272 |

Note: Unlike Ctrl/Alt/Shift, there is no generic/neutral "Win" key because the OS does not support it. However, hotkeys with the # modifier can be triggered by either Win.

273 |
Control (or Ctrl)Ctrl. As a hotkey (Control::) it fires upon release unless it has the tilde prefix. Corresponds to the ^ hotkey prefix.
AltAlt. As a hotkey (Alt::) it fires upon release unless it has the tilde prefix. Corresponds to the ! hotkey prefix.
ShiftShift. As a hotkey (Shift::) it fires upon release unless it has the tilde prefix. Corresponds to the + hotkey prefix.
LControl (or LCtrl)Left Ctrl. Corresponds to the <^ hotkey prefix.
RControl (or RCtrl)Right Ctrl. Corresponds to the >^ hotkey prefix.
LShiftLeft Shift. Corresponds to the <+ hotkey prefix.
RShiftRight Shift. Corresponds to the >+ hotkey prefix.
LAltLeft Alt. Corresponds to the <! hotkey prefix.
RAlt 310 |

Right Alt. Corresponds to the >! hotkey prefix.

311 |

Note: If your keyboard layout has AltGr instead of RAlt, you can probably use it as a hotkey prefix via <^>! as described here. In addition, LControl & RAlt:: would make AltGr itself into a hotkey.

312 |
315 |

Multimedia Keys

316 |

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 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 |
NameDescription
Browser_BackBack
Browser_ForwardForward
Browser_RefreshRefresh
Browser_StopStop
Browser_SearchSearch
Browser_FavoritesFavorites
Browser_HomeHomepage
Volume_MuteMute the volume
Volume_DownLower the volume
Volume_UpIncrease the volume
Media_NextNext Track
Media_PrevPrevious Track
Media_StopStop
Media_Play_PausePlay/Pause
Launch_MailLaunch default e-mail program
Launch_MediaLaunch default media player
Launch_App1Launch This PC (formerly My Computer or Computer)
Launch_App2Launch Calculator
395 |

Other Keys

396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 437 | 438 |
NameDescription
AppsKeyMenu. This is the key that invokes the right-click context menu.
PrintScreenPrtSc (print screen key)
CtrlBreakCtrl+Pause or Ctrl+ScrollLock
PausePause 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.
HelpHelp. This probably doesn't exist on most keyboards. It's usually not the same as F1.
SleepSleep. Note that the sleep key on some keyboards might not work with this.
SCnnnSpecify for nnn the scan code of a key. Recognizes unusual keys not mentioned above. See Special Keys for details.
VKnn

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 *VK24 or ~VK24, will fire for only one of the keys, not both (e.g. NumpadHome but not Home). For more information about the VKnn method, see Special Keys.

435 |

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, vk1Bsc001:: raises an error.

436 |
439 |

Game Controller (Gamepad, Joystick, etc.)

440 |

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.

441 |

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 |
    444 |
  • JoyX, JoyY, and JoyZ: The X (horizontal), Y (vertical), and Z (altitude/depth) axes of the stick.
  • 445 |
  • JoyR: The rudder or 4th axis of the stick.
  • 446 |
  • JoyU and JoyV: The 5th and 6th axes of the stick.
  • 447 |
  • JoyPOV: The point-of-view (hat) control.
  • 448 |
  • JoyName: The name of the controller or its driver.
  • 449 |
  • JoyButtons: The number of buttons supported by the controller (not always accurate).
  • 450 |
  • JoyAxes: The number of axes supported by the controller.
  • 451 |
  • JoyInfo: Provides a string consisting of zero or more of the following letters to indicate the controller's capabilities: Z (has Z axis), R (has R axis), U (has U axis), V (has V axis), P (has POV control), D (the POV control has a limited number of discrete/distinct settings), C (the POV control is continuous/fine). Example string: ZRUVPD
  • 452 |
453 |

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 |
    458 |
  • Controller remapping: Methods of sending keystrokes and mouse clicks with a controller.
  • 459 |
  • Controller-To-Mouse script: Using a controller as a mouse.
  • 460 |
461 | 462 |

Hand-held Remote Controls

463 |

Respond to signals from hand-held remote controls via the WinLIRC client script.

464 |

Special Keys

465 |

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 |
    467 |
  1. Ensure that at least one script is running that is using the keyboard hook. You can tell if a script has the keyboard hook by opening its main window and selecting "View->Key history" from the menu bar.
  2. 468 |
  3. Double-click that script's tray icon to open its main window.
  4. 469 |
  5. Press one of the "mystery keys" on your keyboard.
  6. 470 |
  7. Select the menu item "View->Key history"
  8. 471 |
  9. Scroll down to the bottom of the page. Somewhere near the bottom are the key-down and key-up events for your key. NOTE: Some keys do not generate events and thus will not be visible here. If this is the case, you cannot directly make that particular key a hotkey because your keyboard driver or hardware handles it at a level too low for AutoHotkey to access. For possible solutions, see further below.
  10. 472 |
  11. If your key is detectable, make a note of the 3-digit hexadecimal value in the second column of the list (e.g. 159).
  12. 473 |
  13. To define this key as a hotkey, follow this example: 474 |
    475 | SC159::MsgBox ThisHotkey " was pressed." ; Replace 159 with your key's value.
    476 | 
    Also see ThisHotkey.
  14. 477 |
478 |

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 |
    484 |
  1. 485 |

    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.

    486 |
  2. 487 |
  3. 488 |

    Try AHKHID from the archived forum. You can also try searching the forum for a keywords like RawInput*, USB HID or AHKHID.

    489 |
  4. 490 |
  5. 491 |

    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.

    493 |
  6. 494 |
495 | 496 |

CapsLock and IME

497 |

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:

510 |
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 | Scripting Language | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |

Scripting Language

13 |

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 |

Table of Contents

17 |
    18 |
  • General Conventions
  • 19 |
  • Comments
  • 20 |
  • Expressions 21 |
      22 |
    • Strings / Text
    • 23 |
    • Variables
    • 24 |
    • Constants
    • 25 |
    • Operators
    • 26 |
    • Function Calls 27 |
        28 |
      • Function Call Statements
      • 29 |
      • Optional Parameters
      • 30 |
    • 31 |
    • Operators for Objects
    • 32 |
    • Expression Statements
    • 33 |
  • 34 |
  • Control Flow Statements 35 |
      36 |
    • Control Flow vs. Other Statements
    • 37 |
    • Loop Statement
    • 38 |
    • Not Control Flow
    • 39 |
  • 40 |
  • Structure of a Script 41 |
      42 |
    • Global Code
    • 43 |
    • Functions
    • 44 |
    • #Include
    • 45 |
  • 46 |
  • Miscellaneous 47 |
      48 |
    • Dynamic Variables 49 |
        50 |
      • Pseudo-arrays
      • 51 |
    • 52 |
    • Labels
    • 53 |
  • 54 |
55 | 61 | 62 |

General Conventions

63 |

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.

64 |

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 |
    68 |
  • Function and method calls require there to be no space between the function/method name and (.
  • 69 |
  • Spaces are required when performing concatenation.
  • 70 |
  • Spaces may be required between two operators, to remove ambiguity.
  • 71 |
  • Single-line comments require a leading space if they are not at the start of the line.
  • 72 |
73 |

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 |
    76 |
  • Continuation prefix: Lines that begin with an expression operator (except ++ and --) are merged with the previous line. Lines are merged regardless of whether the line actually contains an expression.
  • 77 |
  • Continuation by enclosure: A sub-expression enclosed in (), [] or {} can automatically span multiple lines in most cases.
  • 78 |
  • Continuation section: Multiple lines are merged with the line above the section, which starts with ( and ends with ) (both symbols must appear at the beginning of a line, excluding whitespace).
  • 79 |
80 | 81 | 82 |

Comments

83 |

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:

89 |
/*
 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.

99 |

Since comments are filtered out when the script is read from file, they do not impact performance or memory utilization.

100 | 101 |

Expressions

102 |

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.

103 |

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.

104 |

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 |

Strings / Text

107 |

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'.

109 |

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."'.

110 |

Quoted strings can contain other escape sequences such as `t (tab), `n (linefeed), and `r (carriage return).

111 | 112 |

Variables

113 |

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:

115 |
    116 |
  • Implicit concatenation: "The value is " MyVar
  • 117 |
  • Explicit concatenation: "The value is " . MyVar
  • 118 |
119 |

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".

123 |

Percent signs within an expression are used to create dynamic variable references, but these are rarely needed.

124 | 125 |

Keyword Constants

126 |

A constant is simply an unchangeable value, given a symbolic name. AutoHotkey currently has the following constants:

127 | 128 | 129 | 130 | 131 |
NameValueTypeDescription
False0IntegerBoolean false, sometimes meaning "off", "no", etc.
True1IntegerBoolean true, sometimes meaning "on", "yes", etc.
132 |

Unlike the read-only built-in variables, these cannot be returned by a dynamic reference.

133 | 134 |

Operators

135 |

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.

136 |
    137 |
  • Unary operators are written either before or after a single operand, depending on the operator. For example, -x or not keyIsDown.
  • 138 |
  • Binary operators are written in between their two operands. For example, 1+1 or 2 * 5.
  • 139 |
  • AutoHotkey has only one ternary operator, which takes the form condition ? valueIfTrue : valueIfFalse.
  • 140 |
141 |

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).

142 |

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

143 | 144 |

Function Calls

145 |

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.

147 |

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.

149 |

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.

150 | 151 |

Function Call Statements

152 |

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:

153 |
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.

156 |

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 |
    160 |
  • If there is a return value, it is always discarded.
  • 161 |
  • Like control flow statements, they cannot be used inside an expression.
  • 162 |
  • When optional parameters are omitted, any commas at the end of the parameter list must also be omitted to prevent line continuation.
  • 163 |
  • Function call statements cannot be variadic, although they can pass a fixed number of parameters to a variadic function.
  • 164 |
165 | 166 |

Optional Parameters

167 |

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", , , &notepadPID)
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:

174 |
    175 |
  • For a user-defined function, the parameter's default value is used.
  • 176 |
  • For a built-in function, the parameter is considered to have been omitted.
  • 177 |
  • For an array literal such as [var?], the element is included in the array's length but is given no value.
  • 178 |
  • For an object literal such as {x: y?}, the property is not assigned.
  • 179 |
180 |

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.

181 |

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).

182 | 183 |

Operators for Objects

184 |

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.

186 |

Alpha.Beta() is a method call. Alpha is implicitly passed as a parameter, but this is normally hidden from view as each method definition implicitly defines a parameter named this. The parentheses can be omitted in specific cases; see Function Call Statements.

187 |

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.

188 |

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.

189 |

Alpha[Index] typically invokes the __Item 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. For COM objects, this invokes the default property by ID (DISPID_VALUE), so is different to explicitly specifying the __Item property.

190 |

[A, B, C] creates an Array with the initial contents A, B and C (all variables in this case), where A is element 1.

191 |

{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}.

192 |

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*]).

193 | 194 |

Expression Statements

195 |

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.

196 |

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--.

198 |

Known limitation: For x++ and x--, there currently cannot be a space between the variable name and operator.

199 |

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.

200 |

Method calls such as MyObj.MyMethod().

201 |

Member access using square brackets, such as MyObj[Index], which can have side-effects like a function call.

202 |

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.

203 |

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.

204 |

Note: The condition cannot begin with ! or any other expression operator, as it would be interpreted as a continuation line.

205 |

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.

206 |

Expressions starting with a double-deref, such as %varname% := 1. This is primarily due to implementation complexity.

207 |

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.

208 |

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".

209 | 210 |

Control Flow Statements

211 |

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.

213 |

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).

214 |

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.

215 |

The following control flow statements exist:

216 |
    217 |
  • A block (denoted by a pair of braces) groups zero or more statements to act as a single statement.
  • 218 |
  • An If statement causes its body to be executed or not depending on a condition. It can be followed by an Else statement, which executes only if the condition was not met.
  • 219 |
  • Goto jumps to the specified label and continues execution.
  • 220 |
  • Return returns from a function.
  • 221 |
  • A Loop statement (Loop, While or For) executes its body repeatedly. 222 |
      223 |
    • Break exits (terminates) a loop.
    • 224 |
    • Continue skips the rest of the current loop iteration and begins a new one.
    • 225 |
    • Until causes a loop to terminate when an expression evaluates to true. The expression is evaluated after each iteration.
    • 226 |
  • 227 |
  • Switch compares a value with multiple cases and executes the statements of the first match.
  • 228 |
  • Exception handling: 229 |
      230 |
    • Try guards its body against runtime errors and values thrown by the throw statement.
    • 231 |
    • Catch executes if an exception of a given type is thrown within a try statement.
    • 232 |
    • Else, when used after a catch statement, executes only if no exception is thrown within a try statement.
    • 233 |
    • Finally executes its body when control is being transferred out of a try or catch statement's body.
    • 234 |
    • Throw throws an exception to be handled by try/catch or OnError, or to display an error dialog.
    • 235 |
  • 236 |
237 | 238 |

Control Flow vs. Other Statements

239 |

Control flow statements differ from function call statements in several ways:

240 |
    241 |
  • The opening brace of a block can be written at the end of the same line as an If, Else, Loop, While, For, Try, Catch or Finally statement (basically any control flow statement which has a body). This is referred to as the One True Brace (OTB) style.
  • 242 |
  • Else, Try and Finally allow any valid statement to their right, as they require a body but have no parameters.
  • 243 |
  • If, While, Return, Until, Loop Count, For, Catch, Break, Continue, Throw, and Goto allow an open parenthesis to be used immediately after the name, to enclose the entire parameter list. Although these look like function calls, they are not, and cannot be used mid-expression. For example, if(expression).
  • 244 |
  • Control flow statements cannot be overridden by defining a function with the same name.
  • 245 |
246 | 247 |

Loop Statement

248 |

There are several types of loop statements:

249 |
    250 |
  • Loop Count executes a statement repeatedly: either the specified number of times or until Break is encountered.
  • 251 |
  • Loop Reg retrieves the contents of the specified registry subkey, one item at a time.
  • 252 |
  • Loop Files retrieves the specified files or folders, one at a time.
  • 253 |
  • Loop Parse retrieves substrings (fields) from a string, one at a time.
  • 254 |
  • Loop Read retrieves the lines in a text file, one at a time.
  • 255 |
  • While executes a statement repeatedly until the specified expression evaluates to false. The expression is evaluated before each iteration.
  • 256 |
  • For executes a statement once for each value or pair of values returned by an enumerator, such as each key-value pair in an object.
  • 257 |
258 |

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 |

Not Control Flow

278 |

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 |

Structure of a Script

281 | 282 |

Global Code

283 |

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 |

Subroutines

289 |

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 |

Functions

292 |

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 |
    295 |
  1. A function can be called by the script itself. This kind of function might be used to avoid repetition, to make the code more manageable, or perhaps for other purposes.
  2. 296 |
  3. A function can be called by the program in response to some event, such as the user pressing a hotkey. For instance, each hotkey is associated with a function to execute whenever the hotkey is pressed.
  4. 297 |
298 |

There are multiple ways to define a function:

299 |
    300 |
  • A function definition combining a name, parentheses and a block of code. This defines a function which can be executed by name with a function call or function call statement. For example: 301 |
    SayHello()  ; Define the SayHello function.
    302 | {
    303 |     MsgBox "Hello!"
    304 | }
    305 | 
    306 | SayHello  ; Call the SayHello function.
    307 |
  • 308 |
  • A hotkey or hotstring definition, combining a hotkey or hotstring with a single statement or a block of code. This type of function cannot be called directly, but is executed whenever the hotkey or hotstring is activated. For example: 309 |
    #w::Run "wordpad"  ; Press Win-W to run Wordpad.
    310 | #n::  ; Press Win-N to run Notepad.
    311 | {
    312 |     Run "notepad"
    313 | }
    314 |
  • 315 |
  • A fat arrow expression defines a function which evaluates an expression and returns its result, instead of executing a block of code. Such functions usually have no name as they are passed directly to another function. For example: 316 |
    SetTimer () => MsgBox("Hello!"), -1000  ; Says hello after 1 second.
    317 |
  • 318 |
  • The fat arrow syntax can also be used outside of expressions as shorthand for a normal function or method definition. For example, the following is equivalent to the SayHello definition above, except that this one returns "OK": 319 |
    SayHello() => MsgBox("Hello!")
    320 |
  • 321 |
322 |

Variables in functions are local to that function by default, except in the following cases:

323 |
    324 |
  • When the function is assume-global.
  • 325 |
  • When a variable is referenced but not used as the target of an assignment or the reference operator (&var).
  • 326 |
  • When referring to a local variable of an outer function inside a nested function.
  • 327 |
328 |

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.

338 |

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.

339 |

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 |

#Include

344 |

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.

346 |

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 |

Miscellaneous

350 | 351 |

Dynamic Variables

352 |

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.

361 |

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.

362 |

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.blue
367 | 368 |

Pseudo-arrays

369 |

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 |
    380 |
  • As the individual elements are just normal variables, one can assign or retrieve a value, but cannot remove or insert elements.
  • 381 |
  • Because the pseudo-array is only conceptual and not a single value, it can't be passed to or returned from a function, or copied as a whole.
  • 382 |
  • A pseudo-array cannot be declared as a whole, so some "elements" may resolve to global (or captured) variables while others do not.
  • 383 |
  • If a variable is referenced non-dynamically but only assigned dynamically, a load-time warning may be displayed. Such warnings are a very effective way to detect errors, so disabling them is not recommended.
  • 384 |
  • Current versions of the language do not permit creating new variables dynamically. This is partly to encourage best practices, and partly to avoid inconsistency between dynamic and non-dynamic variable references in functions.
  • 385 |
386 | 387 |

Labels

388 |

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 | Built-in Classes | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Built-in Classes

15 | 16 |
    17 |
  • Any
      18 |
    • Object
        19 |
      • Array
      • 20 |
      • Buffer
          21 |
        • ClipboardAll
        • 22 |
      • 23 |
      • Class
      • 24 |
      • Error
          25 |
        • MemoryError
        • 26 |
        • OSError
        • 27 |
        • TargetError
        • 28 |
        • TimeoutError
        • 29 |
        • TypeError
        • 30 |
        • UnsetError
            31 |
          • MemberError
              32 |
            • PropertyError
            • 33 |
            • MethodError
            • 34 |
          • 35 |
          • UnsetItemError
          • 36 |
        • 37 |
        • ValueError
            38 |
          • IndexError
          • 39 |
        • 40 |
        • ZeroDivisionError
        • 41 |
      • 42 |
      • File
      • 43 |
      • Func
          44 |
        • BoundFunc
        • 45 |
        • Closure
        • 46 |
        • Enumerator
        • 47 |
      • 48 |
      • Gui
      • 49 |
      • Gui.Control
          50 |
        • Gui.ActiveX
        • 51 |
        • Gui.Button
        • 52 |
        • Gui.CheckBox
        • 53 |
        • Gui.Custom
        • 54 |
        • Gui.DateTime
        • 55 |
        • Gui.Edit
        • 56 |
        • Gui.GroupBox
        • 57 |
        • Gui.Hotkey
        • 58 |
        • Gui.Link
        • 59 |
        • Gui.List
            60 |
          • Gui.ComboBox
          • 61 |
          • Gui.DDL
          • 62 |
          • Gui.ListBox
          • 63 |
          • Gui.Tab
          • 64 |
        • 65 |
        • Gui.ListView
        • 66 |
        • Gui.MonthCal
        • 67 |
        • Gui.Pic
        • 68 |
        • Gui.Progress
        • 69 |
        • Gui.Radio
        • 70 |
        • Gui.Slider
        • 71 |
        • Gui.StatusBar
        • 72 |
        • Gui.Text
        • 73 |
        • Gui.TreeView
        • 74 |
        • Gui.UpDown
        • 75 |
      • 76 |
      • InputHook
      • 77 |
      • Map
      • 78 |
      • Menu
          79 |
        • MenuBar
        • 80 |
      • 81 |
      • RegExMatchInfo
      • 82 |
    • 83 |
    • Primitive
        84 |
      • Number
          85 |
        • Float
        • 86 |
        • Integer
        • 87 |
      • 88 |
      • String
      • 89 |
    • 90 |
    • VarRef
    • 91 |
    • ComValue
        92 |
      • ComObjArray
      • 93 |
      • ComObject
      • 94 |
      • ComValueRef
      • 95 |
    • 96 |
  • 97 |
98 | 99 | 100 | -------------------------------------------------------------------------------- /docs/Objects.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Objects - Definition & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 14 | 15 | 16 | 17 |

Objects

18 | 19 |

An object combines a number of properties and methods.

20 |

Related topics:

21 |
    22 |
  • Objects: General explanation of objects.
  • 23 |
  • Object Protocol: Specifics about how a script interacts with an object.
  • 24 |
  • Function objects: Objects which can be called.
  • 25 |
26 | 27 |

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 |
    32 |
  • AutoHotkey objects are instances of the Object class. These support ad hoc properties, and have methods for discovering which properties exist. Array, Map and all user defined and built-in classes are derived from Object.
  • 33 |
  • COM objects such as those created by ComObject. These are implemented by external libraries, so often differ in behaviour to AutoHotkey objects. ComObject typically represents a COM or "Automation" object implementing the IDispatch interface, but is also used to wrap values of specific types to be passed to COM objects and functions.
  • 34 |
35 | 36 |

Table of Contents

37 |
    38 |
  • Basic Usage 39 |
      40 |
    • Arrays
    • 41 |
    • Maps (Associative Arrays)
    • 42 |
    • Objects
    • 43 |
    • Object Literal
    • 44 |
    • Freeing Objects
    • 45 |
    46 |
  • 47 |
  • Extended Usage 48 |
      49 |
    • Arrays of Arrays
    • 50 |
    51 |
  • 52 |
  • Custom Objects 53 |
      54 |
    • Ad Hoc
    • 55 |
    • Delegation
    • 56 |
    • Creating a Base Object
    • 57 |
    • Classes
    • 58 |
    • __Enum Method
    • 59 |
    • __Item Property
    • 60 |
    • Construction and Destruction
    • 61 |
    • Meta-Functions
    • 62 |
    63 |
  • 64 |
  • Primitive Values 65 |
      66 |
    • Adding Properties and Methods
    • 67 |
    68 |
  • 69 |
  • Implementation 70 |
      71 |
    • Reference Counting
    • 72 |
    • Pointers to Objects
    • 73 |
    74 |
  • 75 |
76 | 77 |

Basic Usage

78 | 79 |

Arrays

80 |

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):

86 |
MyArray[Index] := Value
87 |

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 |

Maps (Associative Arrays)

112 |

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:

115 |
Value := MyMap[Key]
116 |

Assign an item:

117 |
MyMap[Key] := Value
118 |

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 ' = ' value
124 | 125 |

Objects

126 |

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.

127 |

Examples:

128 |

Retrieve or set a property literally named Property:

129 |
Value := MyObject.Property
130 |
MyObject.Property := Value
131 |

Retrieve or set a property where the name is determined by evaluating an expression or variable:

132 |
Value := MyObject.%Expression%
133 |
MyObject.%Expression% := Value
134 |

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] := Value
141 |

An object may also support indexing: MyArray[Index] actually invokes the __Item property of MyArray, passing Index as a parameter.

142 | 143 |

Object Literal

144 |

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:

145 |
Coord := {X: 13, Y: 240}
146 |

This is equivalent:

147 |
Coord := Object()
148 | Coord.X := 13
149 | Coord.Y := 240
150 |

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.key
155 | 156 |

Freeing Objects

157 |

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.

165 |
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 |

Extended Usage

175 | 176 |

Arrays of Arrays

177 |

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 |

Custom Objects

219 |

There are two general ways to create custom objects:

220 |
    221 |
  • Ad hoc: create an object and add properties.
  • 222 |
  • Delegation: define properties in a shared base object or class.
  • 223 |
224 |

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 |

Ad Hoc

228 |

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.

242 |

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.

243 |

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 |

Delegation

248 |

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.)

251 | 252 |

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.

253 |

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 |
    256 |
  • By creating a normal object.
  • 257 |
  • By defining a class. Each class has a Prototype property containing an object which all instances of that class are based on, while the class itself becomes the base object of any direct subclasses.
  • 258 |
259 |

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 |

Creating a Base Object

262 |

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.

267 | 268 |

Classes

269 |
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 | Wikipedia
271 |

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().

272 |

Since Objects are dynamic and prototype-based, each class consists of two parts:

273 |
    274 |
  • The class has a Prototype object, on which all instances of the class are based. All methods and dynamic properties that apply to instances of the class are contained by the prototype object. This includes all properties and methods which lack the static keyword.
  • 275 |
  • The class itself is an object, containing only static methods and properties. This includes all properties and methods with the 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.
  • 276 |
277 |

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.

319 |

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.

320 |

Within this documentation, the word "class" on its own usually means a class object constructed with the class keyword.

321 |

Class definitions can contain variable declarations, method definitions and nested class definitions.

322 | 323 |

Instance Variables

324 |

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):

325 |
InstanceVar := Expression
326 |

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.

327 |

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).

328 |

To access an instance variable (even within a method), always specify the target object; for example, this.InstanceVar.

329 |

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.

330 | 331 |

Static/Class Variables

332 |

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 := Expression
334 |

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.

336 |

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.

337 |

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).

338 | 339 |

Nested Classes

340 |

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).

341 |
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 |
    350 |
  • 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).
  • 351 |
  • X.Y := 1 is an error by default (the property is read-only).
  • 352 |
  • Referring to or calling the class for the first time causes it to be initialized.
  • 353 |
354 | 355 |

Methods

356 |

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.

357 |

There are two types of methods:

358 |
    359 |
  • Instance methods are defined as below, and are attached to the class's Prototype, which makes them accessible via any instance of the class. When the method is called, this refers to an instance of the class.
  • 360 |
  • Static methods are defined by preceding the method name with the separate keyword 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.
  • 361 |
362 |

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.

363 |
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() => Expression
372 | 373 |

Super

374 |

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:

375 |
    376 |
  • 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.
  • 377 |
  • super.Method() implicitly passes this as the first (hidden) parameter.
  • 378 |
  • Since it is not known where (or whether) ClassName exists within the chain of base objects, ClassName itself is used as the starting point. Therefore, 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.
  • 379 |
  • An error is thrown if the property is not defined in a superclass or cannot be invoked.
  • 380 |
381 |

The keyword super must be followed by one of the following symbols: .[(

382 |

super() is equivalent to super.call().

383 | 384 |

Properties

385 |

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.

397 |

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.

399 |

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.

400 |

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.

401 |

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.

402 |

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.

403 |

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 Properties

406 |

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:

413 |
ShorterProperty[Parameters] => Expression which calculates property value
414 |

In both cases, the square brackets must be omitted unless parameters are defined.

415 | 416 |

__Enum Method

417 |
__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 |

__Item Property

422 |

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):

433 |
    434 |
  • object[params] is equivalent to object.__Item[params] when there are parameters.
  • 435 |
  • object[] is equivalent to object.__Item.
  • 436 |
437 |

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.

446 | 447 |

Construction and Destruction

448 |

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:

449 |
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 |

Class Initialization

475 |

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.

476 |

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.

477 |

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.

478 |

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.

479 |

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.

480 |

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:

481 |
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 |

Meta-Functions

495 |
496 | class ClassName {
497 |     __Get(Name, Params)
498 |     __Set(Name, Params, Value)
499 |     __Call(Name, Params)
500 | }
501 | 
502 |
503 |
Name
504 |

The name of the property or method.

505 |
Params
506 |

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.

507 |
Value
508 |

The value being assigned.

509 |
510 |

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.

511 |

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 |
    514 |
  • Call: Throw a MethodError.
  • 515 |
  • If parameters were given, throw an exception (there's no object to forward the parameters to).
  • 516 |
  • Get: Throw a PropertyError.
  • 517 |
  • Set: Define a new property with the given value, such as by calling DefineProp.
  • 518 |
519 |

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 |
    522 |
  • x[y]: Using square brackets without a property name only invokes the __Item property.
  • 523 |
  • x(): Calling the object itself only invokes the Call method. This includes internal calls made by built-in functions such as SetTimer and Hotkey.
  • 524 |
  • Internal calls to other meta-functions or double-underscore methods do not trigger __Call.
  • 525 |
526 | 527 |

Dynamic Properties

528 |

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

532 |

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 |
    534 |
  • Primitive (extends Any)
      535 |
    • Number
        536 |
      • Float
      • 537 |
      • Integer
      • 538 |
    • 539 |
    • String
    • 540 |
  • 541 |
542 |

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.

543 |

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.

545 | 546 |

Adding Properties and Methods

547 |

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:

548 |
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 |

Implementation

560 |

Reference Counting

561 |

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")  ; 20
572 |

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.

573 |

To run code when the last reference to an object is being released, implement the __Delete meta-function.

574 |

Problems with Reference Counting

575 |

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: 2
580 |

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.

581 |

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.

585 |

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.

587 |

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 deleted
591 |

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.

592 |

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).

623 |

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 |
    650 |
  • Decrement the reference count (Release) after storing the reference.
  • 651 |
  • Increment the reference count (AddRef) before unsetting the reference.
  • 652 |
  • Explicitly unset the reference before __Delete returns (doing so before it is called is fine).
  • 653 |
654 |

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 |

Pointers to Objects

657 |

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):

659 |
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.

666 |

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:

669 |
670 | ObjAddRef(address), myObject := ObjFromPtr(address)
671 | myObject := ObjFromPtrAddRef(address)
672 | 
673 | 674 | 675 | 676 | -------------------------------------------------------------------------------- /docs/Program.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Using the Program | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |

Using the Program

13 |

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.

14 |
#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 |

Table of Contents

26 |
    27 |
  • Create a Script
  • 28 |
  • Edit a Script
  • 29 |
  • Run a Script
  • 30 |
  • Tray Icon
  • 31 |
  • Main Window
  • 32 |
  • Embedded Scripts
  • 33 |
  • Command Line Usage
  • 34 |
  • Portability of AutoHotkey.exe
  • 35 |
  • Launcher
  • 36 |
  • Dash
  • 37 |
  • New Script
  • 38 |
  • Installation 39 |
      40 |
    • Run with UI Access
    • 41 |
  • 42 |
43 | 44 |

Create a Script

45 |

There are a few common ways to create a script file:

46 |
    47 |
  • In Notepad (or a text editor of your choice), save a file with the .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.

  • 49 |
  • In Explorer, right-click in empty space in the folder where you want to save the script, then select New and AutoHotkey Script. You can then type a name for the script (taking care not to erase the .ahk extension if it is visible).
  • 50 |
  • In the Dash, select New script, type a name for the script (excluding the .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.
  • 51 |
52 |

See Scripting Language for details about how to write a script.

53 | 54 |

Edit a Script

55 |

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 |

Run a Script

59 |

With AutoHotkey installed, there are several ways to run a script:

60 |
    61 |
  • Double-click a script file (or shortcut to a script file) in Explorer.
  • 62 |
  • Call AutoHotkey.exe on the command line and pass the script's filename as a command-line parameter.
  • 63 |
  • After creating the default script, launch AutoHotkey via the shortcut in the Start menu to run it.
  • 64 |
  • If AutoHotkey is pinned to the taskbar or Start menu on Windows 7 or later, recent or pinned scripts can be launched via the program's Jump List.
  • 65 |
66 |

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 |

Tray Icon

70 |

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 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 |
green H iconThe default tray icon.
green icon with a Pause symbolThe script is paused.
green icon with a transparent HThe script is suspended.
green icon with a transparent Pause symbolThe script is paused and suspended.
96 |

Right-click the tray icon to show the tray menu, which has the following options by default:

97 |
    98 |
  • Open - Open the script's main window.
  • 99 |
  • Help - Open the AutoHotkey offline help file.
  • 100 |
  • Window Spy - Displays various information about a window.
  • 101 |
  • Reload Script - See Reload.
  • 102 |
  • Edit Script - See Edit.
  • 103 |
  • Suspend Hotkeys - Suspend or unsuspend hotkeys.
  • 104 |
  • Pause Script - Pause or unpause the script.
  • 105 |
  • Exit - Exit the script.
  • 106 |
107 |

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 |
    110 |
  • A_TrayMenu returns a Menu object which can be used to customise the tray menu.
  • 111 |
  • A_IconHidden or the #NoTrayIcon directive can be used to hide (or show) the tray icon.
  • 112 |
  • A_IconTip can be assigned new tooltip text for the tray icon.
  • 113 |
  • TraySetIcon can be used to change the icon.
  • 114 |
115 | 116 |

Main Window

117 |

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 |
    119 |
  • Lines most recently executed - See ListLines.
  • 120 |
  • Variables and their contents - See ListVars.
  • 121 |
  • Hotkeys and their methods - See ListHotkeys.
  • 122 |
  • Key history and script info - See KeyHistory.
  • 123 |
124 |

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 |

Main Window Title

147 |

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 | 149 | 150 | 151 | 152 | 153 |
Loaded FromTitle ExpressionExample
.ahk fileA_ScriptFullPath " - AutoHotkey v" A_AhkVersionE:\My Script.ahk - AutoHotkey v1.1.33.09
Main resource (compiled script)A_ScriptFullPathE:\My Script.exe
Any other resourceA_ScriptFullPath " - " A_LineFileE:\My AutoHotkey.exe - *BUILTIN-TOOL.AHK
154 |

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 |

Embedded Scripts

166 |

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 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 |
IDSpecUsage
1*#1This 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.
2*#2If present, this script is automatically "included" before any script that the program loads, and before any file specified with /include.
180 |

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 |

Command Line Usage

184 |

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 |

Portability of AutoHotkey.exe

187 |

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 |

Launcher

191 |

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 |
    194 |
  • v1: MsgBox, with comma, MsgBox % "no end percent" and Legacy = assignment.
  • 195 |
  • v1: Multi-line hotkeys without braces or a function definition.
  • 196 |
  • Common directives such as #NoEnv and #If (v1) or #HotIf (v2).
  • 197 |
  • v2: Unambiguous use of continuation by enclosure or end-of-line continuation operators.
  • 198 |
  • v2: Unambiguous use of 'single quotes' or fat arrow => in an expression.
  • 199 |
200 |

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 |
    204 |
  • Only the main file is checked.
  • 205 |
  • Since it is legal to include a line like /****/ 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).
  • 206 |
  • Only syntax is checked, not semantics. For instance, 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.
  • 207 |
  • Since the patterns being detected are effectively syntax errors in one version, a script with actual syntax errors or incorrectly mixed syntax might be misidentified.
  • 208 |
209 |

Note: Declaring the required version with #Requires at the top of the main file eliminates any ambiguity.

210 | 211 |

Launch Settings

212 |

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 |

Criteria

217 |

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.

220 |

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 |

Run *Launch

226 |

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 |
    230 |
  • /Launch causes the process ID (PID) of the newly launched script to be returned as the launcher's exit code, whereas it would normally return the launched script's exit code. Run's OutputVarPID parameter returns the PID of the launcher.
  • 231 |
  • /Launch causes the launcher to exit immediately after launching the script. If /Launch is not used, the launcher generally has to assume that its parent process might be doing something like RunWait(PathOfScript), which wouldn't work as expected if the launcher exited before the launched script.
  • 232 |
233 | 234 |

Command Line Usage

235 |

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 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 262 | 263 |
SwitchMeaning
/LaunchCauses 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.
/RunWith criteriaSpecifies additional criteria for determining which executable to use to launch the script. For example, /RunWith UIA.
/Which 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 `n:

255 |
    256 |
  • The version number. If #Requires was detected, this is whatever number it specified, excluding "v". Otherwise, it is an integer the same as the exit code, unless the version wasn't detected, in which case this is 0 to indicate that the user would have been prompted, or 1 or 2 to indicate the user's preferred version as configured in the Launch Settings.
  • 257 |
  • The path of the interpreter EXE that would be used, if one was found. This is blank if the user would have been prompted or no compatible interpreters were found.
  • 258 |
  • Any additional command-line switches that the launcher would insert, such as /CP65001.
  • 259 |
260 |

Additional lines may be returned in future.

261 |
264 | 265 |

Dash

266 |

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 |
    268 |
  • New script: Create a new script from a template.
  • 269 |
  • Compile: Opens Ahk2Exe, or offers to automatically download and install it.
  • 270 |
  • Help files (F1): Shows a menu containing help files and online documentation for v1 and v2, and any other CHM files found in the installation directory.
  • 271 |
  • Window spy
  • 272 |
  • Launch settings: Configure the launcher.
  • 273 |
  • Editor settings: Set the default editor for .ahk files.
  • 274 |
275 |

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 |

New Script

278 |

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 |
    281 |
  • Edit template: Open the template in the default editor. If it is a preinstalled template, an editable copy is created instead of opening the original.
  • 282 |
  • Hide template: Adds the template name to a list of templates that will not be shown in the GUI. To unhide a template, delete the corresponding registry value from HKCU\Software\AutoHotkey\New\HideTemplate.
  • 283 |
  • Set as default: Sets the template to be selected by default.
  • 284 |
285 |

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 |
    288 |
  • Default to Create: Pressing Enter will activate the Create button, which creates the script and selects it in Explorer.
  • 289 |
  • Default to Edit: Pressing Enter will activate the Edit button, which creates the script and opens it in the default script editor.
  • 290 |
  • Stay open: If enabled, the window will not close automatically after creating a script.
  • 291 |
  • Set folder as default: Sets the current folder as the default location to save scripts. The default location is used if the New Script window is opened directly or via the Dash; it is not used when New Script is invoked via the Explorer context menu.
  • 292 |
  • Open templates folder: Opens the folder where user-defined templates can be stored.
  • 293 |
294 | 295 |

Templates

296 |

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.

304 |

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.

306 | 307 |

Installation

308 |

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 |
    310 |
  • Where to install.
  • 311 |
  • Whether to install for all users or the current user.
  • 312 |
313 |

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 |

Installing with v1

317 |

There are two methods of installing v1 and v2 together:

318 |
    319 |
  1. Install v1 first, and then v2. In that case, the v1 files are left in the root of the installation directory, to avoid breaking any external tools or shortcuts that rely on their current path.
  2. 320 |
  3. Install v1 as an additional version. Running a v1.1.34.03 or later installer gives this option. Alternatively, use the /install switch described below. Each version installs into its own subdirectory.
  4. 321 |
322 |

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 |

Default Version

325 |

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 |

Command Line Usage

328 |

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.

329 |
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.

334 |

To re-register the current installation:

335 |
AutoHotkey32.exe UX\install.ahk
336 |

To uninstall:

337 |
AutoHotkey32.exe UX\install.ahk /uninstall
338 |

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\AutoHotkey
341 |

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:

342 |
    343 |
  • Terminate scripts to allow AutoHotkey*.exe to be overwritten.
  • 344 |
  • Overwrite files that were not previously registered by the installer, or that were modified since registration.
  • 345 |
346 | 347 |

Taskbar Buttons

348 |

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 |

Run with UI Access

351 |

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 |
    354 |
  • Copies each AutoHotkey*.exe to AutoHotkey*_UIA.exe.
  • 355 |
  • Sets the uiAccess attribute in each UIA.exe file's embedded manifest.
  • 356 |
  • Creates a self-signed digital certificate named "AutoHotkey" and signs each UIA.exe file.
  • 357 |
  • Registers the UIAccess shell verb, which appears in Explorer's context menu as "Run with UI access". By default this executes the launcher, which tries to select an appropriate UIA.exe file to run the script.
  • 358 |
359 |

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"'

361 |

Known limitations:

362 |
    363 |
  • UIA is only effective if the file is in a trusted location; i.e. a Program Files sub-directory.
  • 364 |
  • UIA.exe files created on one computer cannot run on other computers without first installing the digital certificate which was used to sign them.
  • 365 |
  • UIA.exe files cannot be started via CreateProcess due to security restrictions. ShellExecute can be used instead. Run tries both.
  • 366 |
  • UIA.exe files cannot be modified, as it would invalidate the file's digital signature.
  • 367 |
  • Because UIA programs run at a different "integrity level" than other programs, they can only access objects registered by other UIA programs. For example, ComObjActive("Word.Application") will fail because Word is not marked for UI Access.
  • 368 |
  • The script's own windows can't be automated by non-UIA programs/scripts for security reasons.
  • 369 |
  • Running a non-UIA script which uses a mouse hook (even as simple as 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.
  • 370 |
  • UIA prevents the Gui +Parent option from working on an existing window if the new parent is always-on-top and the child window is not.
  • 371 |
372 |

For more details, see Enable interaction with administrative programs on the archived forum.

373 | 374 | 375 | 376 | -------------------------------------------------------------------------------- /docs/Scripts.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Scripts - Definition & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Scripts

14 |

Related topics:

15 |
    16 |
  • Using the Program: How to use AutoHotkey, in general.
  • 17 |
  • Concepts and Conventions: General explanation of various concepts utilised by AutoHotkey.
  • 18 |
  • Scripting Language: Specific details about syntax (how to write scripts).
  • 19 |
20 | 21 |

Table of Contents

22 |
    23 |
  • Introduction
  • 24 |
  • Script Startup (the Auto-execute Thread): Taking action immediately upon starting the script, and changing default settings.
  • 25 |
  • Splitting a Long Line into a Series of Shorter Ones: This can improve a script's readability and maintainability.
  • 26 |
  • Script Library Folders
  • 27 |
  • Convert a Script to an EXE (Ahk2Exe): Convert a .ahk script into a .exe file that can run on any PC.
  • 28 |
  • Passing Command Line Parameters to a Script: The variable A_Args contains the incoming parameters.
  • 29 |
  • Script File Codepage: Using non-ASCII characters safely in scripts.
  • 30 |
  • Debugging a Script: How to find the flaws in a misbehaving script.
  • 31 |
32 |

Introduction

33 |

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 |

Script Startup (the Auto-execute Thread)

37 |

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 |

Splitting a Long Line into a Series of Shorter Ones

45 |

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 |
    48 |
  • Continuation operator: Start or end a line with an expression operator to join it to the previous or next line.
  • 49 |
  • Continuation by enclosure: A sub-expression enclosed in (), [] or {} can automatically span multiple lines in most cases.
  • 50 |
  • Continuation section: Mark a group of lines to be merged together, with additional options such as what text (or code) to insert between lines.
  • 51 |
52 |

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:

77 |
 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.

90 |

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):

98 |
    99 |
  • A brace is never interpreted as the beginning of a block if it is preceded by an unclosed (/[/{, since that would produce an invalid expression. For example, the brace in If ({ is the start of an object literal.
  • 100 |
  • An object literal cannot legally follow ) 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).
  • 101 |
  • For control flow statements which require a body (and therefore support OTB), the brace can be the start of an object literal only if it is preceded by an operator, such as := { or for x in {. In particular, the brace in Loop { is always block-begin, and If { and While { are always errors.
  • 102 |
103 |

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 - inside a quoted/literal string:
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 - outside a quoted/literal string:
120 | Var :=
121 | (
122 | "Same as above, except that quote marks are not automatically escaped.
123 | Specify variables as follows: " Var "
124 | A line of text."
125 | )
126 | 
127 | ; EXAMPLE #3:
128 | FileAppend "
129 | (
130 | Line 1 of the text.
131 | Line 2 of the text. By default, a linefeed (`n) is present between lines.
132 | )", A_Desktop "\My File.txt"
133 | 
134 | ; EXAMPLE #4:
135 | FormatStr := "
136 | (
137 | Another way of using variables with a continuation section.
138 | Input value 1: {1}
139 | Input value 2: {2}
140 | )"
141 | MsgBox Format(FormatStr, A_TickCount, A_Now)
142 |

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.

143 |

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.

144 |

Quote marks are automatically escaped (i.e. they are interpreted as literal characters) if the continuation section starts inside a quoted/literal string, as in the examples except #2 above. Otherwise, quote marks act as they do normally; that is, continuation sections can contain expressions with quoted strings, as in the example #2 above.

145 |

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.

146 |

By default, trailing spaces or tabs are omitted.

147 |

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|.

148 |

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.

149 |

LTrim: Omits all spaces and tabs at the beginning of each line. This is usually unnecessary because of the default "smart" behaviour.

150 |

LTrim0 (LTrim followed by a zero): Turns off the omission of spaces and tabs from the beginning of each line.

151 |

RTrim0 (RTrim followed by a zero): Turns off the omission of spaces and tabs from the end of each line.

152 |

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.

153 |

` (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.

154 |

( 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(.

155 | 156 |

Remarks

157 |

Escape sequences such as `n (linefeed) and `t (tab) are supported inside the continuation section except when the accent (`) option has been specified.

158 |

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:

159 |
FileAppend "   ; Comment.
160 | ; Comment.
161 | ( LTrim Join    ; Comment.
162 |      ; This is not a comment; it is literal. Include the word Comments in the line above to make it a comment.
163 | )", "C:\File.txt"   ; Comment.
164 |

As a consequence of the above, semicolons never need to be escaped within a continuation section.

165 |

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.

166 |

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.

167 |

The piecemeal construction of a continuation section by means of #Include is not supported.

168 | 169 |

Script Library Folders

170 |

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:

171 |
A_ScriptDir "\Lib\"  ; Local library.
172 | A_MyDocuments "\AutoHotkey\Lib\"  ; User library.
173 | "directory-of-the-currently-running-AutoHotkey.exe\Lib\"  ; Standard library.
174 |

The library folders are searched in the order shown above.

175 |

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).

176 |

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.

177 | 178 |

Convert a Script to an EXE (Ahk2Exe)

179 |

A script compiler (courtesy of fincs, with additions by TAC109) is available as a separate automatic download.

180 |

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.

181 |

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.

182 |

Compiler Topics

183 |
    184 |
  • Running the Compiler
  • 185 |
  • Base Executable File
  • 186 |
  • Script Compiler Directives
  • 187 |
  • Compressing Compiled Scripts
  • 188 |
  • Background Information
  • 189 |
190 |

Running the Compiler

191 |

Ahk2Exe can be used in the following ways:

192 |
    193 |
  • 194 |

    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.)

    195 |
  • 196 |
  • 197 |

    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.

    198 |
  • 199 |
  • 200 |

    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.

    201 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 |
    Parameter pairMeaning
    /in script_nameThe path and name of the script to compile. This is mandatory if any other parameters are used, unless /gui is used.
    /out exe_nameThe 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.
    /icon icon_nameThe icon file to be used. Default is the last icon saved in the GUI interface, or any SetMainIcon compiler directive in the script.
    /base file_nameThe 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.
    /resourceid nameAssigns 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.
    /cp codepageOverrides 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.
    /compress nCompress the exe? 0 = no, 1 = use MPRESS if present, 2 = use UPX if present. Default is the last setting saved in the GUI interface.
    /guiShows 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.
    /silent [verbose]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.
    Deprecated:
    /ahk file_name
    The path\name of AutoHotkey.exe to be used as a utility when compiling the script.
    Deprecated:
    /mpress 0or1
    Compress the exe with MPRESS? 0 = no, 1 = yes. Default is the last setting used in the GUI interface.
    Deprecated:
    /bin file_name
    The .bin file to be used. Default is the last .bin file name saved in the GUI interface.
    260 |

    For example:

    261 |
    Ahk2Exe.exe /in "MyScript.ahk" /icon "MyIcon.ico"
    262 |
  • 263 |
264 |

Notes:

265 |
    266 |
  • Parameters containing spaces must be enclosed in double quotes.
  • 267 |
  • Compiling does not typically improve the performance of a script.
  • 268 |
  • #NoTrayIcon and A_AllowMainWindow affect the behavior of compiled scripts.
  • 269 |
  • The built-in variable A_IsCompiled contains 1 if the script is running in compiled form, otherwise 0.
  • 270 |
  • When parameters are passed to Ahk2Exe, a message indicating the success or failure of the compiling process is written to stdout. Although the message will not appear at the command prompt, it can be "caught" by means such as redirecting output to a file.
  • 271 |
  • Additionally in the case of a failure, Ahk2Exe has exit codes indicating the kind of error that occurred. These error codes can be found at GitHub (ErrorCodes.md).
  • 272 |
273 |

The compiler's source code and newer versions can be found at GitHub.

274 | 275 |

Base Executable File

276 |

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.

277 |

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.

278 | 279 |

Script Compiler Directives

280 |

Script compiler directives allow the user to specify details of how a script is to be compiled. Some of the features are:

281 |
    282 |
  • Ability to change the version information (such as the name, description, version...).
  • 283 |
  • Ability to add resources to the compiled script.
  • 284 |
  • Ability to tweak several miscellaneous aspects of compilation.
  • 285 |
  • Ability to remove code sections from the compiled script and vice versa.
  • 286 |
287 |

See Script Compiler Directives for more details.

288 | 289 |

Compressing Compiled Scripts

290 |

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.

291 |

MPRESS: archived official website (downloads and information) | direct download (95 KB)

292 |

UPX: official website (downloads and information)

293 |

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.

294 | 295 |

Background Information

296 |

The following folder structure is supported, where the running version of Ahk2Exe.exe is in the first \Compiler directory shown below:

297 |
\AutoHotkey 
298 |    AutoHotkeyA32.exe 
299 |    AutoHotkeyU32.exe
300 |    AutoHotkeyU64.exe
301 |    \Compiler
302 |       Ahk2Exe.exe  ; the master version of Ahk2Exe
303 |       ANSI 32-bit.bin
304 |       Unicode 32-bit.bin
305 |       Unicode 64-bit.bin
306 |    \AutoHotkey v2.0-a135
307 |       AutoHotkey32.exe
308 |       AutoHotkey64.exe
309 |       \Compiler
310 |    \v2.0-beta.1
311 |       AutoHotkey32.exe
312 |       AutoHotkey64.exe
313 |

The base file search algorithm runs for a short amount of time when Ahk2Exe starts, and works as follows:

314 |

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+.

315 |

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.

316 | 317 | 318 |

Passing Command Line Parameters to a Script

319 |

Scripts support command line parameters. The format is:

320 |
AutoHotkey.exe [Switches] [Script Filename] [Script Parameters]
321 |

And for compiled scripts, the format is:

322 |
CompiledScript.exe [Switches] [Script Parameters]
323 |

Switches: Zero or more of the following:

324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 354 | 355 | 356 | 357 | 358 | 363 | 364 | 365 | 366 | 367 | 371 | 372 | 373 | 374 | 375 | 378 | 379 | 380 | 381 | 382 | 389 | 390 | 391 |
SwitchMeaningWorks compiled?
/forceLaunch unconditionally, skipping any warning dialogs. This has the same effect as #SingleInstance Off.Yes
/restartIndicate 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).Yes
/ErrorStdOut

/ErrorStdOut=Encoding
339 |

Send syntax errors that prevent a script from launching to the standard error stream (stderr) rather than displaying a dialog. See #ErrorStdOut for details.

340 |

An encoding can optionally be specified. For example, /ErrorStdOut=UTF-8 encodes messages as UTF-8 before writing them to stderr.

341 |
No
/DebugConnect to a debugging client. For more details, see Interactive Debugging.No
/CPn 352 |

Overrides the default codepage used to read script files. For more details, see Script File Codepage.

353 |
No
/Validate 359 |

AutoHotkey loads the script and then exits instead of running it.

360 |

By default, load-time errors and warnings are displayed as usual. The /ErrorStdOut switch can be used to suppress or capture any error messages.

361 |

The process exit code is zero if the script successfully loaded, or non-zero if there was an error.

362 |
No
/iLib "OutFile" 368 |

Deprecated: Equivalent to /validate; use that instead.

369 |

"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.

370 |
No
/include "IncFile" 376 |

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.

377 |
No
/script 383 |

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:

384 |
CompiledScript.exe /script /ErrorStdOut MyScript.ahk "Script's arg 1"
385 |

If the current executable file does not have an embedded script, this switch is permitted but has no effect.

386 |

This switch is not supported by compiled scripts which are based on a .bin file.

387 |

See also: Base Executable File (Ahk2Exe)

388 |
N/A
392 | 393 |

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.

394 |

Specify an asterisk (*) for the filename to read the script text from standard input (stdin). This also puts the following into effect:

395 |
    396 |
  • The initial working directory is used as A_ScriptDir and to locate the local Lib folder.
  • 397 |
  • A_ScriptName and A_ScriptFullPath both contain "*".
  • 398 |
  • #SingleInstance is off by default.
  • 399 |
400 |

For an example, see ExecScript().

401 |

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.

402 |

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], '"')

403 |

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:

404 |
if A_Args.Length < 3
405 | {
406 |     MsgBox "This script requires at least 3 parameters but it only received " A_Args.Length "."
407 |     ExitApp
408 | }
409 |

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:

410 |
for n, param in A_Args  ; For each parameter:
411 | {
412 |     MsgBox "Parameter number " n " is " param "."
413 | }
414 | 
415 |

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:

416 |
for n, GivenPath in A_Args  ; For each parameter (or file dropped onto a script):
417 | {
418 |     Loop Files, GivenPath, "FD"  ; Include files and directories.
419 |         LongPath := A_LoopFileFullPath
420 |     MsgBox "The case-corrected long path name of file`n" GivenPath "`nis:`n" LongPath
421 | }
422 | 423 |

Script File Codepage

424 |

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:

425 |
    426 |
  • If the file begins with a UTF-8 or UTF-16 (LE) byte order mark, the appropriate codepage is used and the /CPn switch is ignored.
  • 427 |
  • If the /CPn switch is passed on the command-line, codepage n is used. For a list of possible values, see Code Page Identifiers.
  • 428 |
  • In all other cases, UTF-8 is used (this default differs from AutoHotkey v1).
  • 429 |
430 |

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.

431 |

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.

432 |

RegWrite may be used to set the default for scripts launched from Explorer (e.g. by double-clicking a file):

433 |
; Uncomment the appropriate line below or leave them all commented to
434 | ;   reset to the default of the current build.  Modify as necessary:
435 | ; codepage := 0        ; System default ANSI codepage
436 | ; codepage := 65001    ; UTF-8
437 | ; codepage := 1200     ; UTF-16
438 | ; codepage := 1252     ; ANSI Latin 1; Western European (Windows)
439 | if (codepage != "")
440 |     codepage := " /CP" . codepage
441 | cmd := Format('"{1}"{2} "%1" %*', A_AhkPath, codepage)
442 | key := "AutoHotkeyScript\Shell\Open\Command"
443 | if A_IsAdmin    ; Set for all users.
444 |     RegWrite cmd, "REG_SZ", "HKCR\" key
445 | else            ; Set for current user only.
446 |     RegWrite cmd, "REG_SZ", "HKCU\Software\Classes\" key
447 |

This assumes AutoHotkey has already been installed. Results may be less than ideal if it has not.

448 | 449 |

Debugging a Script

450 |

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:

451 |
ListVars
452 | Pause
453 |

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).

454 |

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.

455 |

The following functions are also useful for debugging: ListLines, KeyHistory, and OutputDebug.

456 |

Some common errors, such as typos and missing "global" declarations, can be detected by enabling warnings.

457 |

Interactive Debugging

458 |

Interactive debugging is possible with a supported DBGp client. Typically the following actions are possible:

459 |
    460 |
  • Set and remove breakpoints on lines - pause execution when a breakpoint is reached.
  • 461 |
  • Step through code line by line - step into, over or out of functions.
  • 462 |
  • Inspect all variables or a specific variable.
  • 463 |
  • View the stack of running threads and functions.
  • 464 |
465 |

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.

466 |

To enable interactive debugging, first launch a supported debugger client then launch the script with the /Debug command-line switch.

467 |
AutoHotkey.exe /Debug[=SERVER:PORT] ...
468 |

SERVER and PORT may be omitted. For example, the following are equivalent:

469 |
AutoHotkey /Debug "myscript.ahk"
470 | AutoHotkey /Debug=localhost:9000 "myscript.ahk"
471 |

To attach the debugger to a script which is already running, send it a message as shown below:

472 |
ScriptPath := "" ; SET THIS TO THE FULL PATH OF THE SCRIPT
473 | A_DetectHiddenWindows := true
474 | if WinExist(ScriptPath " ahk_class AutoHotkey")
475 |     ; Optional parameters:
476 |     ;   wParam  = the IPv4 address of the debugger client, as a 32-bit integer.
477 |     ;   lParam  = the port which the debugger client is listening on.
478 |     PostMessage DllCall("RegisterWindowMessage", "Str", "AHK_ATTACH_DEBUGGER")
479 | 
480 |

Once the debugger client is connected, it may detach without terminating the script by sending the "detach" DBGp command.

481 | 482 |

Script Showcase

483 |

See this page for some useful scripts.

484 | 485 | 486 | -------------------------------------------------------------------------------- /docs/Tutorial.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Beginner Tutorial | AutoHotkey v2 10 | 11 | 12 | 13 | 14 |

AutoHotkey Beginner Tutorial by tidbit

15 |

Table of Contents

16 |
    17 |
  1. The Basics 18 |
      19 |
    1. Downloading and installing AutoHotkey
    2. 20 |
    3. How to create a script
    4. 21 |
    5. How to find the help file on your computer
    6. 22 |
    23 |
  2. 24 |
  3. Hotkeys & Hotstrings 25 |
      26 |
    1. Keys and their mysterious symbols
    2. 27 |
    3. Window specific hotkeys/hotstrings
    4. 28 |
    5. Multiple hotkeys/hotstrings per file
    6. 29 |
    7. Examples
    8. 30 |
    31 |
  4. 32 |
  5. Sending Keystrokes 33 |
      34 |
    1. Games
    2. 35 |
    36 |
  6. 37 |
  7. Running Programs & Websites
  8. 38 |
  9. Function Calls with or without Parentheses 39 |
      40 |
    1. Code blocks
    2. 41 |
    42 |
  10. 43 |
  11. Variables 44 |
      45 |
    1. Getting user input
    2. 46 |
    3. Other Examples?
    4. 47 |
    48 |
  12. 49 |
  13. Objects 50 |
      51 |
    1. Creating Objects
    2. 52 |
    3. Using Objects
    4. 53 |
    54 |
  14. 55 |
  15. Other Helpful Goodies 56 |
      57 |
    1. The mysterious square brackets
    2. 58 |
    3. Finding your AHK version
    4. 59 |
    5. Trial and Error
    6. 60 |
    7. Indentation
    8. 61 |
    9. Asking for Help
    10. 62 |
    11. Other links
    12. 63 |
    64 |
  16. 65 |
66 | 67 |

1 - The Basics

68 |

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 |

a. Downloading and installing AutoHotkey

71 |

Since you're viewing this documentation locally, you've probably already installed AutoHotkey and can skip to section b.

72 | 76 |

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 |
    80 |
  1. Go to the AutoHotkey Homepage: https://www.autohotkey.com/
  2. 81 |
  3. Click Download. You should be presented with an option for each major version of AutoHotkey. This documentation is for v2, so choose that option or switch to the v1 documentation.
  4. 82 |
  5. The downloaded file should be named AutoHotkey_*_setup.exe or similar. Run this and click Install.
  6. 83 |
  7. Once done, great! Continue on to section b.
  8. 84 |
85 | 86 |

b. How to create a script

87 |

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 |
    91 |
  1. Right-Click on your desktop.
  2. 92 |
  3. Find "New" in the menu.
  4. 93 |
  5. Click "AutoHotkey Script" inside the "New" menu.
  6. 94 |
  7. Give the script a new name. It must end with a .ahk extension. For example: MyScript.ahk
  8. 95 |
  9. Find the newly created file on your desktop and right-click it.
  10. 96 |
  11. Click "Edit Script".
  12. 97 |
  13. A window should have popped up, probably Notepad. If so, SUCCESS! 98 |

    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 |
      107 |
    • ^j:: is the hotkey. ^ means Ctrl, j is the letter J. Anything to the left of :: are the keys you need to press.
    • 108 |
    • Send "My First Script" is how you send keystrokes. Send is the function, anything after the space inside the quotes will be typed.
    • 109 |
    • { and } marks the start and end of the hotkey.
    • 110 |
    111 |
  14. 112 |
  15. Save the File.
  16. 113 |
  17. Double-click the file/icon in the desktop to run it. Open notepad or (anything you can type in) and press Ctrl and J.
  18. 114 |
  19. Hip Hip Hooray! Your first script is done. Go get some reward snacks then return to reading the rest of this tutorial.
  20. 115 |

For a video instruction, watch Install and Hello World on YouTube.

116 | 117 |

c. How to find the help file on your computer

118 |

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 |
    123 |
  • Via the "Help" menu option in tray menu of a running script.
  • 124 |
  • Via the "Help" menu in the main window of a running script, or by pressing F1 while the main window is active.
  • 125 |
  • Via the "Help files (F1)" option in the Dash, which can be activated with the mouse or by pressing F1 while the Dash is active. The Dash can be opened via the "AutoHotkey" shortcut in the Start menu.
  • 126 |
127 | 128 |

2 - Hotkeys & Hotstrings

129 | 130 |

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 whales
137 |

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.

139 |

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 |

a. Keys and their mysterious symbols

163 |

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 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 |
SymbolDescription
#Win (Windows logo key)
!Alt
^Ctrl
+Shift
&An ampersand may be used between any two keys or mouse buttons to combine them into a custom hotkey.
190 |

(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:

193 | 194 |
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 whales
206 | 207 |

Visit Hotkeys and Hotstrings for additional hotkey and hotstring modifiers, information and examples.

208 |

b. Window specific hotkeys/hotstrings

209 | 210 |

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 |

c. Multiple hotkeys/hotstrings per file

252 |

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::America
276 |

The above code is perfectly acceptable. Multiple hotkeys, multiple hotstrings. All in one big happy script file.

277 | 278 |

d. Examples

279 |
::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 |

3 - Sending Keystrokes

292 |

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 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 |
SymbolDescription
!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.
+Sends Shift. For example, Send "+abC" would send the text "AbC", and Send "!+a" would press Alt+Shift+A.
^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.
#Sends Win (the key with the Windows logo) therefore Send "#e" would hold down Win and then press E.
317 |

The gigantic table on the Send page shows pretty much every special key built-in to AHK. For example: {Enter} and {Space}.

318 |

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:

334 |
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:

342 |
Send "{a}"       ; WRONG
343 | Send "{b}"       ; WRONG
344 | Send "{c}"       ; WRONG
345 | Send "{a}{b}{c}" ; WRONG
346 | Send "{abc}"     ; WRONG
347 | Send "abc"       ; CORRECT
348 | 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 |

a. Games

371 |

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 |

4 - Running Programs & Websites

378 |

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 |

5 - Function Calls with or without Parentheses

399 |

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 parentheses
404 |

The parameters support any kind of expression; this means for example:

405 |
    406 |
  1. You can do math in them: 407 |
    SubStr(37 * 12, 1, 2)
    408 | SubStr(A_Hour - 12, 2)
    409 |
  2. 410 |
  3. You can call another functions inside them (note that these function calls must be specified with parentheses as they are not at the start of the line): 411 |
    SubStr(A_AhkPath, InStr(A_AhkPath, "AutoHotkey"))
    412 |
  4. 413 |
  5. Text needs to be wrapped in quotes: 414 |
    SubStr("I'm scripting, awesome!", 16)
    415 |
  6. 416 |
417 | 418 |

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.

421 |

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 |

a. Code blocks

433 |

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.

434 |

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 |     ExitApp
444 |

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 |

6 - Variables

450 |

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 (:=).

452 |
453 |
Text assignment
454 |
455 |
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 |
458 |
Variable assignment
459 |
460 |
MyVar := MyVar2
461 |

Same as above, but you are assigning a value of a variable to another variable.

462 |
463 |
Number assignment
464 |
465 |
MyVar := 6 + 8 / 3 * 2 - Sqrt(9)
466 |

Thanks to expressions, you can do math!

467 |
468 |
Mixed assignment
469 |
470 |
MyVar := "The value of 5 + " MyVar2 " is: " 5 + MyVar2
471 |

A combination of the three assignments above.

472 |
473 |
474 |

Equal signs (=) with a symbol in front of it such as := += -= .= etc. are called assignment operators.

475 | 476 |

a. Getting user input

477 |

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 |

b. Other Examples?

489 |
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 |

7 - Objects

509 |

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 |
    512 |
  • You want to have a numbered list of things, such as a grocery list (this would be referred to as an indexed array)
  • 513 |
  • You want to represent a grid, perhaps for a board game (this would be done with nested objects)
  • 514 |
  • You have a list of things where each thing has a name, such as the characteristics of a fruit (this would be referred to as an associative array)
  • 515 |
516 | 517 |

a. Creating Objects

518 |

There are a few ways to create an object, and the most common ones are listed below:

519 |
520 |
Bracket syntax (Array)
521 |
522 |
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.

524 |
525 |
Brace syntax
526 |
527 |
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.

529 |
530 |
Array constructor
531 |
532 |
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 |
535 |
Map constructor
536 |
537 |
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.

539 |
540 |
Other constructor
541 |
542 |
Banana := Fruit()
543 |

Creates an object of the given class (Fruit in this case).

544 |
545 |
546 | 547 |

b. Using Objects

548 |

There are many ways to use objects, including retrieving values, setting values, adding more values, and more.

549 | 550 |

To set values

551 |
552 |
Bracket notation
553 |
554 |
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 |
558 |
Dot notation
559 |
560 |
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 |
563 |
564 | 565 |

To retrieve values

566 |
567 |
Bracket notation
568 |
569 |
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].

571 |
572 |
Dot notation
573 |
574 |
Value := Banana.Color
575 |

This example retrieves the Color property of the Banana object.

576 |
577 |
578 | 579 |

To add new keys and values

580 |
581 |
Bracket notation
582 |
583 |
MyMap["NewerKey"] := 3.1415
584 |

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 |
586 |
Dot notation
587 |
588 |
MyObject.NewProperty := "Shiny"
589 |

As mentioned above, assigning to a property that hasn't already been defined will create a new property.

590 |
591 |
InsertAt method
592 |
593 |
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 |
596 |
Push method
597 |
598 |
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 |
601 |
602 | 603 |

To remove properties and items

604 |
605 |
Delete method
606 |
607 |
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.

609 |
610 |
Pop method
611 |
612 |
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 |
615 |
RemoveAt method
616 |
617 |
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 |
621 |
622 | 623 |

8 - Other Helpful Goodies

624 |

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 |

a. The mysterious square brackets

627 |

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.

628 |

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:

637 |
Text := ControlGetText(Control, ExcludeTitle)
638 | 639 |

b. Finding your AHK version

640 |

Run this code to see your AHK version:

641 |
MsgBox A_AhkVersion
642 |

Or look for "AutoHotkey Help File" or "AutoHotkey.chm" in the start menu or your installation directory.

643 | 644 |

c. Trial and Error

645 |

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 |

d. Indentation

650 |

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 |

e. Asking for Help

692 |

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 |
    694 |
  • Don't be afraid to ask for help, even the smartest people ask others for help.
  • 695 |
  • Don't be afraid to show what you tried, even if you think it's silly.
  • 696 |
  • Post anything you have tried.
  • 697 |
  • Pretend everyone but you is a doorknob and knows nothing. Give as much information as you can to educate us doorknobs at what you are trying to do. Help us help you.
  • 698 |
  • Be patient.
  • 699 |
  • Be polite.
  • 700 |
  • Be open.
  • 701 |
  • Be kind.
  • 702 |
  • Enjoy!
  • 703 |
704 |

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 |

f. Other links

708 |

Frequently Asked Questions (FAQ)

709 | 710 | 711 | -------------------------------------------------------------------------------- /docs/Variables.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Variables and Expressions - Definition & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Variables and Expressions

14 | 15 |

Table of Contents

16 |
    17 |
  • Variables
  • 18 |
  • Expressions
  • 19 |
  • Operators in Expressions
  • 20 |
  • Built-in Variables
  • 21 |
  • Variable Capacity and Memory
  • 22 |
23 |

Variables

24 |

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 := Var
29 |

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, &y
33 |

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 |

Expressions

44 |

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 single or 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.

53 |

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.

56 |

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 FoundIt
58 |

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.

59 |

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 := true
62 |

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).

64 |

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:

65 |
MsgBox(0x7F)  ; Shows 128
  66 | MsgBox(1.00)  ; Shows 1.0
67 | 68 |

Operators in Expressions

69 |

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 |

Expression Operators (in descending precedence order)

73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 103 | 104 | 105 | 107 | 111 | 112 | 113 | 114 | 119 | 120 | 121 | 125 | 133 | 134 | 135 | 139 | 145 | 146 | 147 | 149 | 152 | 153 | 154 | 157 | 168 | 169 | 170 | 174 | 183 | 184 | 185 | 186 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 204 | 207 | 208 | 209 | 213 | 218 | 219 | 220 | 221 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 233 | 242 | 243 | 244 | 246 | 255 | 256 | 257 | 258 | 264 | 265 | 266 | 267 | 272 | 273 | 274 | 288 | 295 | 296 | 297 | 298 | 313 | 314 | 315 | 316 | 317 | 321 | 322 |
OperatorDescription
%Expr% 81 |

Dereference or name substitution.

82 |

When Expr evaluates to a VarRef, %Expr% accesses the corresponding variable. For example, x := &y takes a reference to y and assigns it to x, then %x% := 1 assigns to the variable y and %x% reads its value.

83 |

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: %'novar'% ?? 42.

88 |

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 |
x.y
x.%z%
Member access. Get, set or call a property of object x, where y is a literal name and z is an expression which evaluates to a name. See object syntax for more details.
var? 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 may be passed conditionally via the ternary operator or on the right-hand side of AND/OR.

99 |

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 unset keyword.

101 |

See also: unset (Optional Parameters)

102 |
++
106 | --
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, Var := ++X increments X and then assigns its value to Var. Conversely, if the operator appears after the variable's name, the result is the value of X prior to performing the operation. For example, Var := X++ increments X but Var receives the value X had before it was incremented.

109 |

These operators can also be used with a property of an object, such as myArray.Length++ or --myArray[i]. In these cases, the result of the sub-expression is always a number, not a variable reference.

110 |
** 115 |

Power. Example usage: Base**Exponent. Both Base and Exponent may contain a decimal point. If Exponent is negative, the result will be formatted as a floating point number even if Base and Exponent are both integers. Since ** is of higher precedence than unary minus, -2**2 is evaluated like -(2**2) and so yields -4. Thus, to raise a literal negative number to a power, enclose it in parentheses such as (-2)**2.

116 |

The power operator is right-associative. For example, x ** y ** z is evaluated as x ** (y ** z).

117 |

Note: A negative Base combined with a fractional Exponent such as (-2)**0.5 is not supported; attempting it will cause an exception to be thrown. But both (-2)**2 and (-2)**2.0 are supported. If both Base and Exponent are 0, the result is undefined and an exception is thrown.

118 |
-
122 | !
123 | ~
124 | &
126 |

Unary minus (-): Inverts the sign of its operand.

127 |

Unary plus (+): +N is equivalent to -(-N). This has no effect when applied to a pure number, but can be used to convert numeric strings to pure numbers.

128 |

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: !x or !(y and z). Note: The word NOT is synonymous with ! except that ! has a higher precedence. Consecutive unary operators such as !!Var are allowed because they are evaluated in right-to-left order.

129 |

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, ~0xf0f evaluates to -0xf10 (-3856), which is binary equivalent to 0xfffffffffffff0f0. If an unsigned 32-bit value is intended, the result can be truncated with result & 0xffffffff. If the operand is a floating point value, a TypeError is thrown.

130 |

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, ref := &target followed by %ref% := 1 would assign the value 1 to target. The VarRef would typically be passed to a function, but could be stored in an array or property. See also: Dereference, ByRef.

131 |

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 |
*
136 | /
137 | // 138 |

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, 3/2 yields 1.5 rather than 1, and 4/2 yields 2.0 rather than 2.

142 |

Integer divide (//): The double-slash operator uses high-performance integer division. For example, 5//3 is 1 and 5//-3 is -1. If either of the inputs is in floating point format, a TypeError is thrown. For modulo, see Mod.

143 |

The *= and /= operators are a shorthand way to multiply or divide the value in a variable by another value. For example, Var*=2 produces the same result as Var:=Var*2 (though the former performs better).

144 |

Division by zero causes a ZeroDivisionError to be thrown.

+
148 | -

Add (+) and subtract (-). On a related note, the += and -= operators are a shorthand way to increment or decrement a variable. For example, Var+=2 produces the same result as Var:=Var+2 (though the former performs better). Similarly, a variable can be increased or decreased by 1 by using Var++, Var--, ++Var, or --Var.

150 |

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 |
<<
155 | >>
156 | >>>
158 |

Bit shift left (<<). Example usage: Value1 << Value2. This is equivalent to multiplying Value1 by "2 to the Value2th power".

159 |

Arithmetic bit shift right (>>). Example usage: Value1 >> Value2. This is equivalent to dividing Value1 by "2 to the Value2th power" and rounding the result to the nearest integer leftward on the number line; for example, -3>>1 is -2.

160 |

Logical bit shift right (>>>). Example usage: Value1 >>> Value2. Unlike arithmetic bit shift right, this does not preserve the sign of the number. For example, -1 has the same bit representation as the unsigned 64-bit integer 0xffffffffffffffff, therefore -1 >>> 1 is 0x7fffffffffffffff.

161 |

The following applies to all three operators:

162 |
    163 |
  • If either of the inputs is a floating-point number, a TypeError is thrown.
  • 164 |
  • A 64-bit operation is performed and the result is a 64-bit signed integer.
  • 165 |
  • If Value2 is less than 0 or greater than 63, an exception is thrown.
  • 166 |
167 |
&
171 | ^
172 | | 173 |
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 |
    178 |
  • If either of the inputs is a floating-point number, a TypeError is thrown.
  • 179 |
  • A 64-bit operation is performed and the result is a 64-bit signed integer.
  • 180 |
181 |

Related: Bitwise-not (~)

182 |
. 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 x -y, or when the item on the right side has a leading ++ or --). When the dot is omitted, there must be at least one space or tab between the items to be merged.

188 |
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: Var := "The net price is " . Price * (1 - Discount/100).

192 |

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, Chr(0x2010) Chr(0x0000) Chr(0x4030) produces the following string of bytes (due to UTF-16-LE encoding): 0x10, 0x20, 0, 0, 0x30, 0x40. The result has an additional null-terminator (binary zero) which is not included in the length.

194 |

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, 1.1 and (.5) are numbers, A_Args.Has(3) is a method call and A_Args.Length is a property access.

195 |
~=Shorthand for RegExMatch. For example, the result of "abc123" ~= "\d" is 4 (the position of the first numeric character).
>   <
203 | >= <=
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 |
=
210 | ==
211 | !=
212 | !==
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 |
IS
IN
CONTAINS
222 |

Value is Class yields 1 (true) if Value is an instance of Class, otherwise 0 (false). Class must be an Object with an own Prototype property, but typically the property is defined implicitly by a class definition. This operation is generally equivalent to HasBase(Value, Class.Prototype).

223 |

in and contains are reserved for future use.

224 |
NOTLogical-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).
AND
232 | &&

Both of these are logical-AND. For example: x > 3 and x < 10.

234 |

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 AND or && (or any other operator) is automatically appended to the line above it.

OR
245 | ||

Both of these are logical-OR. For example: x <= 3 or x >= 10.

247 |

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 OR or || (or any other operator) is automatically appended to the line above it.

?? 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, A ?? B behaves like A || B (logical-OR) except that the condition is IsSet(A).

260 |

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 IsSet(A) ? A : B, a VarUnset warning may still be shown at load-time if there are other references to the variable but no assignments.

263 |
?: 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, var := x>y ? 2 : 3 stores 2 in Var if x is greater than y; otherwise it stores 3. To enhance performance, only the winning branch is evaluated (see short-circuit evaluation).

269 |

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 |
:=
275 | +=
276 | -=
277 | *=
278 | /=
279 | //=
280 | .=
281 | |=
282 | &=
283 | ^=
284 | >>=
285 | <<=
286 | >>>= 287 |

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, Var //= 2 performs integer division to divide Var by 2, then stores the result back in Var. Similarly, Var .= "abc" is a shorthand way of writing Var := Var . "abc".

289 |

Unlike most other operators, assignments are evaluated from right to left. Consequently, a line such as Var1 := Var2 := 0 first assigns 0 to Var2 then assigns Var2 to Var1.

290 |

If an assignment is used as the input for some other operator, its value is the variable itself. For example, the expression (Var+=2) > 50 is true if the newly-increased value in Var is greater than 50. It is also valid to combine an assignment with the reference operator, as in &(Var := "initial value").

291 |

The precedence of the assignment operators is automatically raised when it would avoid a syntax error or provide more intuitive behavior. For example: not x:=y is evaluated as not (x:=y). Also, x==y && z:=1 is evaluated as x==y && (z:=1), which short-circuits when x doesn't equal y. Similarly, ++Var := X is evaluated as ++(Var := X); and Z>0 ? X:=2 : Y:=2 is evaluated as Z>0 ? (X:=2) : (Y:=2).

292 |

The target 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?).

293 |

An assignment can also target a property of an object, such as myArray.Length += n or myArray[i] .= t. When assigning to a property, the result of the sub-expression is the value being assigned, not a variable reference.

294 |
() => expr 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 + b
302 |
Sum(a, b) {
 303 |     return a + b
 304 | }
 305 | sumfn := Sum
306 |

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 a and stores its reference in the variable double:

308 |
double := a => a * 2
309 |

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 |
,

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: x:=1, y+=2, ++index, MyFunc(). Such statements are executed in order from left to right.

318 |

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, MyFn((x, y)) evaluates both x and y but passes y as the first and only parameter of MyFn.

320 |
323 |

The following types of sub-expressions override precedence/order of evaluation:

324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 335 | 336 | 337 | 340 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 365 | 366 | 367 | 368 | 372 | 373 |
ExpressionDescription
(expression) 332 |

Any sub-expression enclosed in parentheses. For example, (3 + 2) * 2 forces 3 + 2 to be evaluated first.

333 |

For a multi-statement expression, the result of the last statement is returned. For example, (a := 1, b := 2, c := 3) returns 3.

334 |

Mod()
338 | Round()
339 | Abs()

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, (x.y)() retrieves a function from a property and then calls it with no parameters, whereas x.y() would implicitly pass x as the first parameter.

342 |

(expression)()

x.y()

350 |

Method call. The target object x is an expression, while y is a literal property name. There must be no space on either side of the method name, but the dot can be preceded by whitespace, including line breaks.

351 |

The object x is implicitly passed as the first parameter of the method's function. This normally corresponds to this and should not be explicitly defined in a method definition, but any other type of function definition must account for it in the parameter list.

352 |
Fn(Params*)

Variadic function call. Params is an enumerable object (an object with an __Enum method), such as an Array containing parameter values.

x[y]
[a, b, c]
361 |

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, x[y] := z.

362 |

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, [a, b, c] is equivalent to Array(a, b, c) (a, b and c are variables).

363 |

See Arrays and Maps for common usage.

364 |
{a: b, c: d} 369 |

Object literal. Create an Object. Each pair consists of a literal property name a and a property value expression b. For example, x := {a: b} is equivalent to x := Object(), x.a := b. Base may be set within the object literal, but all other properties are set as own value properties, potentially overriding properties inherited from the base object.

370 |

To use a dynamic property name, enclose the sub-expression in percent signs. For example: {%nameVar%: valueVar}.

371 |
374 | 375 |

Built-in Variables

376 |

The variables below are built into the program and can be referenced by any script.

377 |

See Built-in Variables for general information.

378 |

Table of Contents

379 |
    380 |
  • Special Characters: A_Space, A_Tab
  • 381 |
  • Script Properties: command line parameters, A_WorkingDir, A_ScriptDir, A_ScriptName, (...more...)
  • 382 |
  • Date and Time: A_YYYY, A_MM, A_DD, A_Hour, A_Min, A_Sec, (...more...)
  • 383 |
  • Script Settings: A_IsSuspended, A_ListLines, A_TitleMatchMode, (...more...)
  • 384 |
  • User Idle Time: A_TimeIdle, A_TimeIdlePhysical, A_TimeIdleKeyboard, A_TimeIdleMouse
  • 385 |
  • Hotkeys, Hotstrings, and Custom Menu Items: A_ThisHotkey, A_EndChar, (...more...)
  • 386 |
  • Operating System and User Info: A_OSVersion, A_ScreenWidth, A_ScreenHeight, (...more...)
  • 387 |
  • Misc: A_Clipboard, A_Cursor, A_EventInfo, (...more...)
  • 388 |
  • Loop: A_Index, (...more...)
  • 389 |
390 |

Special Characters

391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 |
VariableDescription
A_SpaceContains a single space character.
A_TabContains a single tab character.
405 |

Script Properties

406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 430 | 431 | 432 | 433 | 438 | 439 | 440 | 441 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 455 | 456 | 457 | 458 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | 474 | 481 | 482 | 483 | 484 | 485 | 486 |
VariableDescription
A_ArgsContains an array of command line parameters. For details, see Passing Command Line Parameters to a Script.
A_WorkingDir

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.

418 |

SetWorkingDir can also be used to change the working directory.

419 |

The script's working directory defaults to A_ScriptDir, regardless of how the script was launched.

A_InitialWorkingDirThe 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.
A_ScriptDir 428 |

The full path of the directory where the current script is located. The final backslash is omitted (even for root directories).

429 |

If the script text is read from stdin rather than from file, this variable contains the initial working directory.

A_ScriptName 434 |

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.

435 |

If the script text is read from stdin rather than from file, this variable contains an asterisk (*).

436 |

If the script is compiled or embedded, this is the name of the current executable file.

437 |
A_ScriptFullPath 442 |

The full path of the current script, e.g. C:\Scripts\My Script.ahk

443 |

If the script text is read from stdin rather than from file, this variable contains an asterisk (*).

444 |

If the script is compiled or embedded, this is the full path of the current executable file.

445 |
A_ScriptHwndThe unique ID (HWND/handle) of the script's hidden main window.
A_LineNumber

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: MsgBox "Could not write to log file (line number " A_LineNumber ")".

454 |

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.

A_LineFile 459 |

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.

460 |

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.

461 |

If the script is embedded, A_LineFile contains an asterisk (*) followed by the resource name; e.g. *#1

462 |
A_ThisFuncThe name of the user-defined function that is currently executing (blank if none); for example: MyFunction. See also: Name property (Func)
A_AhkVersionContains 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
A_AhkPath 475 |

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

476 |

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:

477 |
InstallDir := RegRead("HKLM\SOFTWARE\AutoHotkey", "InstallDir", "")
 478 | AhkPath := InstallDir ? InstallDir "\AutoHotkey.exe" : ""
479 |

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.

480 |
A_IsCompiledContains 1 if the script is running as a compiled EXE and 0 (which is considered false) if it is not.
487 |

Date and Time

488 | 489 | 490 | 491 | 492 | 493 | 494 | 495 | 499 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 | 520 | 521 | 522 | 523 | 524 | 525 | 526 | 527 | 528 | 529 | 530 | 531 | 532 | 533 | 534 | 535 | 536 | 537 | 538 | 539 | 540 | 541 | 542 | 543 | 544 | 545 | 546 | 547 | 548 | 549 | 550 | 551 | 552 | 553 | 554 | 558 | 559 | 560 | 561 | 562 | 563 | 564 | 565 | 572 | 573 |
VariableDescription
A_YYYY 496 |

Current 4-digit year (e.g. 2004). Synonymous with A_Year.

497 |

Note: To retrieve a formatted time or date appropriate for your locale and language, use FormatTime() (time and long date) or FormatTime(, "LongDate") (retrieves long-format date).

498 |
A_MMCurrent 2-digit month (01-12). Synonymous with A_Mon.
A_DDCurrent 2-digit day of the month (01-31). Synonymous with A_MDay.
A_MMMMCurrent month's full name in the current user's language, e.g. July
A_MMMCurrent month's abbreviation in the current user's language, e.g. Jul
A_DDDDCurrent day of the week's full name in the current user's language, e.g. Sunday
A_DDDCurrent day of the week's abbreviation in the current user's language, e.g. Sun
A_WDayCurrent 1-digit day of the week (1-7). 1 is Sunday in all locales.
A_YDayCurrent 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").
A_YWeekCurrent 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.
A_HourCurrent 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")
A_Min

Current 2-digit minute (00-59).

A_SecCurrent 2-digit second (00-59).
A_MSecCurrent 3-digit millisecond (000-999). To remove the leading zeros, follow this example: Milliseconds := A_MSec + 0.
A_Now 555 |

The current local time in YYYYMMDDHH24MISS format.

556 |

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.

557 |
A_NowUTCThe current Coordinated Universal Time (UTC) in YYYYMMDDHH24MISS format. UTC is essentially the same as Greenwich Mean Time (GMT).
A_TickCount

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:

566 |
StartTime := A_TickCount
 567 | Sleep 1000
 568 | ElapsedTime := A_TickCount - StartTime
 569 | MsgBox ElapsedTime " milliseconds have elapsed."
570 |

If you need more precision than A_TickCount's 10 ms, use QueryPerformanceCounter().

571 |
574 |

Script Settings

575 | 576 | 577 | 578 | 579 | 580 | 581 | 582 | 583 | 584 | 585 | 586 | 587 | 588 | 589 | 590 | 591 | 592 | 593 | 594 | 595 | 596 | 597 | 598 | 599 | 600 | 601 | 602 | 603 | 604 | 605 | 606 | 607 | 608 | 609 | 610 | 611 | 612 | 613 | 614 | 615 | 616 | 617 | 618 | 619 | 620 | 621 | 622 | 623 | 624 | 625 | 626 | 627 | 628 | 629 | 631 | 632 | 633 | 634 | 636 | 637 | 638 | 639 | 640 | 641 | 642 | 643 | 644 | 645 | 646 | 647 | 648 | 649 | 650 | 651 | 653 | 654 | 655 | 656 | 657 | 658 | 659 | 660 | 665 | 666 | 667 | 668 | 669 | 670 | 671 | 672 | 673 | 674 | 675 | 676 | 677 | 681 | 682 | 683 | 684 | 685 | 686 | 687 | 688 | 691 | 692 | 693 | 694 | 695 | 696 | 697 | 698 | 699 | 700 |
VariableDescription
A_IsSuspendedContains 1 if the script is suspended, otherwise 0.
A_IsPausedContains 1 if the thread immediately underneath the current thread is paused, otherwise 0.
A_IsCriticalContains 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.
A_ListLinesCan be used to get or set whether to log lines. Possible values are 0 (disabled) and 1 (enabled). For details, see ListLines.
A_TitleMatchModeCan be used to get or set the title match mode. Possible values are 1, 2, 3, and RegEx. For details, see SetTitleMatchMode.
A_TitleMatchModeSpeedCan be used to get or set the title match speed. Possible values are Fast and Slow. For details, see SetTitleMatchMode.
A_DetectHiddenWindowsCan be used to get or set whether to detect hidden windows. Possible values are 0 (disabled) and 1 (enabled). For details, see DetectHiddenWindows.
A_DetectHiddenTextCan 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.
A_FileEncodingCan be used to get or set the default encoding for various built-in functions. For details, see FileEncoding.
A_SendModeCan be used to get or set the send mode. Possible values are Event, Input, Play, and InputThenPlay. For details, see SendMode.
A_SendLevelCan be used to get or set the send level, an integer from 0 to 100. For details, see SendLevel.
A_StoreCapsLockModeCan 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.
A_KeyDelay
630 | A_KeyDuration
Can be used to get or set the delay or duration for keystrokes, in milliseconds. For details, see SetKeyDelay.
A_KeyDelayPlay
635 | A_KeyDurationPlay
Can be used to get or set the delay or duration for keystrokes sent via SendPlay mode, in milliseconds. For details, see SetKeyDelay.
A_WinDelayCan be used to get or set the delay for windowing functions, in milliseconds. For details, see SetWinDelay.
A_ControlDelayCan be used to get or set the delay for control-modifying functions, in milliseconds. For details, see SetControlDelay.
A_MenuMaskKeyControls which key is used to mask Win or Alt keyup events. For details, see A_MenuMaskKey.
A_MouseDelay
652 | A_MouseDelayPlay
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.
A_DefaultMouseSpeedCan be used to get or set the default mouse speed, an integer from 0 (fastest) to 100 (slowest). For details, see SetDefaultMouseSpeed.
A_CoordModeToolTip
661 | A_CoordModePixel
662 | A_CoordModeMouse
663 | A_CoordModeCaret
664 | A_CoordModeMenu
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.
A_RegViewCan be used to get or set the registry view. Possible values are 32, 64 and Default. For details, see SetRegView.
A_TrayMenu

Returns a Menu object which can be used to modify or display the tray menu.

A_AllowMainWindow

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).

678 |

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.

679 |

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.

680 |

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.

A_IconHiddenCan be used to get or set whether to hide the tray icon. Possible values are 0 (visible) and 1 (hidden). For details, see #NoTrayIcon.
A_IconTip

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.

689 |

To create a multi-line tooltip, use the linefeed character (`n) in between each line, e.g. "Line1`nLine2". Only the first 127 characters are displayed, and the text is truncated at the first tab character, if present.

690 |

On Windows 10 and earlier, to display tooltip text containing ampersands (&), escape each ampersand with two additional ampersands. For example, assigning "A &&& B" would display "A & B" in the tooltip.

A_IconFileBlank 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.
A_IconNumberBlank if A_IconFile is blank. Otherwise, it's the number of the icon in A_IconFile (typically 1).
701 |

User Idle Time

702 | 703 | 704 | 705 | 706 | 707 | 708 | 709 | 714 | 715 | 716 | 717 | 718 | 719 | 720 | 721 | 722 | 723 | 724 | 725 | 726 | 727 |
VariableDescription
A_TimeIdle 710 |

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:

711 |
if A_TimeIdle > 600000
 712 |     MsgBox "Last activity was 10 minutes ago"
713 |
A_TimeIdlePhysicalSimilar 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).
A_TimeIdleKeyboardIf 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.
A_TimeIdleMouseIf 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.
728 |

Hotkeys, Hotstrings, and Custom Menu Items

729 | 730 | 731 | 732 | 733 | 734 | 735 | 736 | 740 | 741 | 742 | 743 | 744 | 745 | 746 | 747 | 748 | 749 | 750 | 751 | 752 | 753 | 754 | 755 | 756 | 757 | 758 | 759 | 760 | 761 | 762 | 763 | 764 | 765 | 766 | 767 | 768 | 769 | 770 | 771 | 772 | 773 |
VariableDescription
A_ThisHotkey

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.

737 |

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.

738 |

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.

739 |
A_PriorHotkeySame as above except for the previous hotkey. It will be blank if none.
A_PriorKeyThe 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.
A_TimeSinceThisHotkeyThe number of milliseconds that have elapsed since A_ThisHotkey was pressed. It will be blank whenever A_ThisHotkey is blank.
A_TimeSincePriorHotkeyThe number of milliseconds that have elapsed since A_PriorHotkey was pressed. It will be blank whenever A_PriorHotkey is blank.
A_EndCharThe 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.
A_MaxHotkeysPerIntervalCan 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.
A_HotkeyIntervalCan be used to get or set the length of the interval used by A_MaxHotkeysPerInterval, in milliseconds.
A_HotkeyModifierTimeoutCan 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.
774 |

Operating System and User Info

775 | 776 | 777 | 778 | 779 | 780 | 781 | 782 | 785 | 786 | 787 | 788 | 791 | 792 | 793 | 794 | 798 | 799 | 800 | 801 | 802 | 803 | 804 | 805 | 806 | 807 | 808 | 809 | 810 | 811 | 812 | 813 | 814 | 815 | 816 | 817 | 818 | 819 | 820 | 821 | 822 | 823 | 824 | 825 | 834 | 835 | 836 | 837 | 841 | 842 | 843 | 844 | 848 | 849 | 850 | 851 | 855 | 856 | 857 | 858 | 862 | 863 | 864 | 865 | 869 | 870 | 871 | 872 | 876 | 877 | 878 | 879 | 883 | 884 | 885 | 886 | 890 | 891 | 892 | 893 | 897 | 898 | 899 | 900 | 904 | 905 | 906 | 907 | 911 | 912 | 913 | 914 | 917 | 918 | 919 | 921 | 929 | 930 | 931 | 932 | 934 | 935 |
VariableDescription
A_ComSpec

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:

783 |
C:\Windows\system32\cmd.exe
784 |
A_Temp

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:

789 |
C:\Users\<UserName>\AppData\Local\Temp
790 |
A_OSVersion 795 |

The version number of the operating system, in the format "major.minor.build". For example, Windows 7 SP1 is 6.1.7601.

796 |

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.

797 |
A_Is64bitOSContains 1 (true) if the OS is 64-bit or 0 (false) if it is 32-bit.
A_PtrSizeContains 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.
A_LanguageThe system's default language, which is one of these 4-digit codes.
A_ComputerNameThe name of the computer as seen on the network.
A_UserNameThe logon name of the user who launched this script.
A_WinDirThe Windows directory. For example: C:\Windows
A_ProgramFiles 826 |

The Program Files directory (e.g. C:\Program Files or C:\Program Files (x86)). This is usually the same as the ProgramFiles environment variable.

827 |

On 64-bit systems (and not 32-bit systems), the following applies:

828 |
    829 |
  • If the executable (EXE) that is running the script is 32-bit, A_ProgramFiles returns the path of the "Program Files (x86)" directory.
  • 830 |
  • For 32-bit processes, the ProgramW6432 environment variable contains the path of the 64-bit Program Files directory. On Windows 7 and later, it is also set for 64-bit processes.
  • 831 |
  • The ProgramFiles(x86) environment variable contains the path of the 32-bit Program Files directory.
  • 832 |
833 |
A_AppData 838 |

The full path and name of the folder containing the current user's application-specific data. For example:

839 |
C:\Users\<UserName>\AppData\Roaming
840 |
A_AppDataCommon 845 |

The full path and name of the folder containing the all-users application-specific data. For example:

846 |
C:\ProgramData
847 |
A_Desktop 852 |

The full path and name of the folder containing the current user's desktop files. For example:

853 |
C:\Users\<UserName>\Desktop
854 |
A_DesktopCommon 859 |

The full path and name of the folder containing the all-users desktop files. For example:

860 |
C:\Users\Public\Desktop
861 |
A_StartMenu 866 |

The full path and name of the current user's Start Menu folder. For example:

867 |
C:\Users\<UserName>\AppData\Roaming\Microsoft\Windows\Start Menu
868 |
A_StartMenuCommon 873 |

The full path and name of the all-users Start Menu folder. For example:

874 |
C:\ProgramData\Microsoft\Windows\Start Menu
875 |
A_Programs 880 |

The full path and name of the Programs folder in the current user's Start Menu. For example:

881 |
C:\Users\<UserName>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
882 |
A_ProgramsCommon 887 |

The full path and name of the Programs folder in the all-users Start Menu. For example:

888 |
C:\ProgramData\Microsoft\Windows\Start Menu\Programs
889 |
A_Startup 894 |

The full path and name of the Startup folder in the current user's Start Menu. For example:

895 |
C:\Users\<UserName>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
896 |
A_StartupCommon 901 |

The full path and name of the Startup folder in the all-users Start Menu. For example:

902 |
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
903 |
A_MyDocuments 908 |

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 M: rather than M:\). For example:

909 |
C:\Users\<UserName>\Documents
910 |
A_IsAdmin

Contains 1 if the current user has admin rights, otherwise 0.

915 |

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.

916 |

A_ScreenWidth
920 | A_ScreenHeight

The width and height of the primary monitor, in pixels (e.g. 1024 and 768).

922 |

To discover the dimensions of other monitors in a multi-monitor system, use SysGet.

923 |

To instead discover the width and height of the entire desktop (even if it spans multiple monitors), use the following example:

924 |
 925 | VirtualWidth := SysGet(78)
 926 | VirtualHeight := SysGet(79)
 927 | 
928 |

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.

A_ScreenDPI

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.

933 |

See also DPI Scaling and the GUI's -DPIScale option.

936 |

Misc.

937 | 938 | 939 | 940 | 941 | 942 | 943 | 944 | 945 | 946 | 947 | 948 | 949 | 950 | 951 | 952 | 960 | 961 | 962 | 963 | 965 | 966 | 967 | 968 | 971 | 972 |
VariableDescription
A_ClipboardCan be used to get or set the contents of the OS's clipboard. For details, see A_Clipboard.
A_Cursor

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.

A_EventInfo

Contains additional information about the following events:

953 |
    954 |
  • Mouse wheel hotkeys (WheelDown/Up/Left/Right)
  • 955 |
  • OnMessage
  • 956 |
  • Regular Expression Callouts
  • 957 |
958 |

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.

959 |

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).

A_LastError

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.

964 |

Assigning a value to A_LastError also causes the OS's SetLastError() function to be called.

True
False

Contain 1 and 0. They can be used to make a script more readable. For details, see Boolean Values.

969 |

These are actually keywords, not variables.

970 |
973 |

Loop

974 | 975 | 976 | 977 | 978 | 979 | 980 | 981 | 982 | 983 | 984 | 985 | 986 | 987 | 988 | 989 | 990 | 991 | 992 | 993 | 994 | 995 | 996 | 997 | 998 | 999 |
VariableDescription
A_IndexCan 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.
A_LoopFileName, etc.This and other related variables are valid only inside a file loop.
A_LoopRegName, etc.This and other related variables are valid only inside a registry loop.
A_LoopReadLineSee file-reading loop.
A_LoopFieldSee parsing loop.
1000 | 1001 |

Variable Capacity and Memory

1002 |
    1003 |
  • When a variable is given a new string longer than its current contents, additional system memory is allocated automatically.
  • 1004 |
  • The memory occupied by a large variable can be freed by setting it equal to nothing, e.g. var := "".
  • 1005 |
  • There is no limit to how many variables a script may create. The program is designed to support at least several million variables without a significant drop in performance.
  • 1006 |
  • Functions and expressions that accept numeric inputs generally support 15 digits of precision for floating point values. For integers, 64-bit signed values are supported, which range from -9223372036854775808 (-0x8000000000000000) to 9223372036854775807 (0x7FFFFFFFFFFFFFFF). Any integer constants outside this range wrap around. Similarly, arithmetic operations on integers wrap around upon overflow (e.g. 0x7FFFFFFFFFFFFFFF + 1 = -0x8000000000000000).
  • 1007 |
1008 | 1009 | 1010 | -------------------------------------------------------------------------------- /docs/howto/Install.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | How to Install AutoHotkey | AutoHotkey v2 9 | 10 | 11 | 12 | 13 |

How to Install AutoHotkey

14 | 15 |

If you have not already downloaded AutoHotkey, you can get it from one of the following locations:

16 |
    17 |
  • https://www.autohotkey.com/ - multiple options are presented when you click Download.
  • 18 |
  • https://www.autohotkey.com/download/ - the main download links are for the current exe installer, but there are also links to the current zip package and archive of older versions.
  • 19 |
20 |

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.

22 |

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.

25 |

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 |

Next Steps

30 |

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 |
    35 |
  • How to Run Programs
  • 36 |
  • How to Write Hotkeys
  • 37 |
  • How to Send Keystrokes
  • 38 |
39 |

AutoHotkey Beginner Tutorial by tidbit covers a range of topics.

40 | 41 |

Problems?

42 |

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 |

Zip Installer

45 |

AutoHotkey can also be installed from the zip download.

46 |
    47 |
  1. Open the zip file using File Explorer (no extraction necessary), or extract the contents of the zip file to a temporary directory.
  2. 48 |
  3. Run Install.cmd.
  4. 49 |
  5. If you receive a prompt like "The publisher could not be verified. Are you sure...?", click Run.
  6. 50 |
  7. Continue installation as described above.
  8. 51 |
52 | 53 |

Security Prompts

54 |

You may receive one or more security prompts, depending on several factors.

55 | 56 |

Web Browsers

57 |

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 |

SmartScreen

63 |

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 |

Antivirus

67 |

If your antivirus flags the download as malicious, please refer to the following:

68 |
    69 |
  • FAQ: My antivirus program flagged AutoHotkey or a compiled script as malware. Is it really a virus?
  • 70 |
  • Report False-Positives To Anti-Virus Companies
  • 71 |
  • Antivirus False Positives
  • 72 |
73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /docs/howto/ManageWindows.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | How to Manage Windows | AutoHotkey v2 9 | 10 | 11 | 12 | 13 |

How to Manage Windows

14 |

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.

22 |

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 |
    24 |
  • The title is repeated unnecessarily.
  • 25 |
  • The title is correct only for systems with UI language set to English.
  • 26 |
  • It might move an existing untitled Notepad window instead of the new one.
  • 27 |
  • If for some reason no matching window appears, the script will stall indefinitely.
  • 28 |
29 |

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 |

Title Matching

33 |

There are a few things to know when specifying a window by title:

34 |
    35 |
  • Window titles are always case-sensitive, except when using the RegEx matching mode with the i) modifier.
  • 36 |
  • By default, functions expect a substring of the window title. For example, "Notepad" could match both "Untitled - Notepad" and "C:\A\B.ahk - Notepad++". SetTitleMatchMode can be used to make functions expect a prefix, exact match, or RegEx pattern instead.
  • 37 |
  • By default, hidden windows are ignored (except by WinShow). DetectHiddenWindows can be used to change this.
  • 38 |
39 |

See Matching Behaviour for more details.

40 | 41 |

Active Window

42 |

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 |

Last Found Window

46 |

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/2
51 |

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 |

Window Class

54 |

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/2
60 |

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".

61 |

Related: ahk_class

62 | 63 |

Process Name/Path

64 |

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/2
69 |

Related: ahk_exe

70 | 71 |

Process ID (PID)

72 |

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",,, &notepad_pid
 74 | WinWait "ahk_pid " notepad_pid
 75 | WinActivate
 76 | WinMove 0, 0, A_ScreenWidth/4, A_ScreenHeight/2
77 |

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.

79 |

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.

81 |

Related: ahk_pid

82 | 83 |

Window ID (HWND)

84 |

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_id
90 |

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.

93 |

Related: ahk_id

94 | 95 |

Timeout

96 |

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",,, &notepad_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.

108 |

Another way to write it is to return early (in other words, abort) if the wait times out. For example:

109 |
Run "notepad.exe",,, &notepad_pid
110 | if !WinWait("ahk_pid " notepad_pid,, 5)
111 |     return
112 | WinActivate
113 | WinMove 0, 0, A_ScreenWidth/4, A_ScreenHeight/2
114 |

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.

115 |

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",,, &notepad_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",,, &notepad_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.

131 | 132 |

Expressions (Math etc.)

133 |

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 &current_x, &current_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.

145 |

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 | How to Run Example Code | AutoHotkey v2 9 | 10 | 11 | 12 | 13 |

How to Run Example Code

14 |

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 |
    19 |
  1. Download the code as a file. 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.
  2. 20 |
  3. Copy the code into a file. It's usually best to create a new file, so existing code won't interfere with the example code. Once the file has been created, open it for editing and copy-paste the code.
  4. 21 |
22 |

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 |

Assigning Hotkeys

25 |

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 |

Bailing Out

33 |

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.

34 |

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 |

Reloading

38 |

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 |

The Right Tools

41 |

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 |
    43 |
  • The ability to run the script with a keyboard shortcut (such as F5).
  • 44 |
  • Syntax highlighting to make the code easier to read (and write).
  • 45 |
46 |

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 | How to Run Programs | AutoHotkey v2 9 | 10 | 11 | 12 | 13 |

How to Run Programs

14 |

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 |

Command-line Parameters

24 |

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 |
    34 |
  • Firstly, the obvious: the program couldn't be launched.
  • 35 |
  • The dialog shows "Action" and "Params", but our whole command line is shown next to "Action", and "Params" is empty. In other words, the Run function doesn't know where the program name ends and the parameters begin.
  • 36 |
  • "The system cannot find the file specified" (on English-language systems). Perhaps the system couldn't find "wordpad", but what it's really saying is that there is no such file as "wordpad C:\...".
  • 37 |
38 |

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 |
    41 |
  • Explicitly use the ".exe" extension.
  • 42 |
  • Explicitly use the full path of wordpad.exe.
  • 43 |
  • Enclose the program name in quotation marks.
  • 44 |
45 |

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 |

Quote Marks and Spaces

50 |

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.

54 |
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 (`').

58 |

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.

59 |

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).

60 |

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'.

61 | 62 |

Including Variables

63 |

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 |

Run's Parameters

73 |

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

83 |

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 Edit
86 |

Any verb registered with the system can be executed by using the * prefix as shown below:

87 |
Run '*Compile-Gui ' A_ScriptFullPath
88 |

If Ahk2Exe is installed, this opens the Ahk2Exe Gui with the current script pre-selected.

89 | 90 |

Environment

91 |

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".

96 |

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 | How to Send Keystrokes | AutoHotkey v2 9 | 10 | 11 | 12 | 13 |

How to Send Keystrokes

14 |
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 |
    18 |
  1. How to write the code so that the program knows which keys you want to send.
  2. 19 |
  3. How to use the available modes and options to get the right end result.
  4. 20 |
21 |

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 |

Trying the examples

24 |

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.

25 |

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 |

How to write the code

29 |

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 |

Rules of quoted strings

34 |

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:

35 |
^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:

37 |
^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.

44 |

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.

45 | 46 |

Sending keys and key combinations

47 |

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: ^!+#{}

48 |

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.

49 |

To send a key by name, or to send any one of the above symbols literally, enclose it in braces. For example:

50 |
    51 |
  • ^+{Left} produces Ctrl+Shift+Left
  • 52 |
  • ^{+}{Left} produces Ctrl++ followed by Left
  • 53 |
  • ^+Left produces Ctrl+Shift+L followed literally by the letters eft
  • 54 |
55 |

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.

58 |

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 |

Hotkeys vs. Send

67 |

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:

69 |
    70 |
  • Other hotkey modifier symbols are not supported by Send. For example, >^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}".
  • 71 |
  • Key names are never enclosed in braces within hotkeys, but must always be enclosed in braces for Send (if longer than one character).
  • 72 |
  • Send is case-sensitive. For example, Send "^A" sends the combination of Ctrl with upper-case "a", so Ctrl+Shift+A. By contrast, ^a:: and ^A:: are equivalent.
  • 73 |
74 |

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:

76 |
:*?B0:{::{}}{Left}
77 | 78 |

Blind mode

79 |

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.

80 |

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:

81 |
*^1::Send "{Blind}{Home}"
 82 | *^2::Send "{Blind}{End}"
83 |

For more about {Blind}, see Blind mode.

84 | 85 |

Others

86 |

Send supports a few other special constructs, such as:

87 |
    88 |
  • {U+00B5} to send a Unicode character by its ordinal value (character code).
  • 89 |
  • {ASC 0181} to send an Alt+Numpad sequence.
  • 90 |
  • {Click Options} to click or move the mouse.
  • 91 |
92 |

For a full list, see Key names.

93 | 94 |

Modes and options

95 |

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 |

Timing and delays

101 |

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 |
    103 |
  • A keypress is supposed to trigger some change within the target app (such as showing a new control or window), and sending another keypress before that happens will have the wrong effect.
  • 104 |
  • The app can't keep up with a rapid stream of keystrokes, and you need to slow them all down.
  • 105 |
106 |

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.

114 | 115 |

Sending a lot of text

116 |

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 | How to Write Hotkeys | AutoHotkey v2 9 | 10 | 11 | 12 | 13 |

How to Write Hotkeys

14 |

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 ::.

28 |

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 |

Basic Hotkeys

31 |

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 |
    33 |
  • Remove # 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.
  • 34 |
  • Replace # with ^ for Ctrl, ! for Alt or + for Shift, or try combinations.
  • 35 |
  • Replace # 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.
  • 36 |
  • Replace n with any other letter or symbol (except :).
  • 37 |
  • Replace n with any name from the key list.
  • 38 |
39 |

Note: The last character before :: is never interpreted as a modifier symbol.

40 |

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 |
    42 |
  • #:: 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).
  • 43 |
  • ##:: would create a hotkey like the above, but which activates only if you are also holding the Windows key.
  • 44 |
  • LWin:: would create a hotkey activated by pressing down the left Windows key without any other modifier keys.
  • 45 |
46 |

The most common modifiers are Ctrl (^), Alt (!), Shift (+) and Win (#).

47 |

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.

48 |

The other modifiers are:

49 |
    50 |
  • * (wildcard) allows the hotkey to fire even if you are holding modifier keys that the hotkey doesn't include symbols for.
  • 51 |
  • ~ (no-suppress) prevents the hotkey from blocking the key's native function.
  • 52 |
  • $ (use hook) prevents unintentional loops when sending keys, and in some instances makes the hotkey more reliable.
  • 53 |
54 |

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 |

Context-sensitive Hotkeys

58 |

The #HotIf directive can be used to specify a condition that must be met for the hotkey to activate, such as:

59 |
    60 |
  • If a window of a specific app is active when you press the hotkey.
  • 61 |
  • If CapsLock is on when you press the hotkey.
  • 62 |
  • Any other condition you are able to detect with code.
  • 63 |
64 |

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).

73 |

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 |
    76 |
  • Replace WinActive with WinExist so that the hotkeys activate if Notepad is running, even if Notepad doesn't have the focus.
  • 77 |
  • Replace the condition with GetKeyState("CapsLock", "T") so that the hotkeys only activate while CapsLock is on.
  • 78 |
  • Add another ^a or #c hotkey for some other window, such as your web browser or editor. Note that we use ahk_class so that the example will work on non-English systems, but you can remove it and use the window's title if you wish.
  • 79 |
80 |

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 |

Custom Combinations

84 |

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.

85 |

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 |
    87 |
  1. Use another hotkey such as 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.
  2. 88 |
  3. Prefix the combination with tilde (~), as in ~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.
  4. 89 |
90 |

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.

91 |

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 |

Other Features

99 |

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 | Quick Reference | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | AutoHotkey 15 |

Version 2.0.19

16 |

https://www.autohotkey.com

17 |

© 2014 Steve Gray, Chris Mallett, portions © AutoIt Team and various others

18 |

Software License: GNU General Public License

19 | 20 |

Quick Reference

21 |

Getting started:

22 |
    23 |
  • How to use the program
  • 24 |
  • Tutorials: 25 |
      26 |
    • How to run example code
    • 27 |
    • How to write hotkeys
    • 28 |
    • How to send keystrokes
    • 29 |
    • How to run programs
    • 30 |
    • How to manage windows
    • 31 |
    • Beginner tutorial by tidbit
    • 32 |
    33 |
  • 34 |
  • Text editors with AutoHotkey support
  • 35 |
  • Frequently asked questions
  • 36 |
37 |

Scripts:

38 |
    39 |
  • Concepts and conventions: explanations of various things you need to know.
  • 40 |
  • Scripting language: how to write scripts.
  • 41 |
  • Miscellaneous topics
  • 42 |
  • List of built-in functions
  • 43 |
  • Variables and expressions
  • 44 |
  • How to use functions
  • 45 |
  • Objects
  • 46 |
  • Interactive debugging
  • 47 |
48 |

Keyboard and mouse:

49 |
    50 |
  • Hotkeys (mouse, controller and keyboard shortcuts)
  • 51 |
  • Hotstrings and auto-replace
  • 52 |
  • Remapping keys and buttons
  • 53 |
  • List of keys, mouse buttons and controller controls
  • 54 |
55 |

Other:

56 |
    57 |
  • DllCall
  • 58 |
  • RegEx quick reference
  • 59 |
60 | 61 |

Acknowledgements

62 |

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 - Definition & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

A_Clipboard

15 | 16 |

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:

19 |
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.

26 | 27 |

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_Clipboard
32 | 33 | 34 |

Related

35 |
    36 |
  • ClipboardAll: For operating upon everything on the clipboard (such as pictures and formatting).
  • 37 |
  • OnClipboardChange: For detecting and responding to clipboard changes.
  • 38 |
39 | 40 |

Examples

41 |
42 |

Gives the clipboard entirely new contents.

43 |
A_Clipboard := "my text"
44 |
45 | 46 |
47 |

Empties the clipboard.

48 |
A_Clipboard := ""
49 |
50 | 51 |
52 |

Converts any copied files, HTML, or other formatted text to plain text.

53 |
A_Clipboard := A_Clipboard
54 |
55 | 56 |
57 |

Appends some text to the clipboard.

58 |
A_Clipboard .= " Text to append."
59 |
60 | 61 |
62 |

Replaces all occurrences of ABC with DEF (also converts the clipboard to plain text).

63 |
A_Clipboard := StrReplace(A_Clipboard, "ABC", "DEF")
64 |
65 | 66 |

Clipboard utilities written in AutoHotkey v1:

67 |
    68 |
  • Deluxe Clipboard: Provides unlimited number of private, named clipboards to Copy, Cut, Paste, Append or CutAppend of selected text.
  • 69 |
  • ClipStep: Control multiple clipboards using only the keyboard's Ctrl-X-C-V.
  • 70 |
71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /docs/lib/A_HotkeyModifierTimeout.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | A_HotkeyModifierTimeout - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

A_HotkeyModifierTimeout

15 | 16 |

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 |

Remarks

21 |

This variable has no effect when:

22 |
    23 |
  • Hotkeys send their keystrokes via the SendInput or SendPlay methods. This is because those methods postpone the user's physical pressing and releasing of keys until after the Send completes.
  • 24 |
  • The script has the keyboard hook installed (you can see if your script uses the hook via the "View->Key history" menu item in the main window, or via the KeyHistory function). This is because the hook can keep track of which modifier keys (Alt, Ctrl, Shift, and Win) the user is physically holding down and doesn't need to use the timeout.
  • 25 |
26 |

To illustrate the effect of this variable, consider this example: ^!a::Send "abc".

27 |

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 |
    31 |
  • Install the keyboard hook by calling InstallKeybdHook.
  • 32 |
  • Use the SendInput or SendPlay methods rather than the traditional SendEvent method.
  • 33 |
  • When using the traditional SendEvent method, reduce SetKeyDelay to 0 or -1, which should help because it sends the keystrokes more quickly.
  • 34 |
35 | 36 |

Related

37 |

GetKeyState

38 | 39 |

Examples

40 |
41 |

Sets the hotkey modifier timeout to 100 ms instead of 50 ms.

42 |
A_HotkeyModifierTimeout := 100
43 |
44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /docs/lib/A_MaxHotkeysPerInterval.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | A_MaxHotkeysPerInterval / A_HotkeyInterval - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

A_MaxHotkeysPerInterval / A_HotkeyInterval

15 | 16 |

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 (hotkeys) for A_MaxHotkeysPerInterval and 2000 (ms) for A_HotkeyInterval.

20 | 21 |

Remarks

22 |

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.

25 |

The limit might be reached by means other than an infinite loop, such as:

26 |
    27 |
  • Key-repeat when the limit is too low relative to the key-repeat rate, or the system is under heavy load.
  • 28 |
  • Keyboard or mouse hardware which sends input events more rapidly than the typical key-repeat rate. For example, tilting the wheel left or right on some mice sends a rapid flood of events which may reach the limit for hotkeys such as WheelLeft:: and WheelRight::.
  • 29 |
30 |

To disable the warning dialog entirely, use A_HotkeyInterval := 0.

31 | 32 |

Examples

33 |
34 |

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 := 200
37 |
38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /docs/lib/A_MenuMaskKey.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | A_MenuMaskKey - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

A_MenuMaskKey

15 | 16 |

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 "".

19 |

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 |

Remarks

23 |

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 |
    30 |
  • The hotkey is suppressed (it lacks the tilde modifier).
  • 31 |
  • Alt or Win is logically down when the hotkey is pressed.
  • 32 |
  • The modifier is physically down or the hotkey requires the modifier to activate. For example, $#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.
  • 33 |
  • Alt is not masked if Ctrl was down when the hotkey was pressed, since Ctrl+Alt does not activate the menu bar.
  • 34 |
  • Win is not masked if the most recent Win keydown was modified with Ctrl, Shift or Alt, since the Start Menu does not normally activate in those cases. However, key-repeat occurs even for Win if it was the last key physically pressed, so it can be hard to predict when the most recent Win keydown was.
  • 35 |
  • Either the keyboard hook is not installed (i.e. for a mouse hotkey), or there have been no other (unsuppressed) keydown or keyup events since the last Alt or Win keydown. Note that key-repeat occurs even for modifier keys and even after sending other keys, but only for the last physically pressed key.
  • 36 |
37 |

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.

39 |

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.

42 | 43 |

Related

44 |

See this archived forum thread for background information.

45 | 46 |

Examples

47 |
48 |

Basic usage.

49 |
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 |
52 | 53 |
54 |

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 |
66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /docs/lib/Any.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Any - Methods & Properties | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Any

15 | 16 |

Any is the class at the root of AutoHotkey's type hierarchy. All other types are a sub-type of Any.

17 |

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.

18 | 19 |

Table of Contents

20 |
    21 |
  • Methods: 22 |
      23 |
    • GetMethod: Retrieves the implementation function of a method.
    • 24 |
    • HasBase: Returns true if the specified base object is in the value's chain of base objects.
    • 25 |
    • HasMethod: Returns true if the value has a method by this name.
    • 26 |
    • HasProp: Returns true if the value has a property by this name.
    • 27 |
    28 |
  • 29 |
  • Properties: 30 |
      31 |
    • Base: Retrieves the value's base object.
    • 32 |
    33 |
  • 34 |
  • Functions: 35 |
      36 |
    • ObjGetBase: Returns the value's base object.
    • 37 |
    38 |
  • 39 |
40 | 41 |

Methods

42 | 43 |

GetMethod

44 |

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.

47 |
48 | 49 |

HasBase

50 |

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.

53 |
54 | 55 |

HasMethod

56 |

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.

59 |
60 | 61 |

HasProp

62 |

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.

65 |
66 | 67 |

Properties

68 | 69 |

Base

70 |

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).

73 |

See also: ObjGetBase, ObjSetBase, Obj.Base

74 |
75 | 76 |

Functions

77 |

ObjGetBase

78 |

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 | Array Object - Methods & Properties | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Array Object

15 |
class Array extends Object
16 | 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 |

Table of Contents

33 |
    34 |
  • Static Methods: 35 |
      36 |
    • Call: Creates a new Array containing the specified values.
    • 37 |
    38 |
  • 39 |
  • Methods: 40 |
      41 |
    • Clone: Returns a shallow copy of an array.
    • 42 |
    • Delete: Removes the value of an array element, leaving the index without a value.
    • 43 |
    • Get: Returns the value at a given index, or a default value.
    • 44 |
    • Has: Returns a non-zero number if the index is valid and there is a value at that position.
    • 45 |
    • InsertAt: Inserts one or more values at a given position.
    • 46 |
    • Pop: Removes and returns the last array element.
    • 47 |
    • Push: Appends values to the end of an array.
    • 48 |
    • RemoveAt: Removes items from an array.
    • 49 |
    • __New: Appends items. Equivalent to Push.
    • 50 |
    • __Enum: Enumerates array elements.
    • 51 |
    52 |
  • 53 |
  • Properties: 54 |
      55 |
    • Length: Retrieves or sets the length of an array.
    • 56 |
    • Capacity: Retrieves or sets the current capacity of an array.
    • 57 |
    • Default: Defines the default value returned when an element with no value is requested.
    • 58 |
    • __Item: Retrieves or sets the value of an array element.
    • 59 |
    60 |
  • 61 |
62 | 63 |

Static Methods

64 | 65 |

Call

66 |

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 |
71 | 72 |

Methods

73 | 74 |

Clone

75 |

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 |
80 | 81 |

Delete

82 |

Removes the value of an array element, leaving the index without a value.

83 |
RemovedValue := ArrayObj.Delete(Index)
84 |

Parameters

85 |
86 |
Index
87 |
88 |

Type: Integer

89 |

A valid array index.

90 |
91 |
92 |

Return Value

93 |

Type: Any

94 |

This method returns the removed value (blank if none).

95 |

Remarks

96 |

This method does not affect the Length of the array.

97 |

A ValueError is thrown if Index is out of range.

98 |
99 | 100 |

Get

101 |

Returns the value at a given index, or a default value.

102 |
Value := ArrayObj.Get(Index , Default)
103 |

This method does the following:

104 |
    105 |
  • Throw an IndexError if Index is zero or out of range.
  • 106 |
  • Return the value at Index, if there is one (see Has).
  • 107 |
  • Return the value of the Default parameter, if specified.
  • 108 |
  • Return the value of ArrayObj.Default, if defined.
  • 109 |
  • Throw an UnsetItemError.
  • 110 |
111 |

When Default is omitted, this is equivalent to ArrayObj[Index], except that __Item is not called.

112 |
113 | 114 |

Has

115 |

Returns a non-zero number if the index is valid and there is a value at that position.

116 |
HasIndex := ArrayObj.Has(Index)
117 |
118 | 119 |

InsertAt

120 |

Inserts one or more values at a given position.

121 |
ArrayObj.InsertAt(Index, Value1 , Value2, ... ValueN)
122 |

Parameters

123 |
124 |
Index
125 |
126 |

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 |
129 |
Value1 ...
130 |
131 |

Type: Any

132 |

One or more values to insert. To insert an array of values, pass theArray* as the last parameter.

133 |
134 |
135 |

Remarks

136 |

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.

149 |
150 | 151 |

Pop

152 |

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 |

If the array is empty (Length is 0), an Error is thrown.

159 |
160 | 161 |

Push

162 |

Appends values to the end of an array.

163 |
ArrayObj.Push(Value, Value2, ..., ValueN)
164 |

Parameters

165 |
166 |
Value ...
167 |
168 |

Type: Any

169 |

One or more values to insert. To insert an array of values, pass theArray* as the last parameter.

170 |
171 |
172 |
173 | 174 |

RemoveAt

175 |

Removes items from an array.

176 |
RemovedValue := ArrayObj.RemoveAt(Index)
177 | ArrayObj.RemoveAt(Index, Length)
178 |

Parameters

179 |
180 |
Index
181 |
182 |

Type: Integer

183 |

The index of the value or values to remove.

184 |
185 | 186 |
Length
187 |
188 |

Type: Integer

189 |

If omitted, one item is removed. Otherwise, specify the length of the range of values to remove.

190 |
191 |
192 |

Return Value

193 |

Type: Any

194 |

If Length is omitted, the removed value is returned (blank if none). Otherwise there is no return value.

195 |

Remarks

196 |

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]              ; C
206 |
207 | 208 |

__New

209 |

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 |
213 | 214 |

__Enum

215 |

Enumerates array elements.

216 |
For Value in ArrayObj
217 |
For Index, Value in ArrayObj
218 |

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 |
220 |
Index
221 |
222 |

Type: Integer

223 |

The array index, typically the same as A_Index. This is present only in the two-parameter mode.

224 |
225 |
Value
226 |
227 |

Type: Any

228 |

The value (if there is no value, Value becomes uninitialized).

229 |
230 |
231 |
232 | 233 |

Properties

234 | 235 |

Length

236 |

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 |
245 | 246 |

Capacity

247 |

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 |
252 | 253 |

Default

254 |

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 |
259 | 260 |

__Item

261 |

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 |
269 | 270 | 271 | 272 | -------------------------------------------------------------------------------- /docs/lib/Block.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | {...} (block) - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

{...} (block)

14 |

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 |

Remarks

21 |

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 |     return
29 |

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 |

Related

64 |

Function Definitions, Control Flow Statements, If, Else, Loop Statements, Try, Catch, Finally

65 | 66 |

Examples

67 |
68 |

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.

69 |
if (x = 1)
70 | {
71 |     MsgBox "test1"
72 |     Sleep 5
73 | }
74 | else
75 |     MsgBox "test2"
76 |
77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /docs/lib/BlockInput.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | BlockInput - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

BlockInput

14 | 15 |

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 MouseMove
20 |

Parameters

21 |
22 | 23 |
OnOff
24 |
25 |

Type: String or Integer

26 |

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 |
30 |
SendMouse
31 |
32 |

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").

35 |

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").

36 |

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.

38 |
39 |
MouseMove
40 |
41 |

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 |
46 | 47 |
48 | 49 |

Remarks

50 |

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.

51 |

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 $#).

64 |

Input is automatically re-enabled when the script closes.

65 |

Related

66 |

SendMode, Send, Click, MouseMove, MouseClick, MouseClickDrag

67 |

Examples

68 |
69 |

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 false
75 |
76 | 77 | 78 | -------------------------------------------------------------------------------- /docs/lib/Break.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Break - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Break

14 |

Exits (terminates) any type of loop statement.

15 |
Break LoopLabel
16 | 17 |

Parameters

18 |
19 |
LoopLabel
20 |
21 |

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")

23 |
24 |
25 | 26 |

Remarks

27 |

The use of Break and Continue are encouraged over Goto since they usually make scripts more readable and maintainable.

28 |

Related

29 |

Continue, Loop, While-loop, For-loop, Blocks, Labels

30 | 31 |

Examples

32 |
33 |

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 |
44 | 45 |
46 |

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 |
61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /docs/lib/Buffer.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Buffer Object - Definition & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Buffer Object

15 |
class Buffer extends Object
16 | 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 Buffer
22 | 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 |

Table of Contents

27 |
    28 |
  • Buffer-like Objects
  • 29 |
  • Static Methods: 30 |
      31 |
    • Call: Creates a new Buffer object.
    • 32 |
    33 |
  • 34 |
  • Methods: 35 |
      36 |
    • __New: Allocates or reallocates the buffer and optionally fills it.
    • 37 |
    38 |
  • 39 |
  • Properties: 40 |
      41 |
    • Ptr: Retrieves the buffer's current memory address.
    • 42 |
    • Size: Retrieves or sets the buffer's size, in bytes.
    • 43 |
    44 |
  • 45 |
  • Related
  • 46 |
  • Examples
  • 47 |
48 | 49 |

Buffer-like Objects

50 |

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 |

Static Methods

54 |

Call

55 |

Creates a new Buffer object.

56 |
BufferObj := Buffer(ByteCount, FillByte)
 57 | BufferObj := Buffer.Call(ByteCount, FillByte)
58 |

Parameters

59 |
60 |
ByteCount
61 |
62 |

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 |
66 |
FillByte
67 |
68 |

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 |
72 |
73 |

Return Value

74 |

Type: Object

75 |

This method or function returns a Buffer object.

76 |

Remarks

77 |

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 |
80 | 81 |

Methods

82 |

__New

83 |

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 |
90 | 91 |

Properties

92 |

Ptr

93 |

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 |
97 | 98 |

Size

99 |

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 |
106 | 107 |

Related

108 |

DllCall, NumPut, NumGet, StrPut, StrGet, File.RawRead, File.RawWrite, ClipboardAll

109 | 110 |

Examples

111 |
112 |

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 |
135 | 136 | 137 | 138 | -------------------------------------------------------------------------------- /docs/lib/CallbackCreate.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | CallbackCreate - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

CallbackCreate

15 | 16 |

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 |

Parameters

20 |
21 | 22 |
Function
23 |
24 |

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 |
29 | 30 |
Options
31 |
32 |

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").

34 |

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 |
38 | 39 |
ParamCount
40 |
41 |

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 |
44 | 45 |
46 | 47 |

Return Value

48 |

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 |

Error Handling

52 |

This function fails and throws an exception under any of the following conditions:

53 |
    54 |
  • Function is not an object, or has neither a MinParams property nor a Call method.
  • 55 |
  • Function has a MinParams property which exceeds the number of parameters that the callback will supply.
  • 56 |
  • ParamCount is negative.
  • 57 |
  • ParamCount is omitted and: 1) Function has no MinParams property; or 2) the & option is used with the standard 32-bit calling convention.
  • 58 |
59 | 60 | 61 |

The Function's Parameters

62 |

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 >> 32
73 | 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:

88 |
 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 |

What Function Should Return

98 |

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 |

Fast vs. Slow

101 |

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 |

CallbackFree

106 |

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 |

Related

112 |

DllCall, OnMessage, OnExit, OnClipboardChange, Sort's callback, Critical, PostMessage, SendMessage, Functions, Windows Messages, Threads

113 | 114 |

Examples

115 |
116 |

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 |
135 | 136 |
137 |

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 |
166 | 167 | 168 | -------------------------------------------------------------------------------- /docs/lib/CaretGetPos.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | CaretGetPos - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

CaretGetPos

15 | 16 |

Retrieves the current position of the caret (text insertion point).

17 | 18 |
CaretFound := CaretGetPos(&OutputVarX, &OutputVarY)
19 |

Parameters

20 |
21 |
&OutputVarX, &OutputVarY
22 |
23 |

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 |
26 |
27 | 28 |

Return Value

29 |

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 |

Remarks

33 |

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 |

Related

37 |

CoordMode, A_CoordModeCaret

38 | 39 |

Examples

40 |
41 |

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 |
50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /docs/lib/Catch.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Catch - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Catch

14 | 15 |

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 |

Parameters

22 |
23 | 24 |
ErrorClass
25 |
26 |

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.

28 |

If no classes are specified, the default is Error.

29 |

To catch anything at all, use catch Any.

30 |

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 |
32 | 33 |
OutputVar
34 |
35 |

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 |
39 | 40 |
Statements
41 |
42 |

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 |
45 | 46 |
47 | 48 |

Remarks

49 |

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.

52 |

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 |

Related

62 |

Try, Throw, Error Object, Else, Finally, Blocks, OnError

63 | 64 |

Examples

65 |

See Try.

66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /docs/lib/Chr.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Chr - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Chr

14 | 15 |

Returns the string (usually a single character) corresponding to the character code indicated by the specified number.

16 | 17 |
String := Chr(Number)
18 |

Parameters

19 |
20 | 21 |
Number
22 |
23 |

Type: Integer

24 |

A Unicode character code between 0 and 0x10FFFF.

25 |
26 | 27 |
28 | 29 |

Return Value

30 |

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 |

Remarks

35 |

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 |

Related

39 |

Ord

40 | 41 |

Examples

42 |
43 |

Reports the string corresponding to the character code 116.

44 |
MsgBox Chr(116) ; Reports "t".
45 |
46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /docs/lib/Class.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Class Object - Methods & Properties | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Class Object

15 |
class Class extends Object
16 | 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.

19 |

"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 |

Table of Contents

23 |
    24 |
  • Methods: 25 |
      26 |
    • Call: Constructs a new instance of the class.
    • 27 |
    28 |
  • 29 |
  • Properties: 30 |
      31 |
    • Prototype: Retrieves or sets the object on which all instances of the class are based.
    • 32 |
    33 |
  • 34 |
35 | 36 |

Methods

37 | 38 |

Call

39 |

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 |
    44 |
  • Allocate memory and initialize the binary structure of the object, which depends on the object's native type (e.g. whether it is an Array or Map, or just an Object).
  • 45 |
  • Set the base of the new object to ClassObj.Prototype.
  • 46 |
  • Call the new object's __Init method, if it has one. This method is automatically created by class definitions; it contains all instance variable initializers defined within the class body.
  • 47 |
  • Call the new object's __New method, if it has one. All parameters passed to Call are forwarded on to __New.
  • 48 |
  • Return the new object.
  • 49 |
50 |

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.

51 |

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.

52 |
53 | 54 |

Properties

55 | 56 |

Prototype

57 |

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.

62 |

Prototype is automatically defined as an own property of any class object created by a class definition.

63 |
64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /docs/lib/Click.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Click - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Click

14 | 15 |

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 Options
17 | 18 |

Parameters

19 |
20 |
Options
21 |
22 |

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.

24 |

Warning: Click 100 200 would be equivalent to Click "100200", as the two numbers would be concatenated before the function is called.

25 |

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.

27 |

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.

28 |

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".

30 |

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.

31 |

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 |
33 |
34 | 35 |

Remarks

36 |

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}".

37 |

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+RightClick
40 |

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.

41 |

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 |

Related

45 |

Send "{Click}", SendMode, CoordMode, SetDefaultMouseSpeed, SetMouseDelay, MouseClick, MouseClickDrag, MouseMove, ControlClick, BlockInput

46 |

Examples

47 |
48 |

Clicks the left mouse button at the mouse cursor's current position.

49 |
Click
50 |
51 | 52 |
53 |

Clicks the left mouse button at a specific position.

54 |
Click 100, 200
55 |
56 | 57 |
58 |

Moves the mouse cursor to a specific position without clicking.

59 |
Click 100, 200, 0
60 |
61 | 62 |
63 |

Clicks the right mouse button at a specific position.

64 |
Click 100, 200, "Right"
65 |
66 | 67 |
68 |

Performs a double-click at the mouse cursor's current position.

69 |
Click 2
70 |
71 | 72 |
73 |

Presses down the left mouse button and holds it.

74 |
Click "Down"
75 |
76 | 77 |
78 |

Releases the right mouse button.

79 |
Click "Up Right"
80 |
81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /docs/lib/ClipWait.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ClipWait - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ClipWait

14 | 15 |

Waits until the clipboard contains data.

16 | 17 |
Boolean := ClipWait(Timeout, WaitFor)
18 |

Parameters

19 |
20 | 21 |
Timeout
22 |
23 |

Type: Integer or Float

24 |

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 |
26 | 27 |
WaitFor
28 |
29 |

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 |
35 | 36 |
37 | 38 |

Return Value

39 |

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 |

Remarks

43 |

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 |

Related

49 |

A_Clipboard, WinWait, KeyWait

50 |

Examples

51 |
52 |

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 | return
62 |
63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /docs/lib/ClipboardAll.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ClipboardAll - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ClipboardAll

15 | 16 |

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.

19 | 20 |

Parameters

21 |

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 |
23 |
Data
24 |
25 |

Type: Object or Integer

26 |

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 |
28 |
Size
29 |
30 |

Type: Integer

31 |

The number of bytes of data to use. This is optional when Data is an object.

32 |
33 |
34 | 35 |

Return Value

36 |

Type: Object

37 |

This function returns a ClipboardAll object, which has two properties (inherited from Buffer):

38 |
    39 |
  • Ptr: The address of the data contained by the object. This address is valid until the object is freed.
  • 40 |
  • Size: The size, in bytes, of the raw binary data.
  • 41 |
42 | 43 |

Remarks

44 |

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 |

Related

51 |

A_Clipboard, ClipWait, OnClipboardChange, #ClipboardTimeout, Buffer

52 | 53 |

Examples

54 | 55 |
56 |

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 |
62 | 63 |
64 |

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 |
76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /docs/lib/ComCall.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ComCall - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ComCall

15 | 16 |

Calls a native COM interface method by index.

17 | 18 |
Result := ComCall(Index, ComObj , Type1, Arg1, Type2, Arg2, ReturnType)
19 |

Parameters

20 |
21 | 22 |
Index
23 |
24 |

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 |
31 | 32 |
ComObj
33 |
34 |

Type: Integer or Object

35 |

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.

36 |

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 |
39 | 40 |
Type1, Arg1
41 |
42 |

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 |
45 | 46 |
ReturnType
47 |
48 |

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.

51 |

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 |
54 | 55 |
56 | 57 |

Return Value

58 |

Type: String or Integer

59 |

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.

61 | 62 |

Remarks

63 |

The following DllCall topics are also applicable to ComCall:

64 |
    65 |
  • Types of Arguments and Return Values
  • 66 |
  • Errors
  • 67 |
  • Native Exceptions and A_LastError
  • 68 |
  • Structures and Arrays
  • 69 |
  • Known Limitations
  • 70 |
  • .NET Framework
  • 71 |
72 | 73 |

Related

74 |

ComObject, ComObjQuery, ComValue, Buffer object, CallbackCreate

75 | 76 |

Examples

77 | 78 |
79 |

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 |
111 | 112 |
113 |

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 |
164 | 165 | 166 | 167 | -------------------------------------------------------------------------------- /docs/lib/ComObjActive.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ComObjActive - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ComObjActive

14 | 15 |

Retrieves a registered COM object.

16 |
ComObj := ComObjActive(CLSID)
17 | 18 |

Parameters

19 |
20 | 21 |
CLSID
22 |
23 |

Type: String

24 |

CLSID or human-readable Prog ID of the COM object to retrieve.

25 |
26 | 27 |
28 | 29 |

Return Value

30 |

Type: ComObject

31 |

This function returns a new COM wrapper object with the variant type VT_DISPATCH (9).

32 | 33 |

Error Handling

34 |

An exception is thrown on failure.

35 | 36 |

Related

37 |

ComValue, ComObject, ComObjGet, ComObjConnect, ComObjFlags, ObjAddRef/ObjRelease, ComObjQuery, GetActiveObject (Microsoft Docs)

38 | 39 |

Examples

40 |
41 |

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.FullName
48 |
49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /docs/lib/ComObjArray.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ComObjArray - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ComObjArray

14 | 15 |

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.

19 | 20 |

Parameters

21 |
22 | 23 |
VarType
24 |
25 |

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 |
29 | 30 |
CountN
31 |
32 |

Type: Integer

33 |

The size of each dimension. Arrays containing up to 8 dimensions are supported.

34 |
35 | 36 |
37 | 38 |

Return Value

39 |

Type: ComObjArray

40 |

This function returns a wrapper object containing a new SafeArray.

41 | 42 |

Methods

43 |

ComObjArray objects support the following methods:

44 |
    45 |
  • .MaxIndex(n): Returns the upper bound of the nth dimension. If n is omitted, it defaults to 1.
  • 46 |
  • .MinIndex(n): Returns the lower bound of the nth dimension. If n is omitted, it defaults to 1.
  • 47 |
  • .Clone(): Returns a copy of the array.
  • 48 |
  • .__Enum(): Not typically called by script; allows for-loops to be used with SafeArrays.
  • 49 |
50 | 51 |

Remarks

52 |

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 |

Related

71 |

ComValue, ComObjType, ComObjValue, ComObjActive, ComObjFlags, Array Manipulation Functions (Microsoft Docs)

72 | 73 |

Examples

74 |
75 |

Simple usage.

76 |
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 |
86 | 87 |
88 |

Multiple dimensions.

89 |
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 |
111 | 112 | 113 | 114 | -------------------------------------------------------------------------------- /docs/lib/ComObjConnect.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ComObjConnect - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ComObjConnect

14 |

Connects a COM object's event source to the script, enabling events to be handled.

15 |
ComObjConnect ComObj , PrefixOrSink
16 | 17 |

Parameters

18 |
19 | 20 |
ComObj
21 |
22 |

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 |
27 | 28 |
PrefixOrSink
29 |
30 |

Type: String or Object

31 |

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 |
34 | 35 |
36 | 37 |

Usage

38 |

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.

47 |

Call ComObjConnect(yourObject, "Prefix") to enable event-handling.

48 |

Call ComObjConnect(yourObject) to disconnect the object (stop handling events).

49 |

If the number of parameters is not known, a variadic function can be used.

50 | 51 |

Event Sink

52 |

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.

54 |

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 |

Remarks

58 |

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 |

Related

63 |

ComObject, ComObjGet, ComObjActive, WScript.ConnectObject (Microsoft Docs)

64 | 65 |

Examples

66 |
67 |

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 |
93 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /docs/lib/ComObjFlags.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ComObjFlags - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ComObjFlags

15 |

Retrieves or changes flags which control a COM wrapper object's behaviour.

16 |
Flags := ComObjFlags(ComObj , NewFlags, Mask)
17 | 18 |

Parameters

19 |
20 | 21 |
ComObj
22 |
23 |

Type: Object

24 |

A COM wrapper object. See ComValue for details.

25 |
26 | 27 |
NewFlags
28 |
29 |

Type: Integer

30 |

New values for the flags identified by Mask, or flags to add or remove.

31 |
32 | 33 |
Mask
34 |
35 |

Type: Integer

36 |

A bitmask of flags to change.

37 |
38 | 39 |
40 | 41 |

Return Value

42 |

Type: Integer

43 |

This function returns the current flags of the specified COM object (after applying NewFlags, if specified).

44 | 45 |

Error Handling

46 |

A TypeError is thrown if ComObj is not a COM wrapper object.

47 | 48 |

Flags

49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 61 | 62 |
FlagEffect
1 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 ComValue(8, "example").

60 |
63 | 64 |

Remarks

65 |

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.

66 | 67 |

Related

68 |

ComValue, ComObjActive, ComObjArray

69 | 70 |

Examples

71 |
72 |

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 |
80 | 81 |
82 |

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 |
99 | 100 | 101 | 102 | -------------------------------------------------------------------------------- /docs/lib/ComObjFromPtr.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ComObjFromPtr - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ComObjFromPtr

15 | 16 |

Wraps a raw IDispatch pointer (COM object) for use by the script.

17 |
ComObj := ComObjFromPtr(DispPtr)
18 | 19 |

Parameters

20 |
21 | 22 |
DispPtr
23 |
24 |

Type: Integer

25 |

A non-null interface pointer for IDispatch or a derived interface.

26 |
27 | 28 |
29 | 30 |

Return Value

31 |

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 |

Remarks

36 |

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.

37 |

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.

38 | 39 |

Related

40 |

ComObject, ComValue, ComObjGet, ComObjConnect, ComObjFlags, ObjAddRef/ObjRelease, ComObjQuery, GetActiveObject (Microsoft Docs)

41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /docs/lib/ComObjGet.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ComObjGet - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ComObjGet

14 |

Returns a reference to an object provided by a COM component.

15 |
ComObj := ComObjGet(Name)
16 | 17 |

Parameters

18 |
19 | 20 |
Name
21 |
22 |

Type: String

23 |

The display name of the object to be retrieved. See MkParseDisplayName (Microsoft Docs) for more information.

24 |
25 | 26 |
27 | 28 |

Return Value

29 |

Type: ComObject

30 |

This function returns a new COM wrapper object with the variant type VT_DISPATCH (9).

31 | 32 |

Error Handling

33 |

An exception is thrown on failure.

34 | 35 |

Related

36 | ComObject, ComObjActive, ComObjConnect, ComObjQuery, CoGetObject (Microsoft Docs) 37 | 38 |

Examples

39 |
40 |

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 |
57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /docs/lib/ComObjQuery.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ComObjQuery - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ComObjQuery

14 |

Queries a COM object for an interface or service.

15 |
InterfaceComObj := ComObjQuery(ComObj, SID, IID)
 16 | InterfaceComObj := ComObjQuery(ComObj, IID)
17 | 18 |

Parameters

19 |
20 | 21 |
ComObj
22 |
23 |

Type: Object or Integer

24 |

A COM wrapper object, an interface pointer, or an object with a Ptr property which returns an interface pointer. See ComValue for details.

25 |
26 | 27 |
IID
28 |
29 |

Type: String

30 |

An interface identifier (GUID) in the form "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}".

31 |
32 | 33 |
SID
34 |
35 |

Type: String

36 |

A service identifier in the same form as IID.

37 |
38 | 39 |
40 | 41 |

Return Value

42 |

Type: Object

43 |

This function returns a COM wrapper object of type dependent on the IID parameter.

44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 |
IIDClassVariant TypeDescription
IID_IDispatchComObjectVT_DISPATCH (9)Allows the script to call properties and methods of the object using normal object syntax.
Any other IIDComValueVT_UNKNOWN (13)Provides only a Ptr property, which allows the object to be passed to DllCall or ComCall.
59 | 60 |

Error Handling

61 |

An exception is thrown on failure, such as if the interface is not supported.

62 | 63 |

Remarks

64 |

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 |

Related

68 |

ComCall, ComObject, ComObjGet, ComObjActive

69 | 70 |

Examples

71 |
72 |

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 |
109 | 110 |
111 |

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 |
153 | 154 | 155 | 156 | -------------------------------------------------------------------------------- /docs/lib/ComObjType.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ComObjType - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ComObjType

14 | 15 |

Retrieves type information from a COM object.

16 | 17 |
Info := ComObjType(ComObj , InfoType)
18 | 19 |

Parameters

20 |
21 | 22 |
ComObj
23 |
24 |

Type: Object

25 |

A wrapper object containing a COM object or typed value. See ComValue for details.

26 |
27 | 28 |
InfoType
29 |
30 |

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.

36 |
37 | 38 |
39 | 40 |

Return Value

41 |

Type: Integer or String

42 |

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 |

Variant Type Constants

45 |

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 |

General Remarks

81 |

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.

83 |

If InfoType is "Name" or "IID", type information is retrieved via the IDispatch::GetTypeInfo interface method. ComObj's variant type must be VT_DISPATCH.

84 |

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).

85 | 86 |

Related

87 |

ComObjValue, ComValue, ComObject, ComObjGet, ComObjActive

88 | 89 |

Examples

90 |
91 |

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 |
103 | 104 | 105 | 106 | -------------------------------------------------------------------------------- /docs/lib/ComObjValue.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ComObjValue - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ComObjValue

14 | 15 |

Retrieves the value or pointer stored in a COM wrapper object.

16 | 17 |
Value := ComObjValue(ComObj)
18 | 19 |

Parameters

20 |
21 | 22 |
ComObj
23 |
24 |

Type: Object

25 |

A wrapper object containing a COM object or typed value. See ComValue for details.

26 |
27 | 28 |
29 | 30 |

Return Value

31 |

Type: Integer

32 |

This function returns a 64-bit signed integer.

33 | 34 |

Error Handling

35 |

A TypeError is thrown if ComObj is not a COM wrapper object.

36 | 37 |

Remarks

38 |

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.

40 | 41 |

Related

42 |

ComObjType, ComObject, ComObjGet, ComObjActive

43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /docs/lib/ComObject.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ComObject - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ComObject

15 |

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.

18 | 19 |

Parameters

20 |
21 | 22 |
CLSID
23 |
24 |

Type: String

25 |

CLSID or human-readable Prog ID of the COM object to create.

26 |
27 | 28 |
IID
29 |
30 |

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.

32 |
33 | 34 |
35 | 36 |

Return Value

37 |

Type: Object

38 |

This function returns a COM wrapper object of type dependent on the IID parameter.

39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 |
IIDClassVariant TypeDescription
IID_IDispatchComObjectVT_DISPATCH (9)Allows the script to call properties and methods of the object using normal object syntax.
Any other IIDComValueVT_UNKNOWN (13)Provides only a Ptr property, which allows the object to be passed to DllCall or ComCall.
54 | 55 |

Error Handling

56 |

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 |

Related

59 |

ComValue, ComObjGet, ComObjActive, ComObjConnect, ComObjArray, ComObjQuery, ComCall, CreateObject (Microsoft Docs)

60 | 61 |

Examples

62 |

For a long list of v1.1 examples, see this archived forum thread.

63 |
64 |

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 |
70 |
71 |

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 |
87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /docs/lib/ComValue.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ComValue - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ComValue

15 | 16 |

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.

19 | 20 |

Parameters

21 |
22 | 23 |
VarType
24 |
25 |

Type: Integer

26 |

An integer indicating the type of value. See ComObjType for a list of types.

27 |
28 | 29 |
Value
30 |
31 |

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 |
36 | 37 |
Flags
38 |
39 |

Type: Integer

40 |

Flags affecting the behaviour of the wrapper object; see ComObjFlags for details.

41 |
42 | 43 |
44 | 45 |

Return Value

46 |

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 |
    50 |
  1. Some COM methods may require specific types of values which have no direct equivalent within AutoHotkey. This function allows the type of a value to be specified when passing it to a COM method. For example, ComValue(0xB, true) creates an object which represents the COM boolean value true.
  2. 51 |
  3. Wrapping a COM object or SafeArray 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, ComObjArray, ComObjActive, ComObjGet and any COM method which returns an object.
  4. 52 |
  5. Wrapping a COM interface pointer allows the script to take advantage of automatic reference counting. An interface pointer can be wrapped immediately upon being returned to the script (typically from ComCall or DllCall), avoiding the need to explicitly release it at some later point.
  6. 53 |
54 | 55 |

Ptr

56 |

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.

57 |

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.

58 |

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.

59 | 60 |

ByRef

61 |

If a wrapper object's VarType includes the VT_BYREF (0x4000) flag, empty brackets [] can be used to read or write the referenced value.

62 |

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.

70 |

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_var
74 |

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.

75 | 76 |

General Remarks

77 |

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.

78 |

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.

82 | 83 |

Related

84 |

ComObjFromPtr, ComObject, ComObjGet, ComObjConnect, ComObjFlags, ObjAddRef/ObjRelease, ComObjQuery, GetActiveObject (Microsoft Docs)

85 | 86 |

Examples

87 |
88 |

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 |
148 | 149 | 150 | 151 | -------------------------------------------------------------------------------- /docs/lib/Continue.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Continue - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Continue

14 |

Skips the rest of a loop statement's current iteration and begins a new one.

15 |
Continue LoopLabel
16 | 17 |

Parameters

18 |
19 |
LoopLabel
20 |
21 |

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")

23 |
24 |
25 | 26 |

Remarks

27 |

Continue behaves the same as reaching the loop's closing brace:

28 |
    29 |
  1. It skips the rest of the loop's body.
  2. 30 |
  3. The loop's Until expression (if it has one) is evaluated.
  4. 31 |
  5. A_Index is increased by 1.
  6. 32 |
  7. The loop's own condition (if it has one) is checked to see if it is satisfied. If so, a new iteration begins; otherwise the loop ends.
  8. 33 |
34 |

The use of Break and Continue are encouraged over Goto since they usually make scripts more readable and maintainable.

35 | 36 |

Related

37 |

Break, Loop, Until, While-loop, For-loop, Blocks, Labels

38 | 39 |

Examples

40 |
41 |

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.

42 |
43 | Loop 10
44 | {
45 |     if (A_Index <= 5)
46 |         continue
47 |     MsgBox A_Index
48 | }
49 |
50 | 51 |
52 |

Continues the outer loop from within a nested loop.

53 |
outer:
54 | Loop 3
55 | {
56 |     x := A_Index
57 |     Loop 3
58 |     {
59 |         if (x*A_Index = 4)
60 |             continue outer  ; Equivalent to continue 2 or goto continue_outer.
61 |         MsgBox x "," A_Index
62 |     }
63 |     continue_outer: ; For goto.
64 | }
65 |
66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /docs/lib/Control.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | List of Control Functions | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Control Functions

14 | 15 |

Functions for retrieving information about a control or for performing various operations on a control. Click on a function name for details.

16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 |
FunctionDescription
ControlAddItemAdds the specified string as a new entry at the bottom of a ListBox or ComboBox.
ControlChooseIndexSets the selection in a ListBox, ComboBox or Tab control to be the Nth item.
ControlChooseStringSets the selection in a ListBox or ComboBox to be the first entry whose leading part matches the specified string.
ControlClickSends a mouse button or mouse wheel event to a control.
ControlDeleteItemDeletes the specified entry number from a ListBox or ComboBox.
ControlFindItemReturns the entry number of a ListBox or ComboBox that is a complete match for the specified string.
ControlFocusSets input focus to a given control on a window.
ControlGetCheckedReturns a non-zero value if the checkbox or radio button is checked.
ControlGetChoiceReturns the name of the currently selected entry in a ListBox or ComboBox.
ControlGetClassNNReturns the ClassNN (class name and sequence number) of the specified control.
ControlGetEnabledReturns a non-zero value if the specified control is enabled.
ControlGetFocusRetrieves which control of the target window has keyboard focus, if any.
ControlGetHwndReturns the unique ID number of the specified control.
ControlGetIndexReturns the index of the currently selected entry or tab in a ListBox, ComboBox or Tab control.
ControlGetItemsReturns an array of items/rows from a ListBox, ComboBox, or DropDownList.
ControlGetPosRetrieves the position and size of a control.
ControlGetStyle
ControlGetExStyle
Returns an integer representing the style or extended style of the specified control.
ControlGetTextRetrieves text from a control.
ControlGetVisibleReturns a non-zero value if the specified control is visible.
ControlHideHides the specified control.
ControlHideDropDownHides the drop-down list of a ComboBox control.
ControlMoveMoves or resizes a control.
ControlSend
ControlSendText
Sends simulated keystrokes or text to a window or control.
ControlSetCheckedTurns on (checks) or turns off (unchecks) a checkbox or radio button.
ControlSetEnabledEnables or disables the specified control.
ControlSetStyle
ControlSetExStyle
Changes the style or extended style of the specified control, respectively.
ControlSetTextChanges the text of a control.
ControlShowShows the specified control if it was previously hidden.
ControlShowDropDownShows the drop-down list of a ComboBox control.
EditGetCurrentColReturns the column number in an Edit control where the caret (text insertion point) resides.
EditGetCurrentLineReturns the line number in an Edit control where the caret (text insert point) resides.
EditGetLineReturns the text of the specified line in an Edit control.
EditGetLineCountReturns the number of lines in an Edit control.
EditGetSelectedTextReturns the selected text in an Edit control.
EditPastePastes the specified string at the caret (text insertion point) in an Edit control.
ListViewGetContentReturns a list of items/rows from a ListView.
166 | 167 |

The Control Parameter

168 |

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.

173 |

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 |

Error Handling

176 |

Typically one of the following errors may be thrown:

177 |
    178 |
  • TargetError: The target window or control could not be found.
  • 179 |
  • Error or OSError: There was a problem carring out the function's purpose, such as retrieving a setting or applying a change.
  • 180 |
  • ValueError or TypeError: Invalid parameters were detected.
  • 181 |
182 | 183 |

Remarks

184 |

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 |

Related

189 |

SetControlDelay, Win functions, GuiControl object (for controls created by the script)

190 | 191 | 192 | 193 | -------------------------------------------------------------------------------- /docs/lib/ControlAddItem.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlAddItem - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlAddItem

15 | 16 |

Adds the specified string as a new entry at the bottom of a ListBox or ComboBox.

17 | 18 |
ControlAddItem String, Control , WinTitle, WinText, ExcludeTitle, ExcludeText
19 | 20 |

Parameters

21 |
22 |
String
23 |
24 |

Type: String

25 |

The string to add.

26 |
27 |
Control
28 |
29 |

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.

31 |
32 |
WinTitle, WinText, ExcludeTitle, ExcludeText
33 |
34 |

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 |
39 |
40 | 41 |

Return Value

42 |

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 |

Error Handling

46 |

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 |

Remarks

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.

51 | 52 |

Related

53 |

ControlDeleteItem, ControlFindItem, Add method (GuiControl object), Control functions

54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /docs/lib/ControlChooseIndex.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlChooseIndex - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlChooseIndex

15 | 16 |

Sets the selection in a ListBox, ComboBox or Tab control to be the Nth item.

17 | 18 |
ControlChooseIndex N, Control , WinTitle, WinText, ExcludeTitle, ExcludeText
19 | 20 |

Parameters

21 |
22 |
N
23 |
24 |

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 |
27 |
Control
28 |
29 |

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.

31 |
32 |
WinTitle, WinText, ExcludeTitle, ExcludeText
33 |
34 |

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 |
39 |
40 | 41 |

Error Handling

42 |

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 |

Remarks

46 |

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 |

Related

52 |

ControlGetIndex, ControlChooseString, Choose method (GuiControl object), Control functions

53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /docs/lib/ControlChooseString.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlChooseString - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlChooseString

15 | 16 |

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, ExcludeText
19 | 20 |

Parameters

21 |
22 |
String
23 |
24 |

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 |
27 |
Control
28 |
29 |

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.

31 |
32 |
WinTitle, WinText, ExcludeTitle, ExcludeText
33 |
34 |

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 |
39 |
40 | 41 |

Return Value

42 |

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 |

Error Handling

46 |

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 |

Remarks

50 |

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 |

Related

54 |

ControlChooseIndex, ControlGetChoice, Choose method (GuiControl object), Control functions

55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /docs/lib/ControlClick.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlClick - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ControlClick

14 | 15 |

Sends a mouse button or mouse wheel event to a control.

16 | 17 |
ControlClick Control-or-Pos, WinTitle, WinText, WhichButton, ClickCount, Options, ExcludeTitle, ExcludeText
18 |

Parameters

19 |
20 | 21 |
Control-or-Pos
22 |
23 |

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).

26 |

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.

28 |

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".

29 |
30 | 31 |
WinTitle, WinText, ExcludeTitle, ExcludeText
32 |
33 |

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 |
38 | 39 |
WhichButton
40 |
41 |

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 |
46 | 47 |
ClickCount
48 |
49 |

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 |
52 | 53 |
Options
54 |
55 |

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".

57 |

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 |
65 | 66 |
67 | 68 |

Error Handling

69 |

An exception is thrown in the following cases:

70 |
    71 |
  • TargetError: The target window could not be found.
  • 72 |
  • TargetError: The target control could not be found and Control-or-Pos does not specify a valid position.
  • 73 |
  • OSError (very rare): the X or Y position is omitted and the control's position could not be determined.
  • 74 |
  • ValueError or TypeError: Invalid parameters were detected.
  • 75 |
76 | 77 |

Reliability

78 |

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.

80 |

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 |

Remarks

85 |

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 |

Related

90 |

SetControlDelay, Control functions, Click

91 |

Examples

92 |
93 |

Clicks the OK button.

94 |
ControlClick "OK", "Some Window Title"
95 |
96 | 97 |
98 |

Clicks at a set of coordinates. Note the lack of a comma between X and Y.

99 |
ControlClick "x55 y77", "Some Window Title"
100 |
101 | 102 |
103 |

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 |
107 | 108 | 109 | 110 | -------------------------------------------------------------------------------- /docs/lib/ControlDeleteItem.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlDeleteItem - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlDeleteItem

15 | 16 |

Deletes the specified entry number from a ListBox or ComboBox.

17 | 18 |
ControlDeleteItem N, Control , WinTitle, WinText, ExcludeTitle, ExcludeText
19 | 20 |

Parameters

21 |
22 |
N
23 |
24 |

Type: Integer

25 |

The index of the item, where 1 is the first entry, 2 is the second, etc.

26 |
27 |
Control
28 |
29 |

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.

31 |
32 |
WinTitle, WinText, ExcludeTitle, ExcludeText
33 |
34 |

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 |
39 |
40 | 41 |

Error Handling

42 |

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 |

Remarks

46 |

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 |

Related

49 |

ControlAddItem, ControlFindItem, Delete method (GuiControl object), Control functions

50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /docs/lib/ControlFindItem.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlFindItem - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlFindItem

15 | 16 |

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 |

Parameters

21 |
22 |
String
23 |
24 |

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 |
27 |
Control
28 |
29 |

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.

31 |
32 |
WinTitle, WinText, ExcludeTitle, ExcludeText
33 |
34 |

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 |
39 |
40 | 41 |

Return Value

42 |

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 |

Error Handling

46 |

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 |

Remarks

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.

51 | 52 |

Related

53 |

ControlAddItem, ControlDeleteItem, Control functions

54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /docs/lib/ControlFocus.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlFocus - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ControlFocus

14 | 15 |

Sets input focus to a given control on a window.

16 | 17 |
ControlFocus Control , WinTitle, WinText, ExcludeTitle, ExcludeText
18 | 19 |

Parameters

20 |
21 |
Control
22 |
23 |

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.

25 |
26 |
WinTitle, WinText, ExcludeTitle, ExcludeText
27 |
28 |

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 |
33 | 34 |
35 | 36 |

Error Handling

37 |

A TargetError is thrown if the window or control could not be found.

38 | 39 |

Remarks

40 |

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 |
    44 |
  • Focusing a button does not automatically make it the default button, as would normally happen if a button is focused by user input. The default button can usually be activated by pressing Enter.
  • 45 |
  • If user input previously caused the default button to be temporarily changed, focusing a non-button control does not automatically restore the default highlight to the actual default button. Pressing Enter may then activate the default button even though it is not highlighted.
  • 46 |
  • Focusing an edit control does not automatically select its text. Instead, the insertion point (caret) is typically positioned wherever it was last time the control had focus.
  • 47 |
48 |

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_NEXTDLGCTL
52 | 53 |

Related

54 |

SetControlDelay, ControlGetFocus, Control functions

55 |

Examples

56 |
57 |

Sets the input focus to the OK button.

58 |
ControlFocus "OK", "Some Window Title"
59 |
60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /docs/lib/ControlGetChecked.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlGetChecked - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlGetChecked

15 | 16 |

Returns a non-zero value if the checkbox or radio button is checked.

17 | 18 |
IsChecked := ControlGetChecked(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
Control
23 |
24 |

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.

26 |
27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 |
35 | 36 |

Return Value

37 |

Type: Integer (boolean)

38 |

This function returns 1 (true) if the checkbox or radio button is checked, or 0 (false) if not.

39 | 40 |

Error Handling

41 |

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 |

Related

45 |

ControlSetChecked, Value property (GuiControl object), Control functions

46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /docs/lib/ControlGetChoice.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlGetChoice - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlGetChoice

15 | 16 |

Returns the name of the currently selected entry in a ListBox or ComboBox.

17 | 18 |
Choice := ControlGetChoice(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
Control
23 |
24 |

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.

26 |
27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 |
35 | 36 |

Return Value

37 |

Type: String

38 |

This function returns the name of the currently selected entry in a ListBox or ComboBox.

39 | 40 |

Error Handling

41 |

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 |

Remarks

45 |

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 |

Related

52 |

ControlChooseIndex, ControlChooseString, Value property (GuiControl object), Choose method (GuiControl object), Control functions

53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /docs/lib/ControlGetClassNN.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlGetClassNN - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlGetClassNN

15 | 16 |

Returns the ClassNN (class name and sequence number) of the specified control.

17 | 18 |
ClassNN := ControlGetClassNN(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
Control
23 |
24 |

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.

26 |
27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 |
35 | 36 |

Return Value

37 |

Type: String

38 |

This function returns the ClassNN (class name and sequence number) of the specified control.

39 | 40 |

Error Handling

41 |

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 |

Remarks

45 |

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 |

Related

50 |

WinGetClass, WinGetControls, ClassNN property (GuiControl object), MouseGetPos, Control functions

51 | 52 |

Examples

53 |
54 |

Retrieves the ClassNN of the currently focused control.

55 |
classNN := ControlGetClassNN(ControlGetFocus("A"))
56 |
57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /docs/lib/ControlGetEnabled.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlGetEnabled - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlGetEnabled

15 | 16 |

Returns a non-zero value if the specified control is enabled.

17 | 18 |
IsEnabled := ControlGetEnabled(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
Control
23 |
24 |

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.

26 |
27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 |
35 | 36 |

Return Value

37 |

Type: Integer (boolean)

38 |

This function returns 1 (true) if the specified control is enabled, or 0 (false) if disabled.

39 | 40 |

Error Handling

41 |

A TargetError is thrown if the window or control could not be found.

42 | 43 |

Related

44 |

ControlSetEnabled, WinSetEnabled, Enabled property (GuiControl object), Control functions

45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/lib/ControlGetFocus.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlGetFocus - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ControlGetFocus

14 | 15 |

Retrieves which control of the target window has keyboard focus, if any.

16 | 17 |
HWND := ControlGetFocus(WinTitle, WinText, ExcludeTitle, ExcludeText)
18 |

Parameters

19 |
20 | 21 |
WinTitle, WinText, ExcludeTitle, ExcludeText
22 |
23 |

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 |
28 | 29 |
30 | 31 |

Return Value

32 |

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 |

Error Handling

37 |

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 |

Remarks

41 |

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 |

Related

45 |

ControlFocus, Control functions

46 |

Examples

47 |
48 |

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 |
54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /docs/lib/ControlGetHwnd.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlGetHwnd - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlGetHwnd

15 | 16 |

Returns the unique ID number of the specified control.

17 | 18 |
Hwnd := ControlGetHwnd(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
Control
23 |
24 |

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.

26 |
27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 |
35 | 36 |

Return Value

37 |

Type: Integer

38 |

This function returns the window handle (HWND) of the specified control.

39 | 40 |

Error Handling

41 |

A TargetError is thrown if the window or control could not be found.

42 | 43 |

Remarks

44 |

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 |

Related

47 |

WinGetID, Hwnd property (GuiControl object), Control functions

48 | 49 |

Examples

50 |
51 |

Retrieves the unique ID number of the Notepad's Edit control.

52 |
editHwnd := ControlGetHwnd("Edit1", "ahk_class Notepad")
53 |
54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /docs/lib/ControlGetIndex.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlGetIndex - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlGetIndex

15 | 16 |

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 |

Parameters

21 |
22 |
Control
23 |
24 |

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.

26 |
27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 |
35 | 36 |

Return Value

37 |

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 |

Error Handling

41 |

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 |

Remarks

45 |

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 |

Related

49 |

ControlChooseIndex, ControlGetChoice, ControlChooseString, Value property (GuiControl object), Choose method (GuiControl object), Control functions

50 | 51 |

Examples

52 | 53 |
54 |

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 |
60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /docs/lib/ControlGetItems.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlGetItems - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlGetItems

15 | 16 |

Returns an array of items/rows from a ListBox, ComboBox, or DropDownList.

17 | 18 |
Items := ControlGetItems(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
Control
23 |
24 |

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.

26 |
27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 |
35 | 36 |

Return Value

37 |

Type: Array

38 |

This function returns an array containing the text of each item or row.

39 | 40 |

Error Handling

41 |

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 |

Remarks

45 |

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 |

Related

48 |

ListViewGetContent, WinGetList, Control functions

49 | 50 |

Examples

51 |
52 |

Accesses the items one by one.

53 |
for item in ControlGetItems("ComboBox1", WinTitle)
54 |     MsgBox "Item number " A_Index " is " item
55 |
56 | 57 |
58 |

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 |
63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /docs/lib/ControlGetPos.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlGetPos - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ControlGetPos

14 | 15 |

Retrieves the position and size of a control.

16 | 17 |
ControlGetPos &OutX, &OutY, &OutWidth, &OutHeight, Control, WinTitle, WinText, ExcludeTitle, ExcludeText
18 |

Parameters

19 |
20 | 21 |
&OutX, &OutY
22 |
23 |

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 |
26 | 27 |
&OutWidth, &OutHeight
28 |
29 |

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 |
32 | 33 |
Control
34 |
35 |

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. This parameter is required; that is, it cannot be omitted.

37 |
38 | 39 |
WinTitle, WinText, ExcludeTitle, ExcludeText
40 |
41 |

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 |
46 | 47 |
48 | 49 |

Error Handling

50 |

A TargetError is thrown if the window or control could not be found.

51 | 52 |

Remarks

53 |

Unlike functions that change a control, ControlGetPos does not have an automatic delay (SetControlDelay does not affect it).

54 | 55 |

Related

56 |

ControlMove, WinGetPos, Control functions

57 |

Examples

58 |
59 |

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 |
68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /docs/lib/ControlGetStyle.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlGetStyle / ControlGetExStyle - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlGetStyle / ControlGetExStyle

15 | 16 |

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 |

Parameters

22 |
23 |
Control
24 |
25 |

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.

27 |
28 |
WinTitle, WinText, ExcludeTitle, ExcludeText
29 |
30 |

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 |
35 |
36 | 37 |

Return Value

38 |

Type: Integer

39 |

These functions return the style or extended style of the specified control.

40 | 41 |

Error Handling

42 |

A TargetError is thrown if the window or control could not be found.

43 | 44 |

Remarks

45 |

See the styles table for a partial listing of styles.

46 |

ControlGetExStyle only retrieves generic extended styles, such as WS_EX_CLIENTEDGE (0x200). To retrieve control-specific extended styles, use SendMessage, e.g. SendMessage(0x1037, 0, 0, MyListView) where 0x1037 is LVM_GETEXTENDEDLISTVIEWSTYLE. For a ListView created via AutoHotkey, this example returns 48 (0x30), a combination of LVS_EX_FULLROWSELECT (0x20) and LVS_EX_HEADERDRAGDROP (0x10), provided the extended ListView styles have not been changed beforehand.

47 | 48 |

Related

49 |

ControlSetStyle / ControlSetExStyle, WinGetStyle / WinGetExStyle, styles table, Control functions

50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /docs/lib/ControlGetText.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlGetText - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ControlGetText

14 | 15 |

Retrieves text from a control.

16 | 17 |
Text := ControlGetText(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)
18 |

Parameters

19 |
20 | 21 |
Control
22 |
23 |

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.

25 |
26 | 27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 | 35 |
36 | 37 |

Return Value

38 |

Type: String

39 |

This function returns the text of the specified control.

40 | 41 |

Error Handling

42 |

A TargetError is thrown if the window or control could not be found.

43 | 44 |

Remarks

45 |

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 := "".

48 |

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).

50 |

To retrieve an array of all controls in a window, use WinGetControls or WinGetControlsHwnd.

51 | 52 |

Related

53 |

ControlSetText, WinGetText, Control functions

54 |

Examples

55 |
56 |

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 |
59 |
60 |

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 |
65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /docs/lib/ControlGetVisible.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlGetVisible - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlGetVisible

15 | 16 |

Returns a non-zero value if the specified control is visible.

17 | 18 |
IsVisible := ControlGetVisible(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
Control
23 |
24 |

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.

26 |
27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 |
35 | 36 |

Return Value

37 |

Type: Integer (boolean)

38 |

This function returns 1 (true) if the specified control is visible, or 0 (false) if hidden.

39 | 40 |

Error Handling

41 |

A TargetError is thrown if the window or control could not be found.

42 | 43 |

Related

44 |

ControlHide, ControlShow, Visible property (GuiControl object), Control functions

45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/lib/ControlHide.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlHide - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlHide

15 | 16 |

Hides the specified control.

17 | 18 |
ControlHide Control , WinTitle, WinText, ExcludeTitle, ExcludeText
19 | 20 |

Parameters

21 |
22 |
Control
23 |
24 |

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.

26 |
27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 |
35 | 36 |

Error Handling

37 |

A TargetError is thrown if the window or control could not be found.

38 | 39 |

Remarks

40 |

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 |

Related

44 |

ControlShow, ControlGetVisible, WinHide, Visible property (GuiControl object), Control functions

45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/lib/ControlHideDropDown.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlHideDropDown - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlHideDropDown

15 | 16 |

Hides the drop-down list of a ComboBox control.

17 | 18 |
ControlHideDropDown Control , WinTitle, WinText, ExcludeTitle, ExcludeText
19 | 20 |

Parameters

21 |
22 |
Control
23 |
24 |

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.

26 |
27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 |
35 | 36 |

Error Handling

37 |

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 |

Remarks

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 |

Related

44 |

ControlShowDropDown, Control functions

45 | 46 |

Examples

47 |

See example #1 on the ControlShowDropDown page.

48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /docs/lib/ControlMove.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlMove - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ControlMove

14 | 15 |

Moves or resizes a control.

16 | 17 |
ControlMove X, Y, Width, Height, Control, WinTitle, WinText, ExcludeTitle, ExcludeText
18 | 19 |

Parameters

20 |
21 |
X, Y
22 |
23 |

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 |
26 | 27 |
Width, Height
28 |
29 |

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 |
32 | 33 |
Control
34 |
35 |

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. This parameter is required; that is, it cannot be omitted.

37 |
38 | 39 |
WinTitle, WinText, ExcludeTitle, ExcludeText
40 |
41 |

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 |
46 |
47 | 48 |

Error Handling

49 |

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 |

Remarks

54 |

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 |

Related

57 |

ControlGetPos, WinMove, SetControlDelay, Control functions

58 | 59 |

Examples

60 |
61 |

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 |
75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /docs/lib/ControlSend.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlSend / ControlSendText - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ControlSend / ControlSendText

14 | 15 |

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, ExcludeText
19 |

Parameters

20 |
21 | 22 |
Keys
23 |
24 |

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 |
28 | 29 |
Control
30 |
31 |

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.

33 |
34 | 35 |
WinTitle, WinText, ExcludeTitle, ExcludeText
36 |
37 |

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 |
42 | 43 |
44 | 45 |

Error Handling

46 |

A TargetError is thrown if the window or control could not be found.

47 | 48 |

Remarks

49 |

Unlike Send, ControlSend ignores SendMode. It uses the operating system's PostMessage function to post keyboard messages.

50 |

ControlSendText is similar to ControlSend, except that it 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.

51 |

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.

52 |

By default, modifier keystrokes (Ctrl, Alt, Shift, and Win) are sent as they normally would be by the SendEvent 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.

53 |

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:

54 |
ControlSend "{Alt down}f{Alt up}", "Edit1", "Untitled - Notepad"
55 |

The method above also allows the sending of modifier keystrokes (Ctrl, Alt, Shift, and Win) while the workstation is locked (protected by logon prompt).

56 |

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.

57 |

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:

58 |
SetKeyDelay 10, 10
 59 | SetKeyDelay 0, 10
 60 | SetKeyDelay -1, 0
61 |

If the target control is an Edit control (or something similar), the following are usually more reliable and faster than ControlSend:

62 |
EditPaste("This text will be inserted at the caret position.", ControlName, WinTitle)
63 |
ControlSetText("This text will entirely replace any current text.", ControlName, WinTitle)
64 |

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.

65 | 66 |

Related

67 |

SetKeyDelay, Escape sequences (e.g. `n) , Control functions, Send, Automating Winamp

68 |

Examples

69 |
70 |

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.

71 |
Run "Notepad",, "Min", &PID  ; Run Notepad minimized.
 72 | WinWait "ahk_pid " PID  ; Wait for it to appear.
 73 | ; Send the text to the inactive Notepad edit control.
 74 | ; The third parameter is omitted so the last found window is used.
 75 | ControlSend "This is a line of text in the notepad window.{Enter}", "Edit1"
 76 | ControlSendText "Notice that {Enter} is not sent as an Enter keystroke with ControlSendText.", "Edit1"
 77 | 
 78 | Msgbox "Press OK to activate the window to see the result."
 79 | WinActivate "ahk_pid " PID  ; Show the result.
80 |
81 | 82 |
83 |

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.

84 |
SetTitleMatchMode 2
 85 | Run A_ComSpec,,, &PID  ; Run command prompt.
 86 | WinWait "ahk_pid " PID  ; Wait for it to appear.
 87 | ControlSend "ipconfig{Enter}",, "cmd.exe"  ; Send directly to the command prompt window.
88 |
89 |
90 |

Creates a GUI with an edit control and sent it some text.

91 |
MyGui := Gui()
 92 | MyGui.Add("Edit", "r10 w500")
 93 | MyGui.Show()
 94 | ControlSend "This is a line of text in the edit control.{Enter}", "Edit1", MyGui
 95 | ControlSendText "Notice that {Enter} is not sent as an Enter keystroke with ControlSendText.", "Edit1", MyGui
 96 | 
97 |
98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /docs/lib/ControlSetChecked.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlSetChecked - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlSetChecked

15 | 16 |

Turns on (checks) or turns off (unchecks) a checkbox or radio button.

17 | 18 |
ControlSetChecked NewSetting, Control , WinTitle, WinText, ExcludeTitle, ExcludeText
19 | 20 |

Parameters

21 |
22 | 23 |
NewSetting
24 |
25 |

Type: Integer

26 |

One of the following values:

27 |
    28 |
  • 1 or True turns on the setting
  • 29 |
  • 0 or False turns off the setting
  • 30 |
  • -1 toggles the setting (sets it to the opposite of its current state)
  • 31 |
32 |
33 |
Control
34 |
35 |

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.

37 |
38 |
WinTitle, WinText, ExcludeTitle, ExcludeText
39 |
40 |

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 |
45 |
46 | 47 |

Error Handling

48 |

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 |

Remarks

52 |

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 |

Related

56 |

ControlGetChecked, Value property (GuiControl object), Control functions

57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /docs/lib/ControlSetEnabled.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlSetEnabled - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlSetEnabled

15 | 16 |

Enables or disables the specified control.

17 | 18 |
ControlSetEnabled NewSetting, Control , WinTitle, WinText, ExcludeTitle, ExcludeText
19 | 20 |

Parameters

21 |
22 | 23 |
NewSetting
24 |
25 |

Type: Integer

26 |

One of the following values:

27 |
    28 |
  • 1 or True turns on the setting
  • 29 |
  • 0 or False turns off the setting
  • 30 |
  • -1 toggles the setting (sets it to the opposite of its current state)
  • 31 |
32 |
33 |
Control
34 |
35 |

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.

37 |
38 |
WinTitle, WinText, ExcludeTitle, ExcludeText
39 |
40 |

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 |
45 |
46 | 47 |

Error Handling

48 |

A TargetError is thrown if the window or control could not be found.

49 | 50 |

Remarks

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 |

Related

54 |

ControlGetEnabled, WinSetEnabled, Enabled property (GuiControl object), Control functions

55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /docs/lib/ControlSetStyle.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlSetStyle / ControlSetExStyle - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlSetStyle / ControlSetExStyle

15 | 16 |

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, ExcludeText
20 | 21 |

Parameters

22 |
23 |
Value
24 |
25 |

Type: Integer or String

26 |

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 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 |
OperationPrefixExampleFormula
Add+"+0x80"NewStyle := CurrentStyle | Value
Remove-"-0x80"NewStyle := CurrentStyle & ~Value
Toggle^"^0x80"NewStyle := CurrentStyle ^ Value
54 |

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.

56 |
57 |
Control
58 |
59 |

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.

61 |
62 |
WinTitle, WinText, ExcludeTitle, ExcludeText
63 |
64 |

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 |
69 |
70 | 71 |

Error Handling

72 |

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 |

Remarks

76 |

See the styles table for a partial listing of styles.

77 |

Certain style changes require that the entire window be redrawn using WinRedraw.

78 |

ControlSetExStyle only changes generic extended styles, such as WS_EX_CLIENTEDGE (0x200). To change control-specific extended styles, use SendMessage, e.g. SendMessage(0x1036, 0, 0x1, MyListView) where 0x1036 is LVM_SETEXTENDEDLISTVIEWSTYLE and 0x1 is LVS_EX_GRIDLINES. Note that when creating a ListView with AutoHotkey, extended ListView styles can also be specified with the LV option.

79 | 80 |

Related

81 |

ControlGetStyle / ControlGetExStyle, WinSetStyle / WinSetExStyle, styles table, Control functions

82 | 83 |

Examples

84 |
85 |

Sets the WS_BORDER style of the Notepad's Edit control to its opposite state.

86 |
ControlSetStyle("^0x800000", "Edit1", "ahk_class Notepad")
87 |
88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /docs/lib/ControlSetText.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlSetText - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ControlSetText

14 | 15 |

Changes the text of a control.

16 | 17 |
ControlSetText NewText, Control , WinTitle, WinText, ExcludeTitle, ExcludeText
18 |

Parameters

19 |
20 | 21 |
NewText
22 |
23 |

Type: String

24 |

The new text to set into the control.

25 |
26 | 27 |
Control
28 |
29 |

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.

31 |
32 | 33 |
WinTitle, WinText, ExcludeTitle, ExcludeText
34 |
35 |

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 |
40 | 41 |
42 | 43 |

Error Handling

44 |

A TargetError is thrown if the window or control could not be found.

45 | 46 |

Remarks

47 |

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 |

Related

52 |

SetControlDelay, ControlGetText, Control functions

53 |

Examples

54 |
55 |

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 |
58 |
59 |

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 |
64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /docs/lib/ControlShow.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlShow - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlShow

15 | 16 |

Shows the specified control if it was previously hidden.

17 | 18 |
ControlShow Control , WinTitle, WinText, ExcludeTitle, ExcludeText
19 | 20 |

Parameters

21 |
22 |
Control
23 |
24 |

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.

26 |
27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 |
35 | 36 |

Error Handling

37 |

A TargetError is thrown if the window or control could not be found.

38 | 39 |

Remarks

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.

41 | 42 |

Related

43 |

ControlHide, ControlGetVisible, WinShow, Visible property (GuiControl object), Control functions

44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /docs/lib/ControlShowDropDown.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ControlShowDropDown - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ControlShowDropDown

15 | 16 |

Shows the drop-down list of a ComboBox control.

17 | 18 |
ControlShowDropDown Control , WinTitle, WinText, ExcludeTitle, ExcludeText
19 | 20 |

Parameters

21 |
22 |
Control
23 |
24 |

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.

26 |
27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 |
35 | 36 |

Error Handling

37 |

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 |

Remarks

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 |

Related

44 |

ControlHideDropDown, Control functions

45 | 46 |

Examples

47 |
48 |

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 |
57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /docs/lib/CoordMode.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | CoordMode - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

CoordMode

14 | 15 |

Sets coordinate mode for various built-in functions to be relative to either the active window or the screen.

16 | 17 |
CoordMode TargetType , RelativeTo
18 |

Parameters

19 |
20 | 21 |
TargetType
22 |
23 |

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 |
31 | 32 |
RelativeTo
33 |
34 |

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 |
40 | 41 |
42 | 43 |

Return Value

44 |

Type: String

45 |

This function returns the previous setting; either Screen, Window or Client.

46 | 47 |

Remarks

48 |

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 |

Related

52 |

Click, MouseMove, MouseClick, MouseClickDrag, MouseGetPos, PixelGetColor, PixelSearch, ToolTip, Menu.Show

53 |

Examples

54 |
55 |

Places tooltips at absolute screen coordinates.

56 |
CoordMode "ToolTip", "Screen"
57 |
58 |
59 |

Same effect as the above because "Screen" is the default.

60 |
CoordMode "ToolTip"
61 |
62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /docs/lib/Critical.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Critical - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Critical

14 | 15 |

Prevents the current thread from being interrupted by other threads, or enables it to be interrupted.

16 | 17 |
18 | Critical OnOffNumeric
19 | 20 |

Parameters

21 |
22 |
OnOffNumeric
23 |
24 |

Type: String or Integer

25 |

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 |
30 |
31 | 32 |

Return Value

33 |

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 |

Behavior of Critical Threads

37 |

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 |

Critical Off

41 |

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.

42 |

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.

43 | 44 |

Thread Settings

45 |

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.

46 |

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 |

Message Check Interval

50 |

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)).

51 |

This setting affects the following:

52 |
    53 |
  • Preemptive message checks, which potentially occur before each line of code executes.
  • 54 |
  • Periodic message checks during Send, file and download operations.
  • 55 |
56 |

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.

60 | 61 |

Related

62 |

Thread (function), Threads, #MaxThreadsPerHotkey, #MaxThreadsBuffer, OnMessage, CallbackCreate, Hotkey, Menu object, SetTimer

63 | 64 |

Examples

65 |
66 |

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 |
76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /docs/lib/DateAdd.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DateAdd - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DateAdd

15 | 16 |

Adds or subtracts time from a date-time value.

17 | 18 |
Result := DateAdd(DateTime, Time, TimeUnits)
19 |

Parameters

20 |
21 | 22 |
DateTime
23 |
24 |

Type: String

25 |

A date-time stamp in the YYYYMMDDHH24MISS format.

26 |
27 | 28 |
Time
29 |
30 |

Type: Integer or Float

31 |

The amount of time to add, as an integer or floating-point number. Specify a negative number to perform subtraction.

32 |
33 | 34 |
TimeUnits
35 |
36 |

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.

38 | 39 |
40 | 41 |

Return Value

42 |

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 |

Remarks

46 |

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 |

Related

51 |

DateDiff, FileGetTime, FormatTime

52 | 53 |

Examples

54 |
55 |

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 |
61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /docs/lib/DateDiff.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DateDiff - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DateDiff

15 | 16 |

Compares two date-time values and returns the difference.

17 | 18 |
Result := DateDiff(DateTime1, DateTime2, TimeUnits)
19 |

Parameters

20 |
21 | 22 |
DateTime1, DateTime2
23 |
24 |

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 |
28 | 29 |
TimeUnits
30 |
31 |

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 |
34 | 35 |
36 | 37 |

Return Value

38 |

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 |

Remarks

43 |

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 |

Related

49 |

DateAdd, FileGetTime, FormatTime

50 |

Examples

51 |
52 |

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 |
58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /docs/lib/DetectHiddenText.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DetectHiddenText - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

DetectHiddenText

14 | 15 |

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 |

Parameters

19 |
20 | 21 |
Mode
22 |
23 |

Type: Boolean

24 |

If true, hidden text is detected.

25 |

If false, hidden text is not detected.

26 |
27 | 28 |
29 | 30 |

Return Value

31 |

Type: Integer (boolean)

32 |

This function returns the previous setting; either 0 (false) or 1 (true).

33 | 34 |

Remarks

35 |

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 |

Related

40 |

DetectHiddenWindows

41 |

Examples

42 |
43 |

Turns off the detection of hidden text.

44 |
DetectHiddenText false
45 |
46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /docs/lib/DetectHiddenWindows.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DetectHiddenWindows - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

DetectHiddenWindows

14 | 15 |

Determines whether invisible windows are "seen" by the script.

16 | 17 |
DetectHiddenWindows Mode
18 |

Parameters

19 |
20 | 21 |
Mode
22 |
23 |

Type: Boolean

24 |

If true, hidden windows are detected.

25 |

If false, hidden windows are not detected, except by the WinShow function.

26 |
27 | 28 |
29 | 30 |

Return Value

31 |

Type: Integer (boolean)

32 |

This function returns the previous setting; either 0 (false) or 1 (true).

33 | 34 |

Remarks

35 |

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 |
    40 |
  • When using a pure HWND (as an Integer or an Object with a HWND property), as in WinShow(A_ScriptHwnd) or WinMoveTop(myGui), except with WinWait or WinWaitClose.
  • 41 |
  • When accessing a control or child window via the ahk_id method or as the last-found-window.
  • 42 |
  • When accessing GUI windows via the +LastFound option.
  • 43 |
44 |

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 |

Related

48 |

DetectHiddenText

49 |

Examples

50 |
51 |

Turns on the detection of hidden windows.

52 |
DetectHiddenWindows true
53 |
54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /docs/lib/DirCopy.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DirCopy - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DirCopy

15 | 16 |

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 , Overwrite
19 |

Parameters

20 |
21 | 22 |
Source
23 |
24 |

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 |
28 | 29 |
Dest
30 |
31 |

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 |
34 | 35 |
Overwrite
36 |
37 |

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 |
43 | 44 |
45 | 46 |

Error Handling

47 |

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 |

Remarks

51 |

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 |

Related

55 |

DirMove, FileCopy, FileMove, FileDelete, file loops, DirSelect, SplitPath

56 |

Examples

57 |
58 |

Copies a directory to a new location.

59 |
DirCopy "C:\My Folder", "C:\Copy of My Folder"
60 |
61 | 62 |
63 |

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 | return
81 |
82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /docs/lib/DirCreate.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DirCreate - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DirCreate

15 | 16 |

Creates a folder.

17 | 18 |
DirCreate DirName
19 |

Parameters

20 |
21 | 22 |
DirName
23 |
24 |

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 |
27 | 28 |
29 | 30 |

Error Handling

31 |

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 |

Remarks

35 |

This function will also create all parent directories given in DirName if they do not already exist.

36 |

Related

37 |

DirDelete

38 |

Examples

39 |
40 |

Creates a new directory, including its parent directories if necessary.

41 |
DirCreate "C:\Test1\My Images\Folder2"
42 |
43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /docs/lib/DirDelete.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DirDelete - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DirDelete

15 | 16 |

Deletes a folder.

17 | 18 |
DirDelete DirName , Recurse
19 |

Parameters

20 |
21 | 22 |
DirName
23 |
24 |

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 |
27 | 28 |
Recurse
29 |
30 |

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 |
35 | 36 |
37 | 38 |

Error Handling

39 |

An exception is thrown if an error occurs.

40 | 41 |

Related

42 |

DirCreate, FileDelete

43 |

Examples

44 |
45 |

Removes the directory, but only if it is empty.

46 |
DirDelete "C:\Download Temp"
47 |
48 | 49 |
50 |

Removes the directory including its files and subdirectories.

51 |
DirDelete "C:\Download Temp", true
52 |
53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /docs/lib/DirExist.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DirExist - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DirExist

15 | 16 |

Checks for the existence of a folder and returns its attributes.

17 | 18 |
AttributeString := DirExist(FilePattern)
19 |

Parameters

20 |
21 | 22 |
FilePattern
23 |
24 |

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.

26 |

Both asterisks (*) and question marks (?) are supported as wildcards. * matches zero or more characters and ? matches any single character. Usage examples:

27 |
    28 |
  • * matches all folders.
  • 29 |
  • gr?y matches e.g. gray and grey.
  • 30 |
  • *report* matches any folder name containing the word "report".
  • 31 |
32 |
33 | 34 |
35 | 36 |

Return Value

37 |

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:

39 |
    40 |
  • R = READONLY
  • 41 |
  • A = ARCHIVE
  • 42 |
  • S = SYSTEM
  • 43 |
  • H = HIDDEN
  • 44 |
  • D = DIRECTORY
  • 45 |
  • O = OFFLINE
  • 46 |
  • C = COMPRESSED
  • 47 |
48 |

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 |

Remarks

51 |

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.

52 |

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.

54 |

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.

55 | 56 |

Related

57 |

FileExist, FileGetAttrib, file loops

58 | 59 |

Examples

60 |
61 |

Shows a message box if a folder does exist.

62 |
if DirExist("C:\Windows")
63 |     MsgBox "The target folder does exist."
64 |
65 | 66 |
67 |

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 |
71 | 72 |
73 |

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 |
77 | 78 |
79 |

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 |
83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /docs/lib/DirMove.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DirMove - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DirMove

15 | 16 |

Moves a folder along with all its sub-folders and files. It can also rename a folder.

17 | 18 |
DirMove Source, Dest , OverwriteOrRename
19 |

Parameters

20 |
21 | 22 |
Source
23 |
24 |

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 |
27 | 28 |
Dest
29 |
30 |

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 |
34 | 35 |
OverwriteOrRename
36 |
37 |

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 |
44 | 45 |
46 | 47 |

Error Handling

48 |

An exception is thrown if an error occurs.

49 | 50 |

Remarks

51 |

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 |

Related

54 |

DirCopy, FileCopy, FileMove, FileDelete, file loops, DirSelect, SplitPath

55 |

Examples

56 |
57 |

Moves a directory to a new drive.

58 |
DirMove "C:\My Folder", "D:\My Folder"
59 |
60 | 61 |
62 |

Performs a simple rename.

63 |
DirMove "C:\My Folder", "C:\My Folder (renamed)", "R"
64 |
65 | 66 |
67 |

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 |
70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /docs/lib/DirSelect.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DirSelect - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DirSelect

15 | 16 |

Displays a standard dialog that allows the user to select a folder.

17 | 18 |
SelectedFolder := DirSelect(StartingFolder, Options, Prompt)
19 |

Parameters

20 |
21 | 22 |
StartingFolder
23 |
24 |

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.

26 |

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.

27 |

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).

29 |
30 | 31 |
Options
32 |
33 |

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 |
41 | 42 |
Prompt
43 |
44 |

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.

46 |
47 | 48 |
49 | 50 |

Return Value

51 |

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 |

Remarks

57 |

A folder-selection dialog usually looks like this:

58 | DirSelect 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 |

Related

62 |

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 |

Examples

65 |
66 |

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 |
73 | 74 |
75 |

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 |
78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /docs/lib/DllCall.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DllCall - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

DllCall

14 | 15 |

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 |

Parameters

19 |
20 | 21 |
[DllFile\]Function
22 |
23 |

Type: String or Integer

24 |

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.

25 |

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".

26 |

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".

27 |

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.

30 |
31 | 32 |
Type1, Arg1
33 |
34 |

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 |
37 | 38 |
Cdecl ReturnType
39 |
40 |

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".

43 |

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 |
46 | 47 |
48 | 49 |

Return Value

50 |

Type: String or Integer

51 |

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 |

Types of Arguments and Return Values

54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 123 | 124 | 125 | 127 | 132 | 133 | 134 | 135 | 139 | 140 | 141 | 142 | 146 | 147 |
TypeDescription
Str 62 |

A string such as "Blue" or MyVar, or a VarRef such as &MyVar. If the called function modifies the string and the argument is a naked variable or VarRef, its contents will be updated. For example, the following call would convert the contents of MyVar to uppercase: DllCall("CharUpper", "Str", MyVar).

63 |

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 VarSetStrCapacity(&MyVar, 123), where 123 is the number of 16-bit units (loosely referred to as characters) that MyVar must be able to hold. If the variable is not null-terminated upon return, an error message is shown and the program exits as it is likely that memory has been corrupted via buffer overrun. This would typically indicate that the variable's capacity was insufficient.

65 |

A Str argument must not be an expression that evaluates to a number (such as i+1). If it is, the function is not called and a TypeError is thrown.

66 |

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 Ptr* arg type must be used instead.

67 |

Note: When passing a string to a function, be aware what type of string the function expects.

WStrSince AutoHotkey uses UTF-16 natively, WStr (wide character string) is equivalent to Str.
AStr 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 |
Int64A 64-bit integer, whose range is -9223372036854775808 (-0x8000000000000000) to 9223372036854775807 (0x7FFFFFFFFFFFFFFF).
Int

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.

ShortA 16-bit integer, whose range is -32768 (-0x8000) to 32767 (0x7FFF). An unsigned Short (UShort) can be used with functions that expect a WORD.
CharAn 8-bit integer, whose range is -128 (-0x80) to 127 (0x7F). An unsigned character (UChar) can be used with functions that expect a BYTE.
FloatA 32-bit floating point number, which provides 6 digits of precision.
DoubleA 64-bit floating point number, which provides 15 digits of precision.
Ptr

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 Ptr property is used. If no such property exists, a PropertyError is thrown. Typically the object would be a Buffer.

115 |

If an object is passed to a Ptr* parameter, the value of the object's Ptr property is retrieved before the call and the address of a temporary variable containing this value is passed to the function. After the function returns, the new value is assigned back to the object's Ptr property.

116 |

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 |
    119 |
  • It is only unsigned in 32-bit builds as AutoHotkey does not support unsigned 64-bit integers.
  • 120 |
  • Objects are not permitted.
  • 121 |
122 |

Note: To pass a NULL handle or pointer, pass the integer 0.

* or P
126 | (suffix)

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: DllCall("MyDll\MyFunction", "Int*", &MyVar).

128 |

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 |
U (prefix)

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 |
HRESULT 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 |
148 | 149 |

Errors

150 |

DllCall throws an Error under any of the following conditions:

151 |
    152 |
  • OSError: The HRESULT return type was used and the function returned an error value (as defined by the FAILED macro). Exception.Extra contains the hexadecimal error code.
  • 153 |
  • TypeError: The [DllFile\]Function parameter is a floating point number. A string or positive integer is required.
  • 154 |
  • ValueError: The return type or one of the specified arg types is invalid.
  • 155 |
  • TypeError: An argument was passed a value of an unexpected type. For instance, an expression that evaluates to a number was passed to a string (str) argument, a non-numeric string was passed to a numeric argument, or an object was passed to an argument not of type Ptr.
  • 156 |
  • Error: The specified DllFile could not be accessed or loaded. If no explicit path was specified for DllFile, the file must exist in the system's PATH or A_WorkingDir. This error might also occur if the user lacks permission to access the file, or if AutoHotkey is 32-bit and the DLL is 64-bit or vice versa.
  • 157 |
  • Error: The specified function could not be found inside the DLL.
  • 158 |
  • Error: The function was called but it aborted with a fatal exception. 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.
  • 159 |
  • Error: The function was called but was passed too many or too few arguments. 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.
  • 160 |
161 | 162 |

Native Exceptions and A_LastError

163 |

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 |

Performance

167 |

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.

178 |

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").

179 | 180 |

Structures and Arrays

181 |

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.

184 |

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.

185 |

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.

186 |

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.

187 |

See Structure Examples for actual usages.

188 | 189 |

Known Limitations

190 |

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.

191 |

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:

193 |
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 |

Component Object Model (COM)

199 |

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

203 |

.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 |

Related

207 |

Binary Compatibility, Buffer object, ComCall, PostMessage, OnMessage, CallbackCreate, Run, VarSetStrCapacity, Functions, SysGet, #DllLoad, Windows API Index

208 | 209 |

Examples

210 |
211 |

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 #" WhichButton
214 |
215 | 216 |
217 |

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 |
220 | 221 |
222 |

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 |
227 | 228 |
229 |

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 |
238 | 239 |
240 |

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 |
247 | 248 |
249 |

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 |
273 | 274 |
275 |

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 |
288 | 289 |
290 |

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 |
325 | 326 |
327 |

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 |
367 | 368 |
369 |

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 |
378 | 379 |
380 |

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 |
393 | 394 |
395 |

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 |
    424 |
  • See the WinLIRC client script for a demonstration of how to use DllCall to make a network connection to a TCP/IP server and receive data from it.
  • 425 |
  • The operating system offers standard dialog boxes that prompt the user to pick a font, color, or icon. These dialogs use structures and can be displayed via DllCall in combination with comdlg32\ChooseFont, comdlg32\ChooseColor, or shell32\PickIconDlg. Search the forums for examples.
  • 426 |
427 |
428 | 429 |
430 |

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 |
467 | 468 | 469 | 470 | -------------------------------------------------------------------------------- /docs/lib/Download.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Download - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Download

15 | 16 |

Downloads a file from the Internet.

17 | 18 |
Download URL, Filename 
19 |

Parameters

20 |
21 | 22 |
URL
23 |
24 |

Type: String

25 |

URL of the file to download. For example, "https://someorg.org" might retrieve the welcome page for that organization.

26 |
27 | 28 |
Filename
29 |
30 |

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 |
34 | 35 |
36 | 37 |

Error Handling

38 |

An exception is thrown on failure.

39 | 40 |

Remarks

41 |

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.

44 |

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 |

Related

51 |

FileRead, FileCopy

52 | 53 |

Examples

54 |
55 |

Downloads a text file.

56 |
Download "https://www.autohotkey.com/download/2.0/version.txt", "C:\AutoHotkey Latest Version.txt"
57 |
58 | 59 |
60 |

Downloads a zip file.

61 |
Download "https://someorg.org/archive.zip", "C:\SomeOrg's Archive.zip"
62 |
63 | 64 |
65 |

Downloads text to a variable.

66 |
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 |
75 | 76 |
77 |

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 |
105 | 106 | 107 | 108 | -------------------------------------------------------------------------------- /docs/lib/Drive.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | List of Drive Functions | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Drive Functions

14 | 15 |

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 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 |
FunctionDescription
DriveEjectEjects the tray of the specified CD/DVD drive, or ejects a removable drive.
DriveGetCapacityReturns the total capacity of the drive which contains the specified path, in megabytes.
DriveGetFileSystemReturns the type of the specified drive's file system.
DriveGetLabelReturns the volume label of the specified drive.
DriveGetListReturns a string of letters, one character for each drive letter in the system.
DriveGetSerialReturns the volume serial number of the specified drive.
DriveGetSpaceFreeReturns the free disk space of the drive which contains the specified path, in megabytes.
DriveGetStatusReturns the status of the drive which contains the specified path.
DriveGetStatusCDReturns the media status of the specified CD/DVD drive.
DriveGetTypeReturns the type of the drive which contains the specified path.
DriveLockPrevents the eject feature of the specified drive from working.
DriveRetractRetracts the tray of the specified CD/DVD drive.
DriveSetLabelChanges the volume label of the specified drive.
DriveUnlockRestores the eject feature of the specified drive.
78 | 79 |

Error Handling

80 |

An exception is thrown on failure.

81 | 82 |

Related

83 |

List of all functions

84 | 85 |

Examples

86 | 87 |
88 |

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 |
105 | 106 | 107 | 108 | -------------------------------------------------------------------------------- /docs/lib/DriveEject.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DriveEject / DriveRetract - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DriveEject / DriveRetract

15 | 16 |

Ejects or retracts the tray of the specified CD/DVD drive. DriveEject can also eject a removable drive.

17 | 18 |
DriveEject Drive
19 | DriveRetract Drive
20 | 21 |

Parameters

22 |
23 |
Drive
24 | 25 |
26 |

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:\".

28 |

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.

29 |
30 |
31 | 32 |

Error Handling

33 |

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 |

Remarks

37 |

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 |

Related

44 |

DriveGetStatusCD, Drive functions

45 | 46 |

Examples

47 | 48 |
49 |

Ejects (opens) the tray of the first CD/DVD drive.

50 |
DriveEject()
51 |
52 | 53 |
54 |

Retracts (closes) the tray of the first CD/DVD drive.

55 |
DriveRetract()
56 |
57 | 58 |
59 |

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 |
68 | 69 |
70 |

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 |
80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /docs/lib/DriveGetCapacity.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DriveGetCapacity - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DriveGetCapacity

15 | 16 |

Returns the total capacity of the drive which contains the specified path, in megabytes.

17 | 18 |
Capacity := DriveGetCapacity(Path)
19 | 20 |

Parameters

21 |
22 |
Path
23 |
24 |

Type: String

25 |

Any path contained by the drive (might also work on UNC paths and mapped drives).

26 |
27 |
28 | 29 |

Return Value

30 |

Type: Integer

31 |

This function returns the total capacity of the drive which contains Path, in megabytes.

32 | 33 |

Error Handling

34 |

An exception is thrown on failure.

35 | 36 |

Remarks

37 |

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 |

Related

40 |

DriveGetSpaceFree, Drive functions

41 | 42 |

Examples

43 |

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 | DriveGetFileSystem - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DriveGetFileSystem

15 | 16 |

Returns the type of the specified drive's file system.

17 | 18 |
FileSystem := DriveGetFileSystem(Drive)
19 | 20 |

Parameters

21 |
22 |
Drive
23 |
24 |

Type: String

25 |

The drive letter followed by a colon and an optional backslash, or a UNC name such as "\server1\share1".

26 |
27 |
28 | 29 |

Return Value

30 |

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 |

Error Handling

34 |

An exception is thrown on failure, such as if the drive does not contain formatted media.

35 | 36 |

Related

37 |

Drive functions

38 | 39 |

Examples

40 |

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 | DriveGetLabel - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DriveGetLabel

15 | 16 |

Returns the volume label of the specified drive.

17 | 18 |
Label := DriveGetLabel(Drive)
19 | 20 |

Parameters

21 |
22 |
Drive
23 |
24 |

Type: String

25 |

The drive letter followed by a colon and an optional backslash, or a UNC name such as "\server1\share1".

26 |
27 |
28 | 29 |

Return Value

30 |

Type: String

31 |

This function returns the Drive's volume label.

32 | 33 |

Error Handling

34 |

An exception is thrown on failure.

35 | 36 |

Related

37 |

DriveSetLabel, Drive functions

38 | 39 |

Examples

40 |

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 | DriveGetList - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DriveGetList

15 | 16 |

Returns a string of letters, one character for each drive letter in the system.

17 | 18 |
List := DriveGetList(DriveType)
19 | 20 |

Parameters

21 |
22 |
DriveType
23 |
24 |

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 |
27 |
28 | 29 |

Return Value

30 |

Type: String

31 |

This function returns the drive letters in the system, depending on DriveType. For example: ACDEZ.

32 | 33 |

Related

34 |

Drive functions

35 | 36 |

Examples

37 |

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 | DriveGetSerial - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DriveGetSerial

15 | 16 |

Returns the volume serial number of the specified drive.

17 | 18 |
Serial := DriveGetSerial(Drive)
19 | 20 |

Parameters

21 |
22 |
Drive
23 |
24 |

Type: String

25 |

The drive letter followed by a colon and an optional backslash, or a UNC name such as "\server1\share1".

26 |
27 |
28 | 29 |

Return Value

30 |

Type: Integer

31 |

This function returns the Drive's volume serial number. See Format for how to convert it to hexadecimal.

32 | 33 |

Error Handling

34 |

An exception is thrown on failure.

35 | 36 |

Related

37 |

Drive functions

38 | 39 |

Examples

40 |

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 | DriveGetSpaceFree - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DriveGetSpaceFree

15 | 16 |

Returns the free disk space of the drive which contains the specified path, in megabytes.

17 | 18 |
FreeSpace := DriveGetSpaceFree(Path)
19 | 20 |

Parameters

21 |
22 |
Path
23 |
24 |

Type: String

25 |

Any path contained by the drive (might also work on UNC paths and mapped drives).

26 |
27 |
28 | 29 |

Return Value

30 |

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 |

Error Handling

34 |

An exception is thrown on failure.

35 | 36 |

Remarks

37 |

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 |

Related

40 |

DriveGetCapacity, Drive functions

41 | 42 |

Examples

43 |
44 |

Retrieves and reports the free disk space of the drive which contains A_MyDocuments.

45 |
FreeSpace := DriveGetSpaceFree(A_MyDocuments)
46 | MsgBox FreeSpace " MB"
47 |
48 |

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 | DriveGetStatus - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DriveGetStatus

15 | 16 |

Returns the status of the drive which contains the specified path.

17 | 18 |
Status := DriveGetStatus(Path)
19 | 20 |

Parameters

21 |
22 |
Path
23 |
24 |

Type: String

25 |

Any path contained by the drive (might also work on UNC paths and mapped drives).

26 |
27 |
28 | 29 |

Return Value

30 |

Type: String

31 |

This function returns the status of the drive which contains Path:

32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 |
StatusNotes
UnknownMight indicate unformatted/RAW file system.
ReadyThis is the most common.
NotReadyTypical for removable drives that don't contain media.
InvalidPath does not exist or is a network drive that is presently inaccessible, etc.
54 | 55 |

Error Handling

56 |

An exception is thrown on failure.

57 | 58 |

Remarks

59 |

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 |

Related

62 |

Drive functions

63 | 64 |

Examples

65 |

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 | DriveGetStatusCD - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DriveGetStatusCD

15 | 16 |

Returns the media status of the specified CD/DVD drive.

17 | 18 |
CDStatus := DriveGetStatusCD(Drive)
19 | 20 |

Parameters

21 |
22 |
Drive
23 |
24 |

Type: String

25 |

If omitted, the default CD/DVD drive will be used. Otherwise, specify the drive letter followed by a colon.

26 |
27 |
28 | 29 |

Return Value

30 |

Type: String

31 |

This function returns the Drive's media status:

32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 |
StatusMeaning
not readyThe 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.
openThe drive contains no disc, or the tray is ejected.
playingThe drive is playing a disc.
pausedThe previously playing audio or video is now paused.
seekingThe drive is seeking.
stoppedThe drive contains a CD but is not currently accessing it.
62 | 63 |

Error Handling

64 |

An exception is thrown on failure.

65 | 66 |

Remarks

67 |

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 |

Related

71 |

DriveEject, Drive functions

72 | 73 |

Examples

74 |

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 | DriveGetType - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DriveGetType

15 | 16 |

Returns the type of the drive which contains the specified path.

17 | 18 |
DriveType := DriveGetType(Path)
19 | 20 |

Parameters

21 |
22 |
Path
23 |
24 |

Type: String

25 |

Any path contained by the drive (might also work on UNC paths and mapped drives).

26 |
27 |
28 | 29 |

Return Value

30 |

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 |

Remarks

34 |

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 |

Related

37 |

Drive functions

38 | 39 |

Examples

40 |

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 | DriveLock - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DriveLock

15 | 16 |

Prevents the eject feature of the specified drive from working.

17 | 18 |
DriveLock Drive
19 | 20 |

Parameters

21 |
22 |
Drive
23 |
24 |

Type: String

25 |

The drive letter followed by a colon and an optional backslash (might also work on UNC paths and mapped drives).

26 |
27 |
28 | 29 |

Error Handling

30 |

An exception is thrown on failure, such as if Drive does not exist or does not support the locking feature.

31 | 32 |

Remarks

33 |

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 |

Related

38 |

DriveUnlock, Drive functions

39 | 40 |

Examples

41 |
42 |

Locks the D drive.

43 |
DriveLock "D:"
44 |
45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/lib/DriveSetLabel.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DriveSetLabel - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DriveSetLabel

15 | 16 |

Changes the volume label of the specified drive.

17 | 18 |
DriveSetLabel Drive , NewLabel
19 | 20 |

Parameters

21 |
22 |
Drive
23 |
24 |

Type: String

25 |

The drive letter followed by a colon and an optional backslash (might also work on UNC paths and mapped drives).

26 |
27 |
NewLabel
28 |
29 |

Type: String

30 |

If omitted, the drive will have no label. Otherwise, specify the new label to set.

31 |
32 |
33 | 34 |

Error Handling

35 |

An exception is thrown on failure.

36 | 37 |

Related

38 |

DriveGetLabel, Drive functions

39 | 40 |

Examples

41 |
42 |

Changes the volume label of the C drive.

43 |
DriveSetLabel "C:", "Seagate200"
44 |
45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/lib/DriveUnlock.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DriveUnlock - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

DriveUnlock

15 | 16 |

Restores the eject feature of the specified drive.

17 | 18 |
DriveUnlock Drive
19 | 20 |

Parameters

21 |
22 |
Drive
23 |
24 |

Type: String

25 |

The drive letter followed by a colon and an optional backslash (might also work on UNC paths and mapped drives).

26 |
27 |
28 | 29 |

Error Handling

30 |

An exception is thrown on failure.

31 | 32 |

Remarks

33 |

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.

34 | 35 |

Related

36 |

DriveLock, Drive functions

37 | 38 |

Examples

39 |
40 |

Unlocks the D drive.

41 |
DriveUnlock "D:"
42 |
43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /docs/lib/Edit.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Edit - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Edit

14 | 15 |

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 |

Related

24 |

Reload, How to edit a script, Editors with AutoHotkey support

25 | 26 |

Examples

27 |
28 |

Opens the script for editing.

29 |
Edit
30 |
31 | 32 |
33 |

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.

34 |
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 |
39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /docs/lib/EditGetCurrentCol.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | EditGetCurrentCol - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

EditGetCurrentCol

15 | 16 |

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 |

Parameters

21 |
22 |
Control
23 |
24 |

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.

26 |
27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 |
35 | 36 |

Return Value

37 |

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 |

Error Handling

41 |

An exception is thrown on failure, or if the window or control could not be found.

42 | 43 |

Related

44 |

EditGetCurrentLine, EditGetLineCount, EditGetLine, EditGetSelectedText, EditPaste, Control functions

45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/lib/EditGetCurrentLine.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | EditGetCurrentLine - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

EditGetCurrentLine

15 | 16 |

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 |

Parameters

21 |
22 |
Control
23 |
24 |

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.

26 |
27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 |
35 | 36 |

Return Value

37 |

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 |

Error Handling

41 |

An exception is thrown on failure, or if the window or control could not be found.

42 | 43 |

Related

44 |

EditGetCurrentCol, EditGetLineCount, EditGetLine, EditGetSelectedText, EditPaste, Control functions

45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/lib/EditGetLine.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | EditGetLine - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

EditGetLine

15 | 16 |

Returns the text of the specified line in an Edit control.

17 | 18 |
Line := EditGetLine(N, Control , WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
N
23 |
24 |

Type: Integer

25 |

The line number. Line 1 is the first line.

26 |
27 |
Control
28 |
29 |

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.

31 |
32 |
WinTitle, WinText, ExcludeTitle, ExcludeText
33 |
34 |

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 |
39 |
40 | 41 |

Return Value

42 |

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 |

Error Handling

46 |

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 |

Related

51 |

EditGetCurrentCol, EditGetCurrentLine, EditGetLineCount, EditGetSelectedText, EditPaste, Control functions

52 | 53 |

Examples

54 |
55 |

Retrieves the first line of the Notepad's Edit control.

56 |
line1 := EditGetLine(1, "Edit1", "ahk_class Notepad")
57 |
58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /docs/lib/EditGetLineCount.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | EditGetLineCount - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

EditGetLineCount

15 | 16 |

Returns the number of lines in an Edit control.

17 | 18 |
LineCount := EditGetLineCount(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
Control
23 |
24 |

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.

26 |
27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 |
35 | 36 |

Return Value

37 |

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 |

Error Handling

41 |

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 |

Related

45 |

EditGetCurrentCol, EditGetCurrentLine, EditGetLine, EditGetSelectedText, EditPaste, Control functions

46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /docs/lib/EditGetSelectedText.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | EditGetSelectedText - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

EditGetSelectedText

15 | 16 |

Returns the selected text in an Edit control.

17 | 18 |
SelectedText := EditGetSelectedText(Control , WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
Control
23 |
24 |

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.

26 |
27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 |
35 | 36 |

Return Value

37 |

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 |

Error Handling

41 |

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 |

Related

45 |

EditGetCurrentCol, EditGetCurrentLine, EditGetLineCount, EditGetLine, EditPaste, Control functions

46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /docs/lib/EditPaste.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | EditPaste - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

EditPaste

15 | 16 |

Pastes the specified string at the caret (text insertion point) in an Edit control.

17 | 18 |
EditPaste String, Control , WinTitle, WinText, ExcludeTitle, ExcludeText
19 | 20 |

Parameters

21 |
22 |
String
23 |
24 |

Type: String

25 |

The string to paste.

26 |
27 |
Control
28 |
29 |

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.

31 |
32 |
WinTitle, WinText, ExcludeTitle, ExcludeText
33 |
34 |

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 |
39 |
40 | 41 |

Error Handling

42 |

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 |

Remarks

46 |

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 |

Related

50 |

ControlSetText, Control functions

51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /docs/lib/Else.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Else - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Else

14 |

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 |

Remarks

22 |

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 |
    24 |
  • If expression: The expression evaluated to false.
  • 25 |
  • For, Loop (any kind), While: The loop had zero iterations.
  • 26 |
  • Loop Read: As above, but the presence of Else also prevents an error from being thrown if the file or path is not found. Therefore, Else executes if the file is empty or does not exist.
  • 27 |
  • Try...Catch: No exception was thrown within the Try block.
  • 28 |
29 |

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 |

Related

48 |

Blocks, If, Control Flow Statements

49 | 50 |

Examples

51 |
52 |

Common usage of an Else statement. This example is executed as follows:

53 |
    54 |
  1. If Notepad exists: 55 |
      56 |
    1. Activate it
    2. 57 |
    3. Send the string "This is a test." followed by Enter.
    4. 58 |
    59 |
  2. 60 |
  3. Otherwise (that is, if Notepad does not exist): 61 |
      62 |
    1. Activate another window
    2. 63 |
    3. Left-click at the coordinates 100, 200
    4. 64 |
    65 |
  4. 66 |
67 |
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 |
78 | 79 |
80 |

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 |
92 | 93 |
94 |

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 |
103 | 104 | 105 | 106 | -------------------------------------------------------------------------------- /docs/lib/Enumerator.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Enumerator Object - Definition & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Enumerator Object

14 | 15 |

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.

18 | 19 |

Table of Contents

20 |
    21 |
  • Methods: 22 |
      23 |
    • Call: Retrieves the next item or items in an enumeration.
    • 24 |
    25 |
  • 26 |
  • Related
  • 27 |
28 | 29 |

Methods

30 | 31 |

Call

32 |

Retrieves the next item or items in an enumeration.

33 |
Boolean := Enum.Call(&OutputVar1 , &OutputVar2)
34 |
Boolean := EnumFunction(&OutputVar1 , &OutputVar2)
35 |

Parameters

36 |
37 |
&OutputVar1, &OutputVar2
38 |
39 |

Type: VarRef

40 |

One or more references to output variables for the enumerator to assign values.

41 |
42 |
43 |

Return Value

44 |

Type: Integer (boolean)

45 |

This method returns 1 (true) if successful or 0 (false) if there were no items remaining.

46 |

Remarks

47 |

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 |
51 | 52 |

Related

53 |

For-loop, OwnProps, __Enum (Array), __Enum (Map)

54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /docs/lib/EnvGet.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | EnvGet - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

EnvGet

14 | 15 |

Retrieves the value of the specified environment variable.

16 | 17 |
Value := EnvGet(EnvVar)
18 |

Parameters

19 |
20 | 21 |
EnvVar
22 |
23 |

Type: String

24 |

The name of the environment variable, e.g. "Path".

25 |
26 | 27 |
28 | 29 |

Return Value

30 |

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 |

Remarks

34 |

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 |

Related

37 |

EnvSet, Run / RunWait

38 |

Examples

39 |
40 |

Retrieves the value of an environment variable and stores it in LogonServer.

41 |
LogonServer := EnvGet("LogonServer")
42 |
43 | 44 |
45 |

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: " ProgramFilesDir
48 |
49 | 50 |
51 |

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: " LocalAppData
54 |
55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /docs/lib/EnvSet.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | EnvSet - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

EnvSet

14 | 15 |

Writes a value to the specified environment variable.

16 | 17 |
EnvSet EnvVar , Value
18 |

Parameters

19 |
20 | 21 |
EnvVar
22 |
23 |

Type: String

24 |

The name of the environment variable, e.g. "Path".

25 |
26 | 27 |
Value
28 |
29 |

Type: String

30 |

If omitted, the environment variable will be deleted. Otherwise, specify the value to write.

31 |
32 | 33 |
34 | 35 |

Error Handling

36 |

An OSError is thrown on failure.

37 | 38 |

Remarks

39 |

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 |

Related

43 |

EnvGet, Run / RunWait

44 |

Examples

45 |
46 |

Writes some text to an environment variable.

47 |
EnvSet "AutGUI", "Some text to put in the environment variable."
48 |
49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /docs/lib/Error.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Error Object | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Error Object

15 |
class Error extends Object
16 | 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 |

Table of Contents

20 |
    21 |
  • Standard Properties
  • 22 |
  • Error()
  • 23 |
  • Error Types
  • 24 |
  • Related
  • 25 |
26 | 27 |

Standard Properties

28 |

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 |
35 |
File (Line) : [What] SourceCode`r`n
36 |
Represents a call to the function What. File and Line indicate the current script line at this stack depth. SourceCode is an approximation of the source code at that line, as it would be shown in ListLines.
37 |
> What`r`n
38 |
Represents the launching of a thread, typically the direct cause of the function call above it.
39 |
... N more
40 |
Indicates that the stack trace was truncated, and there are N more stack entries not shown. Currently the Stack property cannot exceed 2047 characters.
41 |
42 | 43 |

Note: The standard error dialog requires Message, Extra, File and Line to be own value properties.

44 | 45 |

Error()

46 |

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:

52 |
    53 |
  • NewError.What contains the name of the function.
  • 54 |
  • NewError.Line and NewError.File indicate the line which called the function.
  • 55 |
  • NewError.Stack contains a partial stack trace, with the indicated stack frame at the top.
  • 56 |
57 |

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 |

Error Types

83 | 84 |

The following subclasses of Error are predefined:

85 |
    86 |
  • MemoryError: A memory allocation failed.
  • 87 |
  • OSError: An internal function call to a Win32 function failed. Message includes an error code and description generated by the operating system. OSErrors have an additional Number property which contains the error code. Calling 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."
  • 88 |
  • TargetError: A function failed because its target could not be found. Message indicates what kind of target, such as a window, control, menu or status bar.
  • 89 |
  • TimeoutError: SendMessage timed out.
  • 90 |
  • TypeError: An unexpected type of value was used as input for a function, property assignment, or some other operation. Usually Message indicates the expected and actual type, and Extra contains a string representing the errant value.
  • 91 |
  • UnsetError: An attempt was made to read the value of a variable, property or item, but there was no value.
      92 |
    • MemberError
        93 |
      • PropertyError
      • 94 |
      • MethodError
      • 95 |
    • 96 |
    • UnsetItemError
    • 97 |
  • 98 |
  • ValueError: An unexpected value was used as input for a function, property assignment, or some other operation. Usually Message indicates which expectation was broken, and Extra contains a string representing the errant value.
      99 |
    • IndexError: The index parameter of an object's __Item property was invalid or out of range.
    • 100 |
  • 101 |
  • ZeroDivisionError: Division by zero was attempted in an expression or with the Mod function.
  • 102 |
103 |

Errors are also thrown using the base Error class.

104 | 105 |

Related

106 |

Throw, Try, Catch, Finally, OnError

107 | 108 | 109 | -------------------------------------------------------------------------------- /docs/lib/Exit.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exit - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Exit

14 | 15 |

Exits the current thread.

16 | 17 |
Exit ExitCode
18 |

Parameters

19 |
20 | 21 |
ExitCode
22 |
23 |

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 |
26 | 27 |
28 | 29 |

Remarks

30 |

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 |

Related

36 |

ExitApp, OnExit, Functions, Return, Threads, Persistent

37 |

Examples

38 |
39 |

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 |
52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /docs/lib/ExitApp.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ExitApp - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ExitApp

14 | 15 |

Terminates the script.

16 | 17 |
ExitApp ExitCode
18 |

Parameters

19 |
20 | 21 |
ExitCode
22 |
23 |

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 |
26 | 27 |
28 | 29 |

Remarks

30 |

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 |

Related

36 |

Exit, OnExit, Persistent

37 | 38 |

Examples

39 |
40 |

Press a hotkey to terminate the script.

41 |
#x::ExitApp  ; Win+X
42 |
43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /docs/lib/File.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | File Object - Methods & Properties | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

File Object

14 |
class File extends Object
15 | 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 |

Table of Contents

22 |
    23 |
  • Methods: 24 |
      25 |
    • Read: Reads a string of characters from the file and advances the file pointer.
    • 26 |
    • Write: Writes a string of characters to the file and advances the file pointer.
    • 27 |
    • ReadLine: Reads a line of text from the file and advances the file pointer.
    • 28 |
    • WriteLine: Writes a line of text to the file and advances the file pointer.
    • 29 |
    • ReadNumType: Reads a number from the file and advances the file pointer.
    • 30 |
    • WriteNumType: Writes a number to the file and advances the file pointer.
    • 31 |
    • RawRead: Reads raw binary data from the file into memory and advances the file pointer.
    • 32 |
    • RawWrite: Writes raw binary data to the file and advances the file pointer.
    • 33 |
    • Seek: Moves the file pointer.
    • 34 |
    • Close: Closes the file, flushes any data in the cache to disk and releases the share locks.
    • 35 |
    36 |
  • 37 |
  • Properties: 38 |
      39 |
    • Pos: Retrieves or sets the position of the file pointer.
    • 40 |
    • Length: Retrieves or sets the size of the file.
    • 41 |
    • AtEOF: Retrieves a non-zero number if the file pointer has reached the end of the file.
    • 42 |
    • Encoding: Retrieves or sets the text encoding used by this file object.
    • 43 |
    • Handle: Retrieves a system file handle, intended for use with DllCall.
    • 44 |
    45 |
  • 46 |
47 | 48 |

Methods

49 | 50 |

Read

51 |

Reads a string of characters from the file and advances the file pointer.

52 |
String := FileObj.Read(Characters)
53 |

Parameters

54 |
55 |
Characters
56 |
57 |

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 |
60 |
61 |

Return Value

62 |

Type: String

63 |

This method returns the string of characters that were read.

64 |
65 | 66 |

Write

67 |

Writes a string of characters to the file and advances the file pointer.

68 |
BytesWritten := FileObj.Write(String)
69 |

Parameters

70 |
71 |
String
72 |
73 |

Type: String

74 |

The string to write.

75 |
76 |
77 |

Return Value

78 |

Type: Integer

79 |

This method returns the number of bytes (not characters) that were written.

80 |
81 | 82 |

ReadLine

83 |

Reads a line of text from the file and advances the file pointer.

84 |
TextLine := FileObj.ReadLine()
85 |

Return Value

86 |

Type: String

87 |

This method returns a line of text, excluding the line ending.

88 |

Remarks

89 |

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.

90 | 91 |

WriteLine

92 |

Writes a line of text to the file and advances the file pointer.

93 |
BytesWritten := FileObj.WriteLine(String)
94 |

Parameters

95 |
96 |
String
97 |
98 |

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.

100 |
101 |
102 |

Return Value

103 |

Type: Integer

104 |

This method returns the number of bytes (not characters) that were written.

105 |
106 | 107 |

ReadNumType

108 |

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 |

Return Value

112 |

Type: Integer, Float or String (empty)

113 |

On success, this method returns a number. On failure, it returns an empty string.

114 |

Remarks

115 |

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 |
117 | 118 |

WriteNumType

119 |

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 |

Parameters

123 |
Num
124 |
125 |

Type: Integer or Float

126 |

The number to write.

127 |
128 |
129 |

Return Value

130 |

Type: Integer

131 |

This method returns the number of bytes that were written. For example, FileObj.WriteUInt(42) returns 4 if successful.

132 |
133 | 134 |

RawRead

135 |

Reads raw binary data from the file into memory and advances the file pointer.

136 |
BytesRead := FileObj.RawRead(Buffer , Bytes)
137 |

Parameters

138 |
139 |
Buffer
140 |
141 |

Type: Object or Integer

142 |

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 |
146 |
Bytes
147 |
148 |

Type: Integer

149 |

The maximum number of bytes to read. This is optional when Buffer is an object; otherwise, it is required.

150 |
151 |
152 |

Return Value

153 |

Type: Integer

154 |

This method returns the number of bytes that were read.

155 |
156 | 157 |

RawWrite

158 |

Writes raw binary data to the file and advances the file pointer.

159 |
BytesWritten := FileObj.RawWrite(Data , Bytes)
160 |

Parameters

161 |
162 |
Data
163 |
164 |

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 |
167 |
Bytes
168 |
169 |

Type: Integer

170 |

The number of bytes to write. This is optional when Data is an object or string; otherwise, it is required.

171 |
172 |
173 |

Return Value

174 |

Type: Integer

175 |

This method returns the number of bytes that were written.

176 |
177 | 178 |

Seek

179 |

Moves the file pointer.

180 |
IsMoved := FileObj.Seek(Distance , Origin)
181 |

Parameters

182 |
183 |
Distance
184 |
185 |

Type: Integer

186 |

Distance to move, in bytes. Lower values are closer to the beginning of the file.

187 |
188 |
Origin
189 |
190 |

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 |
    193 |
  • 0 (SEEK_SET): Beginning of the file. Distance must be zero or greater.
  • 194 |
  • 1 (SEEK_CUR): Current position of the file pointer.
  • 195 |
  • 2 (SEEK_END): End of the file. Distance should usually be negative.
  • 196 |
197 |
198 |
199 |

Return Value

200 |

Type: Integer (boolean)

201 |

On success, this method returns 1 (true). On failure, it returns 0 (false).

202 |

Remarks

203 |

This method is equivalent to FileObj.Pos := Distance, if Distance is not negative and Origin is omitted or 0 (SEEK_SET).

204 |
205 | 206 |

Close

207 |

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.

210 | 211 |

Properties

212 | 213 |

Pos

214 |

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).

219 |
220 | 221 |

Length

222 |

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.

227 | 228 |

AtEOF

229 |

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".

232 | 233 |

Encoding

234 |

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 |
    240 |
  • UTF-8: Unicode UTF-8, equivalent to CP65001.
  • 241 |
  • UTF-16: Unicode UTF-16 with little endian byte order, equivalent to CP1200.
  • 242 |
  • CPnnn: a code page with numeric identifier nnn.
  • 243 |
244 |

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.

245 |

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.

246 |
247 | 248 |

Handle

249 |

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.

252 | 253 | 254 | 255 | -------------------------------------------------------------------------------- /docs/lib/FileAppend.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileAppend - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

FileAppend

14 | 15 |

Writes text or binary data to the end of a file (first creating the file, if necessary).

16 | 17 |
FileAppend Text , Filename, Options
18 |

Parameters

19 |
20 | 21 |
Text
22 |
23 |

Type: String or Object

24 |

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 |
27 | 28 |
Filename
29 |
30 |

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" |more
36 |
For /F "tokens=*" %L in ('""%ProgramFiles%\AutoHotkey\AutoHotkey.exe" "My Script .ahk""') do @Echo %L
37 |

Specifying two asterisks (**) for Filename causes Text to be sent to the standard error stream (stderr).

38 |
39 | 40 |
Options
41 |
42 |

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"

44 |

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 |
48 | 49 |
50 | 51 |

Error Handling

52 |

An OSError is thrown on failure.

53 |

A_LastError is set to the result of the operating system's GetLastError() function.

54 | 55 |

Remarks

56 |

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.

59 |

Related

60 |

FileEncoding, FileOpen/File Object, FileRead, file-reading loop, IniWrite, FileDelete, OutputDebug, continuation sections

61 |

Examples

62 |
63 |

Creates a file, if necessary, and appends a line.

64 |
FileAppend "Another line.`n", "C:\My Documents\Test.txt"
65 |
66 | 67 |
68 |

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 |
76 | 77 |
78 |

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 |
101 | 102 | 103 | 104 | -------------------------------------------------------------------------------- /docs/lib/FileCopy.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileCopy - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

FileCopy

14 | 15 |

Copies one or more files.

16 | 17 |
FileCopy SourcePattern, DestPattern , Overwrite
18 |

Parameters

19 |
20 | 21 |
SourcePattern
22 |
23 |

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.

25 |

Both asterisks (*) and question marks (?) are supported as wildcards. * matches zero or more characters and ? matches any single character. Usage examples:

26 |
    27 |
  • *.* or * matches all files.
  • 28 |
  • *.htm matches files with the extension .htm, .html, etc.
  • 29 |
  • *. matches files without an extension.
  • 30 |
  • log?.txt matches e.g. log1.txt but not log10.txt.
  • 31 |
  • *report* matches any filename containing the word "report".
  • 32 |
33 |
34 | 35 |
DestPattern
36 |
37 |

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.

40 |

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 |
45 | 46 |
Overwrite
47 |
48 |

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 |
54 | 55 |
56 | 57 |

Error Handling

58 |

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.

59 |

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 |

Remarks

63 |

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 |

Related

66 |

FileMove, DirCopy, DirMove, FileDelete

67 |

Examples

68 |
69 |

Makes a copy but keep the original file name.

70 |
FileCopy "C:\My Documents\List1.txt", "D:\Main Backup\"
71 |
72 | 73 |
74 |

Copies a file into the same directory by providing a new name.

75 |
FileCopy "C:\My File.txt", "C:\My File New.txt"
76 |
77 | 78 |
79 |

Copies text files to a new location and gives them a new extension.

80 |
FileCopy "C:\Folder1\*.txt", "D:\New Folder\*.bkp"
81 |
82 | 83 |
84 |

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 |
114 | 115 | 116 | 117 | -------------------------------------------------------------------------------- /docs/lib/FileCreateShortcut.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileCreateShortcut - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

FileCreateShortcut

14 | 15 |

Creates a shortcut (.lnk) file.

16 | 17 |
FileCreateShortcut Target, LinkFile , WorkingDir, Args, Description, IconFile, ShortcutKey, IconNumber, RunState
18 |

Parameters

19 |
20 | 21 |
Target
22 |
23 |

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 |
26 | 27 |
LinkFile
28 |
29 |

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 |
32 | 33 |
WorkingDir
34 |
35 |

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 |
38 | 39 |
Args
40 |
41 |

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 |
44 | 45 |
Description
46 |
47 |

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 |
50 | 51 |
IconFile
52 |
53 |

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 |
56 | 57 |
ShortcutKey
58 |
59 |

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 |
62 | 63 |
IconNumber
64 |
65 |

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 |
68 | 69 |
RunState
70 |
71 |

Type: Integer

72 |

If omitted, it defaults to 1. Otherwise, specify one of the following digits to launch Target minimized or maximized:

73 |
    74 |
  • 1 = Normal
  • 75 |
  • 3 = Maximized
  • 76 |
  • 7 = Minimized
  • 77 |
78 |
79 | 80 |
81 |

Error Handling

82 |

An exception is thrown on failure.

83 | 84 |

Remarks

85 |

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"

93 |

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 |

Related

95 |

FileGetShortcut, FileAppend

96 |

Examples

97 |
98 |

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 |
101 | 102 | 103 | 104 | -------------------------------------------------------------------------------- /docs/lib/FileDelete.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileDelete - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

FileDelete

14 | 15 |

Deletes one or more files permanently.

16 | 17 |
FileDelete FilePattern
18 |

Parameters

19 |
20 | 21 |
FilePattern
22 |
23 |

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.

25 |

Both asterisks (*) and question marks (?) are supported as wildcards. * matches zero or more characters and ? matches any single character. Usage examples:

26 |
    27 |
  • *.* or * matches all files.
  • 28 |
  • *.htm matches files with the extension .htm, .html, etc.
  • 29 |
  • *. matches files without an extension.
  • 30 |
  • log?.txt matches e.g. log1.txt but not log10.txt.
  • 31 |
  • *report* matches any filename containing the word "report".
  • 32 |
33 | 34 |

To remove an entire folder, along with all its sub-folders and files, use DirDelete.

35 |
36 | 37 |
38 | 39 |

Error Handling

40 |

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.

41 |

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 |

Remarks

44 |

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".

46 |

Related

47 |

FileRecycle, DirDelete, FileCopy, FileMove

48 |

Examples

49 |
50 |

Deletes all .tmp files in a directory.

51 |
FileDelete "C:\temp files\*.tmp"
52 |
53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /docs/lib/FileEncoding.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileEncoding - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

FileEncoding

14 | 15 |

Sets the default encoding for FileRead, Loop Read, FileAppend, and FileOpen.

16 | 17 |
FileEncoding Encoding
18 | 19 |

Parameters

20 |
21 |
Encoding
22 |
23 |

Type: String or Integer

24 |

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 |
33 |
34 | 35 |

Return Value

36 |

Type: String

37 |

This function returns the previous setting.

38 | 39 |

Remarks

40 |

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").

42 |

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 |

Related

47 |

FileOpen, StrGet, StrPut, Reading Binary Data

48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /docs/lib/FileExist.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileExist - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

FileExist

14 | 15 |

Checks for the existence of a file or folder and returns its attributes.

16 | 17 |
AttributeString := FileExist(FilePattern)
18 |

Parameters

19 |
20 | 21 |
FilePattern
22 |
23 |

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.

25 |

Both asterisks (*) and question marks (?) are supported as wildcards. * matches zero or more characters and ? matches any single character. Usage examples:

26 |
    27 |
  • *.* or * matches all files.
  • 28 |
  • *.htm matches files with the extension .htm, .html, etc.
  • 29 |
  • *. matches files without an extension.
  • 30 |
  • log?.txt matches e.g. log1.txt but not log10.txt.
  • 31 |
  • *report* matches any filename containing the word "report".
  • 32 |
33 |
34 | 35 |
36 | 37 |

Return Value

38 |

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:

40 |
    41 |
  • R = READONLY
  • 42 |
  • A = ARCHIVE
  • 43 |
  • S = SYSTEM
  • 44 |
  • H = HIDDEN
  • 45 |
  • N = NORMAL
  • 46 |
  • D = DIRECTORY
  • 47 |
  • O = OFFLINE
  • 48 |
  • C = COMPRESSED
  • 49 |
  • T = TEMPORARY
  • 50 |
  • L = REPARSE_POINT (typically a symbolic link)
  • 51 |
52 |

If the file has no attributes (rare), "X" is returned. If no file or folder is found, an empty string is returned.

53 | 54 |

Remarks

55 |

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\*").

56 |

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.

58 |

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.

59 | 60 |

Related

61 |

DirExist, FileGetAttrib, file loops

62 | 63 |

Examples

64 |
65 |

Shows a message box if the D drive does exist.

66 |
if FileExist("D:\")
67 |     MsgBox "The drive exists."
68 |
69 | 70 |
71 |

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 |
75 | 76 |
77 |

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 |
81 | 82 |
83 |

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 |
87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /docs/lib/FileGetAttrib.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileGetAttrib - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

FileGetAttrib

14 | 15 |

Reports whether a file or folder is read-only, hidden, etc.

16 | 17 |
AttributeString := FileGetAttrib(Filename)
18 | 19 |

Parameters

20 |
21 | 22 |
Filename
23 |
24 |

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 |
27 | 28 |
29 | 30 |

Return Value

31 |

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:

33 |
    34 |
  • R = READONLY
  • 35 |
  • A = ARCHIVE
  • 36 |
  • S = SYSTEM
  • 37 |
  • H = HIDDEN
  • 38 |
  • N = NORMAL
  • 39 |
  • D = DIRECTORY
  • 40 |
  • O = OFFLINE
  • 41 |
  • C = COMPRESSED
  • 42 |
  • T = TEMPORARY
  • 43 |
  • L = REPARSE_POINT (typically a symbolic link)
  • 44 |
45 | 46 |

Error Handling

47 |

An OSError is thrown on failure.

48 |

A_LastError is set to the result of the operating system's GetLastError() function.

49 | 50 |

Remarks

51 |

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.txt
55 |

A similar method can be used to get the long name of an 8.3 short name.

56 | 57 |

Related

58 |

FileExist, DirExist, FileSetAttrib, FileGetTime, FileSetTime, FileGetSize, FileGetVersion, file loop

59 | 60 |

Examples

61 |
62 |

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 |
65 |
66 |

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 |
70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /docs/lib/FileGetShortcut.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileGetShortcut - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

FileGetShortcut

14 | 15 |

Retrieves information about a shortcut (.lnk) file, such as its target file.

16 | 17 |
FileGetShortcut LinkFile , &OutTarget, &OutDir, &OutArgs, &OutDescription, &OutIcon, &OutIconNum, &OutRunState
18 |

Parameters

19 |
20 | 21 |
LinkFile
22 |
23 |

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 |
26 | 27 |
&OutTarget
28 |
29 |

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 |
32 | 33 |
&OutDir
34 |
35 |

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)

37 |
38 | 39 |
&OutArgs
40 |
41 |

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 |
44 | 45 |
&OutDescription
46 |
47 |

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 |
50 | 51 |
&OutIcon
52 |
53 |

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 |
56 | 57 |
&OutIconNum
58 |
59 |

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 |
62 | 63 |
&OutRunState
64 |
65 |

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 |
    68 |
  • 1 = Normal
  • 69 |
  • 3 = Maximized
  • 70 |
  • 7 = Minimized
  • 71 |
72 |
73 | 74 |
75 | 76 |

Error Handling

77 |

An OSError is thrown on failure.

78 | 79 |

Remarks

80 |

Any of the output variables may be omitted if the corresponding information is not needed.

81 |

Related

82 |

FileCreateShortcut, SplitPath

83 |

Examples

84 |
85 |

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 |
93 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /docs/lib/FileGetSize.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileGetSize - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

FileGetSize

14 | 15 |

Retrieves the size of a file.

16 | 17 |
Size := FileGetSize(Filename, Units)
18 |

Parameters

19 |
20 | 21 |
Filename
22 |
23 |

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 |
26 | 27 |
Units
28 |
29 |

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 |
    32 |
  • B = Bytes
  • 33 |
  • K = Kilobytes
  • 34 |
  • M = Megabytes
  • 35 |
36 |
37 | 38 |
39 | 40 |

Return Value

41 |

Type: Integer

42 |

This function returns the size of the specified file (rounded down to the nearest whole number).

43 | 44 |

Error Handling

45 |

An OSError is thrown on failure.

46 |

A_LastError is set to the result of the operating system's GetLastError() function.

47 | 48 |

Remarks

49 |

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 |

Related

58 |

FileGetAttrib, FileSetAttrib, FileGetTime, FileSetTime, FileGetVersion, file loop

59 |

Examples

60 |
61 |

Retrieves the size in bytes and stores it in Size.

62 |
Size := FileGetSize("C:\My Documents\test.doc")
63 |
64 | 65 |
66 |

Retrieves the size in kilobytes and stores it in Size.

67 |
Size := FileGetSize("C:\My Documents\test.doc", "K")
68 |
69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /docs/lib/FileGetTime.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileGetTime - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

FileGetTime

14 | 15 |

Retrieves the datetime stamp of a file or folder.

16 | 17 |
Timestamp := FileGetTime(Filename, WhichTime)
18 |

Parameters

19 |
20 | 21 |
Filename
22 |
23 |

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 |
26 | 27 |
WhichTime
28 |
29 |

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 |
    32 |
  • M = Modification time
  • 33 |
  • C = Creation time
  • 34 |
  • A = Last access time
  • 35 |
36 |
37 | 38 |
39 | 40 |

Return Value

41 |

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 |

Error Handling

45 |

An OSError is thrown on failure.

46 |

A_LastError is set to the result of the operating system's GetLastError() function.

47 | 48 |

Remarks

49 |

See YYYYMMDDHH24MISS for an explanation of dates and times.

50 |

Related

51 |

FileSetTime, FormatTime, FileGetAttrib, FileSetAttrib, FileGetSize, FileGetVersion, file loop, DateAdd, DateDiff

52 |

Examples

53 |
54 |

Retrieves the modification time and stores it in Timestamp.

55 |
Timestamp := FileGetTime("C:\My Documents\test.doc")
56 |
57 | 58 |
59 |

Retrieves the creation time and stores it in Timestamp.

60 |
Timestamp := FileGetTime("C:\My Documents\test.doc", "C")
61 |
62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /docs/lib/FileGetVersion.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileGetVersion - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

FileGetVersion

14 | 15 |

Retrieves the version of a file.

16 | 17 |
Version := FileGetVersion(Filename)
18 |

Parameters

19 |
20 | 21 |
Filename
22 |
23 |

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 |
26 | 27 |
28 | 29 |

Return Value

30 |

Type: String

31 |

This function returns the version number of the specified file.

32 | 33 |

Error Handling

34 |

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 |

Remarks

38 |

Most non-executable files (and even some EXEs) have no version, and thus an error will be thrown.

39 | 40 |

Related

41 |

FileGetAttrib, FileSetAttrib, FileGetTime, FileSetTime, FileGetSize, file loop

42 |

Examples

43 |
44 |

Retrieves the version of a file and stores it in Version.

45 |
Version := FileGetVersion("C:\My Application.exe")
46 |
47 | 48 |
49 |

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 |
52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /docs/lib/FileInstall.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileInstall - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

FileInstall

14 | 15 |

Includes the specified file inside the compiled version of the script.

16 | 17 |
FileInstall Source, Dest , Overwrite
18 |

Parameters

19 |
20 | 21 |
Source
22 |
23 |

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 |
27 | 28 |
Dest
29 |
30 |

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 |
33 | 34 |
Overwrite
35 |
36 |

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 |
42 | 43 |
44 | 45 |

Error Handling

46 |

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 |
    50 |
  • The destination file already exists and the Overwrite parameter was 0 or omitted.
  • 51 |
  • The destination file could not be opened due to a permission error, or because the file is in use.
  • 52 |
  • The destination path was invalid or specifies a folder which does not exist.
  • 53 |
  • The source file does not exist (only for uncompiled scripts).
  • 54 |
55 | 56 |

Remarks

57 |

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 |

Related

62 |

FileCopy, #Include

63 | 64 |

Examples

65 |
66 |

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", 1
68 |
69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /docs/lib/FileMove.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileMove - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

FileMove

14 | 15 |

Moves or renames one or more files.

16 | 17 |
FileMove SourcePattern, DestPattern , Overwrite
18 |

Parameters

19 |
20 | 21 |
SourcePattern
22 |
23 |

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.

25 |

Both asterisks (*) and question marks (?) are supported as wildcards. * matches zero or more characters and ? matches any single character. Usage examples:

26 |
    27 |
  • *.* or * matches all files.
  • 28 |
  • *.htm matches files with the extension .htm, .html, etc.
  • 29 |
  • *. matches files without an extension.
  • 30 |
  • log?.txt matches e.g. log1.txt but not log10.txt.
  • 31 |
  • *report* matches any filename containing the word "report".
  • 32 |
33 |
34 | 35 |
DestPattern
36 |
37 |

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.

40 |

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 |
45 | 46 |
Overwrite
47 |
48 |

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 |
54 | 55 |
56 | 57 |

Error Handling

58 |

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.

59 |

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 |

Remarks

63 |

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 |

Related

67 |

FileCopy, DirCopy, DirMove, FileDelete

68 |

Examples

69 |
70 |

Moves a file without renaming it.

71 |
FileMove "C:\My Documents\List1.txt", "D:\Main Backup\"
72 |
73 | 74 |
75 |

Renames a single file.

76 |
FileMove "C:\File Before.txt", "C:\File After.txt"
77 |
78 | 79 |
80 |

Moves text files to a new location and gives them a new extension.

81 |
FileMove "C:\Folder1\*.txt", "D:\New Folder\*.bkp"
82 |
83 | 84 |
85 |

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 |
117 | 118 | 119 | 120 | -------------------------------------------------------------------------------- /docs/lib/FileOpen.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileOpen - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 15 | 16 | 17 | 18 |

FileOpen

19 | 20 |

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 |

Parameters

24 |
25 | 26 |
Filename
27 |
28 |

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 stderr
35 |
36 | 37 |
Flags
38 |
39 |

Type: String or Integer

40 |

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 |
42 | 43 |
Encoding
44 |
45 |

Type: String or Integer

46 |

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.

47 |

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).

48 |
49 | 50 |
51 | 52 |

Flags

53 | 54 |

Access modes (mutually-exclusive)

55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 |
FlagDecHexDescription
r00x0Read: Fails if the file doesn't exist.
w10x1Write: Creates a new file, overwriting any existing file.
a20x2Append: Creates a new file if the file didn't exist, otherwise moves the file pointer to the end of the file.
rw30x3Read/Write: Creates a new file if the file didn't exist.
h  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.
93 | 94 |

Sharing mode flags

95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 |
FlagDecHexDescription
-rwd  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.
 00x0If Flags is numeric, the absence of sharing mode flags causes the file to be locked.
 2560x100Shares read access.
 5120x200Shares write access.
 10240x400Shares delete access.
133 | 134 |

End of line (EOL) options

135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 |
FlagDecHexDescription
`n40x4Replace `r`n with `n when reading and `n with `r`n when writing.
`r80x8Replace standalone `r with `n when reading.
155 | 156 |

Return Value

157 |

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 |

Errors

161 |

If the file cannot be opened, an OSError is thrown.

162 | 163 |

Remarks

164 |

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.

165 |

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".

166 |

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.

168 | 169 |

Related

170 |

FileEncoding, File Object, FileRead

171 | 172 |

Examples

173 | 174 |
175 |

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: " TestString
204 |
205 | 206 |
207 |

Opens the script in read-only mode and read its first line.

208 |
Script := FileOpen(A_ScriptFullPath, "r")
209 | MsgBox Script.ReadLine()
210 |
211 | 212 |
213 |

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 |
227 | 228 | 229 | -------------------------------------------------------------------------------- /docs/lib/FileRead.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileRead - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

FileRead

14 | 15 |

Retrieves the contents of a file.

16 | 17 |
Text := FileRead(Filename , Options)
18 |

Parameters

19 |
20 | 21 |
Filename
22 |
23 |

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 |
26 | 27 |
Options
28 |
29 |

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"

31 |

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".

36 |
37 | 38 |
39 | 40 |

Return Value

41 |

Type: String or Object

42 |

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 |

Error Handling

45 |

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 |

Reading Binary Data

50 |

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:

51 |
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 |

Remarks

66 |

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 |

Related

71 |

FileEncoding, FileOpen/File Object, file-reading loop, FileGetSize, FileAppend, IniRead, Sort, Download

72 | 73 |

Examples

74 |
75 |

Reads a text file into MyText.

76 |
MyText := FileRead("C:\My Documents\My File.txt")
77 |
78 | 79 |
80 |

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 |
89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /docs/lib/FileRecycle.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileRecycle - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

FileRecycle

14 | 15 |

Sends a file or directory to the recycle bin if possible, or permanently deletes it.

16 | 17 |
FileRecycle FilePattern
18 |

Parameters

19 |
20 | 21 |
FilePattern
22 |
23 |

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.

25 |

Both asterisks (*) and question marks (?) are supported as wildcards. * matches zero or more characters and ? matches any single character. Usage examples:

26 |
    27 |
  • *.* or * matches all files.
  • 28 |
  • *.htm matches files with the extension .htm, .html, etc.
  • 29 |
  • *. matches files without an extension.
  • 30 |
  • log?.txt matches e.g. log1.txt but not log10.txt.
  • 31 |
  • *report* matches any filename containing the word "report".
  • 32 |
33 |

To recycle an entire directory, provide its name without a trailing backslash.

34 |
35 | 36 |
37 | 38 |

Error Handling

39 |

An exception is thrown on failure.

40 | 41 |

Remarks

42 |

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 |
    45 |
  • The file is on a removable drive.
  • 46 |
  • The Recycle Bin has been disabled, such as via the NukeOnDelete registry value.
  • 47 |
48 |

Related

49 |

FileRecycleEmpty, FileDelete, FileCopy, FileMove

50 |

Examples

51 |
52 |

Sends all .tmp files in a directory to the recycle bin if possible.

53 |
FileRecycle "C:\temp files\*.tmp"
54 |
55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /docs/lib/FileRecycleEmpty.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileRecycleEmpty - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

FileRecycleEmpty

14 | 15 |

Empties the recycle bin.

16 | 17 |
FileRecycleEmpty DriveLetter
18 |

Parameters

19 |
20 | 21 |
DriveLetter
22 |
23 |

Type: String

24 |

If omitted, the recycle bin for all drives is emptied. Otherwise, specify a drive letter such as "C:\".

25 |
26 | 27 |
28 | 29 |

Error Handling

30 |

An OSError is thrown on failure.

31 | 32 |

Related

33 |

FileRecycle, FileDelete, FileCopy, FileMove

34 |

Examples

35 |
36 |

Empties the recycle bin of the C drive.

37 |
FileRecycleEmpty "C:\"
38 |
39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /docs/lib/FileSelect.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileSelect - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

FileSelect

15 | 16 |

Displays a standard dialog that allows the user to open or save file(s).

17 | 18 |
SelectedFile := FileSelect(Options, RootDir\Filename, Title, Filter)
19 |

Parameters

20 |
21 | 22 |
Options
23 |
24 |

Type: String or Integer

25 |

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).

26 |

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.

35 |

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 |
37 | 38 |
RootDir\Filename
39 |
40 |

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 /<|:").

44 |

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 |
50 | 51 |
Title
52 |
53 |

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.

55 |
56 | 57 |
Filter
58 |
59 |

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.

62 |

This parameter must be blank or omitted if the "D" option is present.

63 |
64 | 65 |
66 | 67 |

Return Value

68 |

Type: String or Array

69 |

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 |

Remarks

73 |

A file-selection dialog usually looks like this:

74 | FileSelect 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 |

Related

78 |

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 |

Examples

81 |
82 |

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" SelectedFile
88 |
89 | 90 |
91 |

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 |
106 | 107 |
108 |

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 |
117 | 118 | 119 | 120 | -------------------------------------------------------------------------------- /docs/lib/FileSetAttrib.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileSetAttrib - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

FileSetAttrib

14 | 15 |

Changes the attributes of one or more files or folders. Wildcards are supported.

16 | 17 |
FileSetAttrib Attributes , FilePattern, Mode
18 |

Parameters

19 |
20 | 21 |
Attributes
22 |
23 |

Type: String

24 |

The attributes to change. For example, "+HA-R".

25 |

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 |
    27 |
  • R = READONLY
  • 28 |
  • A = ARCHIVE
  • 29 |
  • S = SYSTEM
  • 30 |
  • H = HIDDEN
  • 31 |
  • N = NORMAL (this is valid only when used without any other attributes)
  • 32 |
  • O = OFFLINE
  • 33 |
  • T = TEMPORARY
  • 34 |
35 |

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.

36 |
37 | 38 |
FilePattern
39 |
40 |

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.

42 |

Both asterisks (*) and question marks (?) are supported as wildcards. * matches zero or more characters and ? matches any single character. Usage examples:

43 |
    44 |
  • *.* or * matches all files.
  • 45 |
  • *.htm matches files with the extension .htm, .html, etc.
  • 46 |
  • *. matches files without an extension.
  • 47 |
  • log?.txt matches e.g. log1.txt but not log10.txt.
  • 48 |
  • *report* matches any filename containing the word "report".
  • 49 |
50 |
51 | 52 |
Mode
53 |
54 |

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 |
    57 |
  • D = Include directories (folders).
  • 58 |
  • F = Include files. If both F and D are omitted, files are included but not folders.
  • 59 |
  • R = Subfolders are recursed into so that files and folders contained therein are operated upon if they match FilePattern. All subfolders will be recursed into, not just those whose names match FilePattern. If R is omitted, files and folders in subfolders are not included.
  • 60 |
61 |
62 | 63 |
64 | 65 |

Error Handling

66 |

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 |

Remarks

70 |

The compression state of files cannot be changed with this function.

71 | 72 |

Related

73 |

FileGetAttrib, FileGetTime, FileSetTime, FileGetSize, FileGetVersion, file loop

74 |

Examples

75 |
76 |

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+H
78 |
79 | 80 |
81 |

Toggles the "hidden" attribute of a single directory.

82 |
FileSetAttrib "^H", "C:\MyFiles"
83 |
84 | 85 |
86 |

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 |
89 | 90 |
91 |

Recurses through all .ini files on the C drive and turns on their "archive" attribute.

92 |
FileSetAttrib "+A", "C:\*.ini", "R"
93 |
94 | 95 |
96 |

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 |
99 | 100 | 101 | 102 | -------------------------------------------------------------------------------- /docs/lib/FileSetTime.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FileSetTime - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

FileSetTime

14 | 15 |

Changes the datetime stamp of one or more files or folders. Wildcards are supported.

16 | 17 |
FileSetTime YYYYMMDDHH24MISS, FilePattern, WhichTime, Mode
18 |

Parameters

19 |
20 | 21 |
YYYYMMDDHH24MISS
22 |
23 |

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 |
26 | 27 |
FilePattern
28 |
29 |

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.

31 |

Both asterisks (*) and question marks (?) are supported as wildcards. * matches zero or more characters and ? matches any single character. Usage examples:

32 |
    33 |
  • *.* or * matches all files.
  • 34 |
  • *.htm matches files with the extension .htm, .html, etc.
  • 35 |
  • *. matches files without an extension.
  • 36 |
  • log?.txt matches e.g. log1.txt but not log10.txt.
  • 37 |
  • *report* matches any filename containing the word "report".
  • 38 |
39 |
40 | 41 |
WhichTime
42 |
43 |

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 |
    46 |
  • M = Modification time
  • 47 |
  • C = Creation time
  • 48 |
  • A = Last access time
  • 49 |
50 |
51 | 52 |
Mode
53 |
54 |

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 |
    57 |
  • D = Include directories (folders).
  • 58 |
  • F = Include files. If both F and D are omitted, files are included but not folders.
  • 59 |
  • R = Subfolders are recursed into so that files and folders contained therein are operated upon if they match FilePattern. All subfolders will be recursed into, not just those whose names match FilePattern. If R is omitted, files and folders in subfolders are not included.
  • 60 |
61 |

Note: If FilePattern is a single folder rather than a wildcard pattern, it will always be operated upon regardless of this setting.

62 |
63 | 64 |
65 | 66 |

Error Handling

67 |

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 |

Remarks

71 |

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 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 |
ElementDescription
YYYYThe 4-digit year
MMThe 2-digit month (01-12)
DDThe 2-digit day of the month (01-31)
HH24The 2-digit hour in 24-hour format (00-23). For example, 09 is 9am and 21 is 9pm.
MIThe 2-digit minutes (00-59)
SSThe 2-digit seconds (00-59)
103 |

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 |
    105 |
  • MM = Month 01
  • 106 |
  • DD = Day 01
  • 107 |
  • HH24 = Hour 00
  • 108 |
  • MI = Minute 00
  • 109 |
  • SS = Second 00
  • 110 |
111 |

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 |

Related

114 |

FileGetTime, FileGetAttrib, FileSetAttrib, FileGetSize, FileGetVersion, FormatTime, file loop, DateAdd, DateDiff

115 |

Examples

116 |
117 |

Sets the modification time to the current time for all matching files.

118 |
FileSetTime "", "C:\temp\*.txt"
119 |
120 | 121 |
122 |

Sets the modification date (time will be midnight).

123 |
FileSetTime 20040122, "C:\My Documents\test.doc"
124 |
125 | 126 |
127 |

Sets the creation date. The time will be set to 4:55pm.

128 |
FileSetTime 200401221655, "C:\My Documents\test.doc", "C"
129 |
130 | 131 |
132 |

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 |
135 | 136 | 137 | 138 | -------------------------------------------------------------------------------- /docs/lib/Finally.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Finally - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Finally

14 | 15 |

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 |

Remarks

23 |

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.

26 |

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 |

Related

44 |

Try, Catch, Else, Throw, Blocks

45 |

Examples

46 |
47 |

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 |
83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /docs/lib/Float.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Float - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Float

15 |

Converts a numeric string or integer value to a floating-point number.

16 |
FltValue := Float(Value)
17 | 18 |

Return Value

19 |

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 |

Remarks

23 |

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.

26 | 27 |

Related

28 |

Type, Integer, Number, String, Values, Expressions, Is functions

29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /docs/lib/For.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | For Loop - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

For-loop

14 | 15 |

Repeats one or more statements once for each key-value pair in an object.

16 | 17 |
For Value1, Value2 in Expression
18 |

Parameters

19 |
20 | 21 |
Value1, Value2
22 |
23 |

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.

29 |
30 | 31 |
Expression
32 |
33 |

Type: Object

34 |

An expression which results in an enumerable object, or a variable which contains an enumerable object.

35 |
36 | 37 |
38 | 39 |

Remarks

40 |

The parameter list can optionally be enclosed in parentheses. For example: for (val in myarray)

41 |

The process of enumeration is as follows:

42 |
    43 |
  • Before the loop begins, Expression is evaluated to determine the target object.
  • 44 |
  • The object's __Enum method is called to retrieve an enumerator object. If no such method exists, the object itself is assumed to be an enumerator object.
  • 45 |
  • At the beginning of each iteration, the enumerator is called to retrieve the next value or pair of values. If it returns false (zero or an empty string), the loop terminates.
  • 46 |
47 |

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 {.

58 |

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 |

COM Objects

62 |

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 |

Related

66 |

Enumerator object, OwnProps, While-loop, Loop, Until, Break, Continue, Blocks

67 | 68 |

Examples

69 |
70 |

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 |
79 | 80 |
81 |

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 windows
86 |
87 | 88 |
89 |

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 |
102 | 103 |
104 |

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 |
117 | 118 | 119 | -------------------------------------------------------------------------------- /docs/lib/Format.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Format - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Format

14 | 15 |

Formats a variable number of input values according to a format string.

16 | 17 |
String := Format(FormatStr , Values...)
18 |

Parameters

19 |
20 | 21 |
FormatStr
22 |
23 |

Type: String

24 |

A format string composed of literal text and placeholders of the form {Index:Format}.

25 |

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: {}

28 |

Use {{} and {}} to include literal braces in the string. Any other invalid placeholders are included in the result as is.

29 |

Whitespace inside the braces is not permitted (except as a flag).

30 |
31 | 32 |
Values
33 |
34 |

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 |
40 | 41 |
42 | 43 |

Return Value

44 |

Type: String

45 |

This function returns the formatted version of the specified string.

46 | 47 |

Format Specifiers

48 |

Each format specifier can include the following components, in this order (without the spaces):

49 |
Flags Width .Precision ULT Type
50 |

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.

52 |

.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 |
    54 |
  • f, e, E: Precision specifies the number of digits after the decimal point. The default is 6.
  • 55 |
  • g, G: Precision specifies the maximum number of significant digits. The default is 6.
  • 56 |
  • s: Precision specifies the maximum number of characters to be printed. Characters in excess of this are not printed.
  • 57 |
  • For the integer types (d, i, u, x, X, o), Precision acts like Width with the 0 prefix and a default of 1.
  • 58 |
59 |

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.

60 |

Type: A character from the type table below indicating how the input value should be interpreted. If omitted, it defaults to s.

61 | 62 |

Flags

63 | 64 | 65 | 66 | 67 | 71 | 72 | 73 | 74 | 78 | 79 | 80 | 81 | 85 | 86 | 87 | 88 | 92 | 93 | 94 | 95 | 101 | 102 |
FlagMeaning
- 68 |

Left align the result within the given field width (insert spaces to the right if needed). For example, Format("{:-10}", 1) returns 1 .

69 |

If omitted, the result is right aligned within the given field width.

70 |
+ 75 |

Use a sign (+ or -) to prefix the output value if it is of a signed type. For example, Format("{:+d}", 1) returns +1.

76 |

If omitted, a sign appears only for negative signed values (-).

77 |
0 82 |

If width is prefixed by 0, leading zeros are added until the minimum width is reached. For example, Format("{:010}", 1) returns 0000000001. If both 0 and - appear, the 0 is ignored. If 0 is specified as an integer format (i, u, x, X, o, d) and a precision specification is also present - for example, {:04.d} - the 0 is ignored.

83 |

If omitted, no padding occurs.

84 |
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 and + flags appear. For example, Format("{: 05d}", 1) returns 0001.

90 |

If omitted, no space appears.

91 |
# 96 |

When it's used with the o, x, or X format, the # flag uses 0, 0x, or 0X, respectively, to prefix any nonzero output value. For example, Format("{:#x}", 1) returns 0x1.

97 |

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, Format("{:#.0f}", 1) returns 1..

98 |

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 |
103 | 104 |

Types

105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 |
Type CharacterArgumentOutput format
d or iIntegerSigned decimal integer. For example, Format("{:d}", 1.23) returns 1.
uIntegerUnsigned decimal integer.
x or XIntegerUnsigned 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.
oIntegerUnsigned octal integer. For example, Format("{:o}", 255) returns 377.
fFloating-pointSigned 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.
eFloating-pointSigned 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.
EFloating-pointIdentical to the e format except that E rather than e introduces the exponent.
gFloating-pointSigned 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.
GFloating-pointIdentical to the g format, except that E, rather than e, introduces the exponent (where appropriate).
aFloating-pointSigned 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.
AFloating-pointIdentical to the a format, except that P, rather than p, introduces the exponent.
pIntegerDisplays the argument as a memory address in hexadecimal digits. For example, Format("{:p}", 255) returns 00000000000000FF.
sStringSpecifies a string. If the input value is numeric, it is automatically converted to a string before the Width and Precision arguments are applied.
cCharacter codeSpecifies 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.
178 | 179 |

Remarks

180 |

Unlike printf, size specifiers are not supported. All integers and floating-point input values are 64-bit.

181 | 182 |

Related

183 |

FormatTime

184 | 185 |

Examples

186 |
187 |

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 |
205 | 206 | 207 | 208 | -------------------------------------------------------------------------------- /docs/lib/FormatTime.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | FormatTime - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 13 | 14 | 15 | 16 |

FormatTime

17 | 18 |

Transforms a YYYYMMDDHH24MISS timestamp into the specified date/time format.

19 | 20 |
String := FormatTime(YYYYMMDDHH24MISS, Format)
21 |

Parameters

22 |
23 | 24 |
YYYYMMDDHH24MISS
25 |
26 |

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 |
29 | 30 |
Format
31 |
32 |

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 |
36 | 37 |
38 | 39 |

Return Value

40 |

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 |

Date Formats (case-sensitive)

46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 |
FormatDescription
dDay of the month without leading zero (1 – 31)
ddDay of the month with leading zero (01 – 31)
dddAbbreviated name for the day of the week (e.g. Mon) in the current user's language
ddddFull name for the day of the week (e.g. Monday) in the current user's language
MMonth without leading zero (1 – 12)
MMMonth with leading zero (01 – 12)
MMMAbbreviated month name (e.g. Jan) in the current user's language
MMMMFull month name (e.g. January) in the current user's language
yYear without century, without leading zero (0 – 99)
yyYear without century, with leading zero (00 – 99)
yyyyYear with century. For example: 2005
ggPeriod/era string for the current user's locale (blank if none)
100 |

Time Formats (case-sensitive)

101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 |
FormatDescription
hHours without leading zero; 12-hour format (1 – 12)
hhHours with leading zero; 12-hour format (01 – 12)
HHours without leading zero; 24-hour format (0 – 23)
HHHours with leading zero; 24-hour format (00 – 23)
mMinutes without leading zero (0 – 59)
mmMinutes with leading zero (00 – 59)
sSeconds without leading zero (0 – 59)
ssSeconds with leading zero (00 – 59)
tSingle character time marker, such as A or P (depends on locale)
ttMulti-character time marker, such as AM or PM (depends on locale)
147 |

Standalone Formats

148 |

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 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 |
FormatDescription
(Blank)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
TimeTime representation for the current user's locale, such as 5:26 PM
ShortDateShort date representation for the current user's locale, such as 02/29/04
LongDateLong date representation for the current user's locale, such as Friday, April 23, 2004
YearMonthYear and month format for the current user's locale, such as February, 2004
YDayDay of the year without leading zeros (1 – 366)
YDay0Day of the year with leading zeros (001 – 366)
WDayDay of the week (1 – 7). Sunday is 1.
YWeekThe 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.
191 |

Additional Options

192 |

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 |
    198 |
  • 0 = Force the default options to be used. This also causes the short date to be in effect.
  • 199 |
  • 1 = Use short date (meaningful only when Format is blank; not compatible with 2 and 8).
  • 200 |
  • 2 = Use long date (meaningful only when Format is blank; not compatible with 1 and 8).
  • 201 |
  • 4 = Use alternate calendar (if any).
  • 202 |
  • 8 = Use Year-Month format (meaningful only when Format is blank; not compatible with 1 and 2).
  • 203 |
  • 0x10 = Add marks for left-to-right reading order layout.
  • 204 |
  • 0x20 = Add marks for right-to-left reading order layout.
  • 205 |
  • 0x80000000 = Do not obey any overrides the user may have in effect for the system's default date format.
  • 206 |
  • 0x40000000 = Use the system ANSI code page for string translation instead of the locale's code page.
  • 207 |
208 |

Tn: Time options. Specify for n one of the following numbers:

209 |
    210 |
  • 0 = Force the default options to be used. This also causes minutes and seconds to be shown.
  • 211 |
  • 1 = Omit minutes and seconds.
  • 212 |
  • 2 = Omit seconds.
  • 213 |
  • 4 = Omit time marker (e.g. AM/PM).
  • 214 |
  • 8 = Always use 24-hour time rather than 12-hour time.
  • 215 |
  • 12 = Combination of the above two.
  • 216 |
  • 0x80000000 = Do not obey any overrides the user may have in effect for the system's default time format.
  • 217 |
  • 0x40000000 = Use the system ANSI code page for string translation instead of the locale's code page.
  • 218 |
219 |

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")

220 |

Remarks

221 |

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".

222 |

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 |

Related

227 |

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 |

Examples

230 |
231 |

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: " YearWeek
254 |
255 | 256 |
257 |

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 " FileTime
264 |
265 | 266 |
267 |

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 |
281 | 282 | 283 | 284 | -------------------------------------------------------------------------------- /docs/lib/Func.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Func Object - Methods & Properties | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Func Object

14 |
class Func extends Object
15 | 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.

19 | 20 |

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 |

Table of Contents

34 |
    35 |
  • Methods: 36 |
      37 |
    • Call: Calls the function.
    • 38 |
    • Bind: Binds parameters to the function.
    • 39 |
    • IsByRef: Determines whether a parameter is ByRef.
    • 40 |
    • IsOptional: Determines whether a parameter is optional.
    • 41 |
    42 |
  • 43 |
  • Properties: 44 |
      45 |
    • Name: Returns the function's name.
    • 46 |
    • IsBuiltIn: Returns 1 (true) if the function is built-in, otherwise 0 (false).
    • 47 |
    • IsVariadic: Returns 1 (true) if the function is variadic, otherwise 0 (false).
    • 48 |
    • MinParams: Returns the number of required parameters.
    • 49 |
    • MaxParams: Returns the number of formally-declared parameters for a user-defined function or maximum parameters for a built-in function.
    • 50 |
    51 |
  • 52 |
53 | 54 |

Methods

55 | 56 |

Call

57 |

Calls the function.

58 |
FuncObj(Param1, Param2, ...)
 59 | FuncObj.Call(Param1, Param2, ...)
60 |

Parameters

61 |
62 |
Param1, Param2, ...
63 |
64 |

Parameters and return value are defined by the function.

65 |
66 |
67 |

Remarks

68 |

The "Call" method is implied when calling a value, so need not be explicitly specified.

69 |
70 | 71 |

Bind

72 |

Binds parameters to the function.

73 |
BoundFunc := FuncObj.Bind(Param1, Param2, ...)
74 |

Parameters

75 |
76 |
Param1, Param2, ...
77 |
78 |

Any number of parameters.

79 |
80 |
81 |

Return Value

82 |

Type: Object

83 |

This method returns a BoundFunc object.

84 |
85 | 86 |

IsByRef

87 |

Determines whether a parameter is ByRef.

88 |
Boolean := FuncObj.IsByRef(ParamIndex)
89 |

Parameters

90 |
91 |
ParamIndex
92 |
93 |

Type: Integer

94 |

If omitted, Boolean indicates whether the function has any ByRef parameters. Otherwise, specify the one-based index of a parameter.

95 |
96 |
97 |

Return Value

98 |

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 |
101 | 102 |

IsOptional

103 |

Determines whether a parameter is optional.

104 |
Boolean := FuncObj.IsOptional(ParamIndex)
105 |

Parameters

106 |
107 |
ParamIndex
108 |
109 |

Type: Integer

110 |

If omitted, Boolean indicates whether the function has any optional parameters. Otherwise, specify the one-based index of a parameter.

111 |
112 |
113 |

Return Value

114 |

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 |

Remarks

117 |

Parameters do not need to be formally declared if the function is variadic. Built-in functions are supported.

118 | 119 |

Properties

120 | 121 |

Name

122 |

Returns the function's name.

123 |
FunctionName := FuncObj.Name
124 |
125 | 126 |

IsBuiltIn

127 |

Returns 1 (true) if the function is built-in, otherwise 0 (false).

128 |
Boolean := FuncObj.IsBuiltIn
129 |
130 | 131 |

IsVariadic

132 |

Returns 1 (true) if the function is variadic, otherwise 0 (false).

133 |
Boolean := FuncObj.IsVariadic
134 |
135 | 136 |

MinParams

137 |

Returns the number of required parameters.

138 |
ParamCount := FuncObj.MinParams
139 |
140 | 141 |

MaxParams

142 |

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.

145 | 146 | 147 | 148 | -------------------------------------------------------------------------------- /docs/lib/GetKeyName.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | GetKeyName - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

GetKeyName

15 | 16 |

Retrieves the name/text of a key.

17 | 18 |
Name := GetKeyName(KeyName)
19 |

Parameters

20 |
21 | 22 |
KeyName
23 |
24 |

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 |
28 | 29 |
30 | 31 |

Return Value

32 |

Type: String

33 |

This function returns the name of the specified key, or blank if the key is invalid or unnamed.

34 | 35 |

Related

36 |

GetKeyVK, GetKeySC, GetKeyState, Key List

37 |

Examples

38 |
39 |

Retrieves and reports the English name of Esc.

40 |
MsgBox GetKeyName("Esc") ; Shows Escape
41 | MsgBox GetKeyName("vk1B") ; Shows also Escape
42 |
43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /docs/lib/GetKeySC.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | GetKeySC - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

GetKeySC

15 | 16 |

Retrieves the scan code of a key.

17 | 18 |
SC := GetKeySC(KeyName)
19 |

Parameters

20 |
21 | 22 |
KeyName
23 |
24 |

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 |
28 | 29 |
30 | 31 |

Return Value

32 |

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 |

Remarks

36 |

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.

37 |

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 |

Related

42 |

GetKeyVK, GetKeyName, GetKeyState, Key List, Format

43 |

Examples

44 |
45 |

Retrieves and reports the hexadecimal scan code of the left Ctrl.

46 |
sc_code := GetKeySC("LControl")
47 | MsgBox Format("sc{:X}", sc_code) ; Reports sc1D
48 |
49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /docs/lib/GetKeyState.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | GetKeyState - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

GetKeyState

14 | 15 |

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 |

Parameters

19 |
20 | 21 |
KeyName
22 |
23 |

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 |
28 | 29 |
Mode
30 |
31 |

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 |
38 | 39 |
40 | 41 |

Return Value

42 |

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 |
    47 |
  • -1: no angle to report
  • 48 |
  • 0: forward POV
  • 49 |
  • 9000 (i.e. 90 degrees): right POV
  • 50 |
  • 27000 (i.e. 270 degrees): left POV
  • 51 |
  • 18000 (i.e. 180 degrees): backward POV
  • 52 |
53 |

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 |

Error Handling

57 |

A ValueError is thrown if invalid parameters are detected, e.g. when KeyName does not exist on the current keyboard layout.

58 | 59 |

Remarks

60 |

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 |

Related

64 |

GetKeyVK, GetKeySC, GetKeyName, KeyWait, Key List, Controller remapping, KeyHistory, InstallKeybdHook, InstallMouseHook

65 | 66 |

Examples

67 | 68 |
69 |

Retrieves the current state of the right mouse button.

70 |
state := GetKeyState("RButton")
71 |
72 | 73 |
74 |

Retrieves the current state of the first controller's second button.

75 |
state := GetKeyState("Joy2")
76 |
77 | 78 |
79 |

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 |
85 | 86 |
87 |

Retrieves the current toggle state of CapsLock.

88 |
state := GetKeyState("CapsLock", "T")
89 |
90 | 91 |
92 |

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 |
106 | 107 |
108 |

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 |
120 | 121 |

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 | GetKeyVK - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

GetKeyVK

15 | 16 |

Retrieves the virtual key code of a key.

17 | 18 |
VK := GetKeyVK(KeyName)
19 |

Parameters

20 |
21 | 22 |
KeyName
23 |
24 |

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 |
28 | 29 |
30 | 31 |

Return Value

32 |

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 |

Remarks

36 |

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.

37 |

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 |

Related

42 |

GetKeySC, GetKeyName, GetKeyState, Key List, Format

43 |

Examples

44 |
45 |

Retrieves and reports the hexadecimal virtual key code of Esc.

46 |
vk_code := GetKeyVK("Esc")
47 | MsgBox Format("vk{:X}", vk_code) ; Reports vk1B
48 |
49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /docs/lib/GetMethod.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | GetMethod - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

GetMethod

15 | 16 |

Retrieves the implementation function of a method.

17 | 18 |
Method := GetMethod(Value , Name, ParamCount)
19 |

Parameters

20 |
21 |
Value
22 |
23 |

Type: Any

24 |

Any value, of any type except ComObject.

25 |
26 |
Name
27 |
28 |

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 |
32 |
ParamCount
33 |
34 | Type: Integer 35 |

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.

38 |
39 |
40 | 41 |

Return Value

42 |

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 |

Errors

46 |

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 |

Remarks

50 |

Methods may be defined through one of the following:

51 |
    52 |
  • A dynamic property with a call accessor function. This includes: 53 |
      54 |
    • Any property created by a method definition within a class.
    • 55 |
    • Any property created by passing a descriptor like {Call: fn} to DefineProp, where fn implements the method.
    • 56 |
    • Any predefined/built-in method.
    • 57 |
    58 |
  • 59 |
  • An own value property of the object or one of its base objects, where the value is a function object.
  • 60 |
  • A dynamic property with a getter which returns a function object. This case is not supported by GetMethod.
  • 61 |
  • Handling within a __Call meta-function. Methods implemented this way cannot be detected and may not even have a corresponding function object, so are not supported by GetMethod.
  • 62 |
63 |

When calling the function object, it is necessary to supply a value for the normally-hidden this parameter. For example, Method(Value, Parameters*).

64 |

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.

65 |

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.

66 | 67 |

Related

68 |

Objects, HasMethod, HasBase, HasProp

69 | 70 |

Examples

71 |
72 |

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 |
79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /docs/lib/Goto.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Goto - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Goto

14 | 15 |

Jumps to the specified label and continues execution.

16 | 17 |
Goto Label
18 | Goto("Label")
19 |

Parameters

20 |
21 | 22 |
Label
23 |
24 |

Type: String

25 |

The name of the label to which to jump.

26 |
27 | 28 |
29 | 30 |

Remarks

31 |

Label can be a variable or expression only if parentheses are used. For example, Goto MyLabel and Goto("MyLabel") both jump to MyLabel:.

32 |

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 |

Related

37 |

Return, IsLabel, Else, Blocks, Break, Continue

38 |

Examples

39 |
40 |

Jumps to the label named "MyLabel" and continues execution.

41 |
Goto MyLabel
42 | ; ...
43 | MyLabel:
44 | Sleep 100
45 | ; ...
46 |
47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /docs/lib/GroupActivate.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | GroupActivate - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

GroupActivate

14 | 15 |

Activates the next window in a window group that was defined with GroupAdd.

16 | 17 |
HWND := GroupActivate(GroupName , Mode)
18 |

Parameters

19 |
20 | 21 |
GroupName
22 |
23 |

Type: String

24 |

The name of the group to activate, as originally defined by GroupAdd.

25 |
26 | 27 |
Mode
28 |
29 |

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 |
33 | 34 |
35 | 36 |

Return Value

37 |

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 |

Remarks

41 |

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 |

Related

47 |

GroupAdd, GroupDeactivate, GroupClose, #WinActivateForce

48 |

Examples

49 |
50 |

Activates the newest window (the one most recently active) in a window group.

51 |
GroupActivate "MyGroup", "R"
52 |
53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /docs/lib/GroupAdd.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | GroupAdd - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

GroupAdd

14 | 15 |

Adds a window specification to a window group, creating the group if necessary.

16 | 17 |
GroupAdd GroupName , WinTitle, WinText, ExcludeTitle, ExcludeText
18 |

Parameters

19 |
20 | 21 |
GroupName
22 |
23 |

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 |
26 | 27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 | 35 |
36 | 37 |

Remarks

38 |

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:

44 |
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 |

Related

47 |

GroupActivate, GroupDeactivate, GroupClose

48 |

Examples

49 |
50 |

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 |
59 | 60 |
61 |

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 |
75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /docs/lib/GroupClose.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | GroupClose - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

GroupClose

14 | 15 |

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 , Mode
18 |

Parameters

19 |
20 | 21 |
GroupName
22 |
23 |

Type: String

24 |

The name of the group as originally defined by GroupAdd.

25 |
26 | 27 |
Mode
28 |
29 |

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".

33 |
34 | 35 |
36 | 37 |

Remarks

38 |

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 |

Related

43 |

GroupAdd, GroupActivate, GroupDeactivate

44 |

Examples

45 |
46 |

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 |
49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /docs/lib/GroupDeactivate.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | GroupDeactivate - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

GroupDeactivate

14 | 15 |

Similar to GroupActivate except activates the next window not in the group.

16 | 17 |
GroupDeactivate GroupName , Mode
18 |

Parameters

19 |
20 | 21 |
GroupName
22 |
23 |

Type: String

24 |

The name of the target group, as originally defined by GroupAdd.

25 |
26 | 27 |
Mode
28 |
29 |

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 |
33 | 34 |
35 | 36 |

Remarks

37 |

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 |
    41 |
  • Owned windows, such as certain dialogs and tool windows, are not evaluated. However, if the owner window is eligible for activation, the most recently active owned window is activated instead, unless the owner was active more recently. This is determined by calling GetLastActivePopup.
  • 42 |
  • Windows with the WS_EX_TOPMOST or WS_EX_NOACTIVATE styles are skipped.
  • 43 |
  • Windows with the WS_EX_TOOLWINDOW style but without the WS_EX_APPWINDOW style are skipped. (These windows are generally also omitted from Alt-Tab and the taskbar.)
  • 44 |
  • Disabled windows are skipped, unless a window it owns (such as a modal dialog) was active more recently than the window itself.
  • 45 |
  • Hidden or cloaked windows are skipped.
  • 46 |
  • The Desktop is skipped.
  • 47 |
48 |

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 |

Related

51 |

GroupAdd, GroupActivate, GroupClose

52 |

Examples

53 |
54 |

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 |
57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /docs/lib/Gui.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Gui Object - Methods & Properties | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Gui Object

15 |
class Gui extends Object
16 | 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 |

Table of Contents

24 |
    25 |
  • Static Methods: 26 |
      27 |
    • Call: Creates a new window.
    • 28 |
    29 |
  • 30 |
  • Methods: 31 |
      32 |
    • Add: Creates a new control and adds it to the window.
    • 33 |
    • Destroy: Deletes the window.
    • 34 |
    • Flash: Blinks the window and its taskbar button.
    • 35 |
    • GetClientPos: Retrieves the position and size of the window's client area.
    • 36 |
    • GetPos: Retrieves the position and size of the window.
    • 37 |
    • Hide: Hides the window.
    • 38 |
    • Maximize: Unhides and maximizes the window.
    • 39 |
    • Minimize: Unhides and minimizes the window.
    • 40 |
    • Move: Moves and/or resizes the window.
    • 41 |
    • OnEvent: Registers a function or method to be called when the given event is raised.
    • 42 |
    • Opt: Sets various options and styles for the appearance and behavior of the window.
    • 43 |
    • Restore: Unhides and unminimizes or unmaximizes the window.
    • 44 |
    • SetFont: Sets the typeface, size, style, and text color for subsequently created controls.
    • 45 |
    • Show: Displays the window. It can also minimize, maximize, or move the window.
    • 46 |
    • Submit: Collects the values from named controls and composes them into an Object. Optionally hides the window.
    • 47 |
    • __Enum: Enumerates the window's controls.
    • 48 |
    • __New: Constructs a new Gui instance.
    • 49 |
    50 |
  • 51 |
  • Properties: 52 |
      53 |
    • BackColor: Retrieves or sets the background color of the window.
    • 54 |
    • FocusedCtrl: Retrieves the GuiControl object of the window's focused control.
    • 55 |
    • Hwnd: Retrieves the window handle (HWND) of the window.
    • 56 |
    • MarginX: Retrieves or sets the size of horizontal margins between sides and subsequently created controls.
    • 57 |
    • MarginY: Retrieves or sets the size of vertical margins between sides and subsequently created controls.
    • 58 |
    • MenuBar: Retrieves or sets the window's menu bar.
    • 59 |
    • Name: Retrieves or sets a custom name for the window.
    • 60 |
    • Title: Retrieves or sets the window's title.
    • 61 |
    • __Item: Retrieves the GuiControl object associated with the specified name, text, ClassNN or HWND.
    • 62 |
    63 |
  • 64 |
  • General: 65 |
      66 |
    • Keyboard Navigation
    • 67 |
    • Window Appearance
    • 68 |
    • General Remarks
    • 69 |
    • Related
    • 70 |
    • Examples
    • 71 |
    72 |
  • 73 |
74 | 75 |

Static Methods

76 |
77 |

Call

78 |

Creates a new window.

79 |
MyGui := Gui(Options, Title, EventObj)
 80 | MyGui := Gui.Call(Options, Title, EventObj)
81 |

Parameters

82 |
83 |
Options
84 |

Type: String

85 |

Any of the options supported by Gui.Opt.

86 |
87 |
Title
88 |

Type: String

89 |

If omitted, it defaults to A_ScriptName. Otherwise, specify the window title.

90 |
91 |
EventObj
92 |

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 |
95 |
96 |

Return Value

97 |

Type: Object

98 |

This method or function returns a Gui object.

99 |
100 | 101 |

Methods

102 |
103 |

Add

104 |

Creates a new control and adds it to the window.

105 |
GuiCtrl := MyGui.Add(ControlType , Options, Text)
106 | GuiCtrl := MyGui.AddControlType(Options, Text)
107 |

Parameters

108 |
109 |
ControlType
110 |

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()
117 |
Options
118 |

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.

124 |

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.

127 |

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).

128 |

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.

129 |

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.

130 |

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.

143 |

If only one component is omitted, its default value depends on which option was used to specify the other component:

144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 |
Specified XDefault for Y
Xn or XMBeneath all previous controls (maximum Y extent plus margin).
XSBeneath all previous controls since the most recent use of the Section option.
X+n or XP+nonzeroSame as the previous control's top edge (YP).
XP or XP+0Below the previous control (bottom edge plus margin).
Specified YDefault for X
Yn or YMTo the right of all previous controls (maximum X extent plus margin).
YSTo the right of all previous controls since the most recent use of the Section option.
Y+n or YP+nonzeroSame as the previous control's left edge (XP).
YP or YP+0To the right of the previous control (right edge plus margin).
156 | 157 |

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".

159 |

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.

163 |

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.

165 |

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.

166 |

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.

167 |

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.

172 |

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.

173 |

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).

175 | 176 |

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.

178 |

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.

179 |

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.

184 |
Text
Depending on the specified control type, a string, number or an array.
185 |
186 |

Return Value

187 |

Type: Object

188 |

This method returns a GuiControl object.

189 |
190 | 191 |
192 |

Destroy

193 |

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.

196 |
197 | 198 |
199 |

Flash

200 |

Blinks the window's button in the taskbar.

201 |
MyGui.Flash(Blink)
202 |

Parameters

203 |
204 |
Blink
205 |

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 |
210 |
211 |

Remarks

212 |

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 |
219 | 220 |
221 |

GetClientPos

222 |

Retrieves the position and size of the window's client area.

223 |
MyGui.GetClientPos(&X, &Y, &Width, &Height)
224 |

Parameters

225 |
226 |
&X, &Y
227 |
228 |

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 |
231 |
&Width, &Height
232 |
233 |

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 |
237 |
238 |

Remarks

239 |

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).

241 |
242 | 243 |
244 |

GetPos

245 |

Retrieves the position and size of the window.

246 |
MyGui.GetPos(&X, &Y, &Width, &Height)
247 |

Parameters

248 |
249 |
&X, &Y
250 |
251 |

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 |
254 |
&Width, &Height
255 |
256 |

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 |
260 |
261 |

Remarks

262 |

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).

264 |
265 | 266 |
267 |

Hide

268 |

Hides the window.

269 |
MyGui.Hide()
270 |
271 | 272 |
273 |

Maximize

274 |

Unhides the window (if necessary) and maximizes it.

275 |
MyGui.Maximize()
276 |
277 | 278 |
279 |

Minimize

280 |

Unhides the window (if necessary) and minimizes it.

281 |
MyGui.Minimize()
282 |
283 | 284 |
285 |

Move

286 |

Moves and/or resizes the window.

287 |
MyGui.Move(X, Y, Width, Height)
288 |

Parameters

289 |
290 |
X, Y
291 |
292 |

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 |
295 |
Width, Height
296 |
297 |

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 |
300 |
301 |

Remarks

302 |

Unlike WinMove, this method applies DPI scaling to Width and Height (unless the -DPIScale option was used).

303 |

Examples

304 |
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 |
311 | 312 |
313 |

OnEvent

314 |

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 |
318 | 319 |
320 |

Opt

321 |

Sets various options and styles for the appearance and behavior of the window.

322 |
MyGui.Opt(Options)
323 |

Parameters

324 |
325 |
Options
326 |

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").

331 |

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.

336 |

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 |
    338 |
  • Avoid using hard-coded coordinates wherever possible. For example, use the XP, XS, XM and X+M options for positioning controls and specify height in rows of text instead of pixels.
  • 339 |
  • Enable (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.
  • 340 |
  • Manually scale the coordinates. For example, x*(A_ScreenDPI/96) converts x from logical/GUI coordinates to physical/non-GUI coordinates.
  • 341 |
342 |

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.

349 |

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.

350 |

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.

351 |

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.

352 |

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").

353 |

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:

354 |
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.

357 |

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.

358 |

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:

359 |
    360 |
  • Running with UI access prevents the +Parent option from working on an existing window if the new parent is always-on-top and the child window is not.
  • 361 |
  • The +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.
  • 362 |
363 |

Resize: Makes the window resizable and enables its maximize button in the title bar. To avoid enabling the maximize button, specify +Resize -MaximizeBox.

364 |

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.

365 |

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.

366 |

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.

369 |
370 |
371 | 372 |
373 |

Restore

374 |

Unhides the window (if necessary) and unminimizes or unmaximizes it.

375 |
MyGui.Restore()
376 |
377 | 378 |
379 |

SetFont

380 |

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 |

Parameters

383 |
384 |
Options
385 |

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.

387 |

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.

388 |

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").

389 |

S: Size (in points). For example: s12 (specify decimal, not hexadecimal)

390 |

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)

391 |

Q: Text rendering quality. For example: q3. Q should be followed by a number from the following table:

392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 |
NumberWindows ConstantDescription
0DEFAULT_QUALITYAppearance of the font does not matter.
1DRAFT_QUALITYAppearance of the font is less important than when the PROOF_QUALITY value is used.
2PROOF_QUALITYCharacter quality of the font is more important than exact matching of the logical-font attributes.
3NONANTIALIASED_QUALITYFont is never antialiased, that is, font smoothing is not done.
4ANTIALIASED_QUALITYFont is antialiased, or smoothed, if the font supports it and the size of the font is not too small or too large.
5CLEARTYPE_QUALITYIf set, text is rendered (when possible) using ClearType antialiasing method.
429 |

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.

431 |
FontName
432 |

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.
437 |
438 |

Remarks

439 |

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 |
442 | 443 |
444 |

Show

445 |

By default, this makes the window visible, unminimizes it (if necessary) and activates it.

446 |
MyGui.Show(Options)
447 |

Parameters

448 |
449 |
Options
450 |

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").

459 |

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").

461 |

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").

468 |
469 |
470 | 471 |
472 |

Submit

473 |

Collects the values from named controls and composes them into an Object. Optionally hides the window.

474 |
NamedCtrlValues := MyGui.Submit(Hide)
475 |

Parameters

476 |
477 |
Hide
478 |

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 |
483 |
484 |

Return Value

485 |

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.

487 |

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 |

Also excluded: ListView, TreeView, ActiveX, Custom.

491 |
492 | 493 |
494 |

__Enum

495 |

Enumerates the window's controls.

496 |
For Ctrl in MyGui
497 |
For Hwnd, Ctrl in MyGui
498 |

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 |
500 |
Hwnd
501 |
502 |

Type: Integer

503 |

The control's HWND. This is present only in the two-parameter mode.

504 |
505 |
Ctrl
506 |
507 |

Type: Object

508 |

The control's GuiControl object.

509 |
510 |
511 |

For example:

512 |
For Hwnd, GuiCtrlObj in MyGui
513 |     MsgBox "Control #" A_Index " is " GuiCtrlObj.ClassNN
514 |
515 | 516 |
517 |

__New

518 |

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.

521 |

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 |
524 | 525 |

Properties

526 |
527 |

BackColor

528 |

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", "".

533 |

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").

535 |

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")

539 |

To illustrate the above, there is an example of an on-screen display (OSD) near the bottom of this page.

540 |
541 | 542 |
543 |

FocusedCtrl

544 |

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 |
548 | 549 |
550 |

Hwnd

551 |

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.

554 | 555 |
556 |

MarginX

557 |

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 |
564 | 565 |
566 |

MarginY

567 |

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 |
574 | 575 |
576 |

MenuBar

577 |

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.

593 |

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).

595 |
596 | 597 |
598 |

Name

599 |

Retrieves or sets a custom name for the window.

600 |
CurrentName := MyGui.Name
601 |
MyGui.Name := NewName
602 |
603 | 604 |
605 |

Title

606 |

Retrieves or sets the window's title.

607 |
CurrentTitle := MyGui.Title
608 |
MyGui.Title := NewTitle
609 |
610 | 611 |
612 |

__Item

613 |

Retrieves the GuiControl object associated with the specified name, text, ClassNN or HWND.

614 |
GuiCtrlObj := MyGui[Name]
615 | GuiCtrlObj := MyGui.__Item[Name]
616 |
617 | 618 |

Keyboard Navigation

619 |

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").

622 | 623 |

Window Appearance

624 |

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:

625 |
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 |

General Remarks

634 |

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 |

Related

641 |

GuiControl object, GuiFromHwnd, GuiCtrlFromHwnd, Control Types, ListView, TreeView, Menu object, Control functions, MsgBox, FileSelect, DirSelect

642 | 643 |

Examples

644 | 645 |
646 |

Creates a popup window.

647 |
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 |
652 | 653 |
654 |

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 |
670 | 671 |
672 |

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 |
694 | 695 |
696 |

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 |
716 | 717 |
718 |

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 |
749 | 750 |
751 |

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 |
769 | 770 |
771 |

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 |
794 | 795 |
796 |

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 |
825 | 826 |
827 |

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 |
959 | 960 |
961 |

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 |
990 | 991 | 992 | 993 | -------------------------------------------------------------------------------- /docs/lib/GuiControl.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | GuiControl Object - Methods & Properties | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

GuiControl Object

15 |
class Gui.Control extends Object
16 | 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.

20 |

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.

21 |

In addition to the methods and property inherited from Object, GuiControl objects may have the following predefined methods and properties.

22 | 23 |

Table of Contents

24 |
    25 |
  • Methods: 26 |
      27 |
    • Add: Appends items to a multi-item control.
    • 28 |
    • Choose: Selects an item in a multi-item control.
    • 29 |
    • Delete: Deletes one or all items from a multi-item control.
    • 30 |
    • Focus: Sets keyboard focus to the control.
    • 31 |
    • GetPos: Retrieves the position and size of the control.
    • 32 |
    • Move: Moves and/or resizes the control.
    • 33 |
    • OnCommand: Registers a function or method to be called on WM_COMMAND.
    • 34 |
    • OnEvent: Registers a function or method to be called when the given event is raised.
    • 35 |
    • OnNotify: Registers a function or method to be called on WM_NOTIFY.
    • 36 |
    • Opt: Sets various options and styles for the appearance and behavior of the control.
    • 37 |
    • Redraw: Redraws the region of the GUI window occupied by the control.
    • 38 |
    • SetFont: Sets the font typeface, size, style, and/or color for the control.
    • 39 |
    40 |
  • 41 |
  • Properties: 42 |
      43 |
    • ClassNN: Retrieves the class name and sequence number (ClassNN) of the control.
    • 44 |
    • Enabled: Retrieves or sets the interaction state of the control.
    • 45 |
    • Focused: Retrieves the focus state of the control.
    • 46 |
    • Gui: Retrieves the Gui object of the control's parent window.
    • 47 |
    • Hwnd: Retrieves the window handle (HWND) of the control.
    • 48 |
    • Name: Retrieves or sets the explicit name of the control.
    • 49 |
    • Text: Retrieves or sets the text/caption of the control.
    • 50 |
    • Type: Retrieves the type of the control.
    • 51 |
    • Value: Retrieves or sets the contents of a value-capable control.
    • 52 |
    • Visible: Retrieves or sets the visibility state of the control.
    • 53 |
    54 |
  • 55 |
  • General Remarks: 56 |
      57 |
    • Redraw: Performance-related remarks about redraw behaviour of controls.
    • 58 |
    59 |
  • 60 |
61 | 62 |

Methods

63 |
64 |

Add

65 |

Appends items to a multi-item control (ListBox, DropDownList, ComboBox, or Tab).

66 |
GuiCtrl.Add(Items)
67 |

Parameters

68 |
69 |
Items
70 |

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"].

72 |
73 |
74 |

Remarks

75 |

To replace (overwrite) the list instead, use the Delete method beforehand. To select an item, use the Choose method.

76 |

Related

77 |

ListView.Add, TreeView.Add

78 |
79 | 80 |
81 |

Choose

82 |

Selects an item in a multi-item control (ListBox, DropDownList, ComboBox, or Tab).

83 |
GuiCtrl.Choose(Value)
84 |

Parameters

85 |
86 |
Value
87 |

Type: Integer or String

88 |

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.

91 |
92 |

Remarks

93 |

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 |
99 | 100 |
101 |

Delete

102 |

Deletes one or all items from a multi-item control (ListBox, DropDownList, ComboBox, or Tab).

103 |
GuiCtrl.Delete(Value)
104 |

Parameters

105 |
106 |
Value
107 |

Type: Integer

108 |

If omitted, all items will be deleted. Otherwise, specify 1 for the first item, 2 for the second, etc.

109 |
110 |
111 |

Remarks

112 |

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.

113 |

Related

114 |

ListView.Delete, TreeView.Delete

115 |
116 | 117 |
118 |

Focus

119 |

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 |
124 | 125 |
126 |

GetPos

127 |

Retrieves the position and size of the control.

128 |
GuiCtrl.GetPos(&X, &Y, &Width, &Height)
129 |

Parameters

130 |
131 |
&X, &Y
132 |
133 |

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 |
136 |
&Width, &Height
137 |
138 |

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 |
141 |
142 |

Remarks

143 |

Unlike ControlGetPos, this method applies DPI scaling to the returned coordinates (unless the -DPIScale option was used).

144 |

Examples

145 |
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 |
149 | 150 |
151 |

Move

152 |

Moves and/or resizes the control.

153 |
GuiCtrl.Move(X, Y, Width, Height)
154 |

Parameters

155 |
156 |
X, Y
157 |
158 |

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 |
161 |
Width, Height
162 |
163 |

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 |
166 |
167 |

Remarks

168 |

Unlike ControlMove, this method applies DPI scaling to the coordinates (unless the -DPIScale option was used).

169 |

Examples

170 |
MyEdit.Move(10, 20, 200, 100)
171 | MyEdit.Move(VarX+10, VarY+5, VarW*2, VarH*1.5)
172 |
173 | 174 |
175 |

OnCommand

176 |

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 |
180 | 181 |
182 |

OnEvent

183 |

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 |
187 | 188 |
189 |

OnNotify

190 |

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 |
194 | 195 |
196 |

Opt

197 |

Sets various options and styles for the appearance and behavior of the control.

198 |
GuiCtrl.Opt(Options)
199 |

Parameters

200 |
201 |
Options
202 |

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 |
205 |
206 |

Remarks

207 |

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 |
213 | 214 |
215 |

Redraw

216 |

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 |
220 | 221 |
222 |

SetFont

223 |

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 |
228 | 229 |

Properties

230 |
231 |

ClassNN

232 |

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 |
237 | 238 |
239 |

Enabled

240 |

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.

246 |
247 | 248 |
249 |

Focused

250 |

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 |
256 | 257 |
258 |

Gui

259 |

Retrieves the Gui object of the control's parent window.

260 |
GuiObj := GuiCtrl.Gui
261 |
262 | 263 |
264 |

Hwnd

265 |

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 |
269 | 270 |
271 |

Name

272 |

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 |
278 | 279 |
280 |

Text

281 |

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.

289 | 290 |

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.

302 | 303 |

StatusBar

304 |

CurrentText and NewText are the text of the StatusBar control's first part only (use SB.SetText for greater flexibility).

305 |
306 | 307 |
308 |

Type

309 |

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 |
313 | 314 |
315 |

Value

316 |

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.

339 | 340 |

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.

347 |

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.

348 | 349 |

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.

352 | 353 |

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.

356 | 357 |

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.

360 |
361 | 362 |
363 |

Visible

364 |

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.

370 |
371 | 372 |

General Remarks

373 | 374 |

Redraw

375 |

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.

376 |

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.

377 | 378 | 379 | 380 | -------------------------------------------------------------------------------- /docs/lib/GuiControls.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | GUI Control Types - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 19 | 20 | 21 | 22 |

GUI Control Types

23 | 24 |

GUI control types are elements of interaction which can be added to a GUI window using Gui.Add.

25 | 26 |

Table of Contents

27 |
    28 |
  • ActiveX
  • 29 |
  • Button
  • 30 |
  • CheckBox
  • 31 |
  • ComboBox
  • 32 |
  • Custom
  • 33 |
  • DateTime
  • 34 |
  • DropDownList (or DDL)
  • 35 |
  • Edit
  • 36 |
  • GroupBox
  • 37 |
  • Hotkey
  • 38 |
  • Link
  • 39 |
  • ListBox
  • 40 |
  • ListView
  • 41 |
  • MonthCal
  • 42 |
  • Picture (or Pic)
  • 43 |
  • Progress
  • 44 |
  • Radio
  • 45 |
  • Slider
  • 46 |
  • StatusBar
  • 47 |
  • Tab3 / Tab2 / Tab
  • 48 |
  • Text
  • 49 |
  • TreeView
  • 50 |
  • UpDown
  • 51 |
52 | 53 |

ActiveX

54 |

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 |

Button

82 |

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 | Button 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").

95 |

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.

100 | 101 |

CheckBox

102 |

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 | CheckBox 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.

112 |

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.

115 | 116 |

ComboBox

117 |

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"].

118 |

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 | ComboBox 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 |

Custom

129 |

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 |

DateTime

195 |

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 | DateTime 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 |

DateTime Methods

205 |
206 |

SetFormat

207 |

Sets the display format of a DateTime control.

208 |
GuiCtrl.SetFormat(Format)
209 |

Parameters

210 |
Format
211 |

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.

217 |
218 |
219 | 220 |

DateTime Usage

221 |

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).

222 |

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 |

Keyboard navigation: Use the ↑/↓ arrow keys, the +/- numpad keys, and Home/End to increase or decrease the control's values. Use ← and → to move from field to field inside the control. Within the drop-down calendar, use the arrow keys to move from day to day; use PgUp/PgDn to move backward/forward by one month; and use Home/End to select the first/last day of the month.

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 |

DateTime Options

230 |

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.

232 |

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 |

DropDownList (or DDL)

239 |

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"].

240 |

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 | DDL 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.

247 |

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.

251 |

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 |

Edit

260 |

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 | Edit 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.

268 |

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").

269 |

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 |

Edit Options

276 |

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.

278 |

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.

282 |

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.

284 |

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.

286 |

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.

287 |

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.

289 |

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 |

GroupBox

293 |

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 | GroupBox 300 |

By default, a GroupBox's title may have only one line of text. This can be overridden by specifying Wrap in Options.

301 |

To specify the number of rows inside the control (or its height and width), see positioning and sizing of controls.

302 | 303 |

Hotkey

304 |

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 | Hotkey 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.

312 |

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.

313 |

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.

314 |

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 |
    318 |
  • 1: Prevent unmodified keys
  • 319 |
  • 2: Prevent Shift-only keys
  • 320 |
  • 4: Prevent Ctrl-only keys
  • 321 |
  • 8: Prevent Alt-only keys
  • 322 |
  • 16: Prevent Shift+Ctrl keys
  • 323 |
  • 32: Prevent Shift+Alt keys
  • 324 |
  • 64: This value is not supported (it will not behave correctly)
  • 325 |
  • 128: Prevent Shift+Ctrl+Alt keys
  • 326 |
327 |

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.

328 |

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 |

Link

331 |

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.

332 |

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 | Link 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 |

ListBox

361 |

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"].

362 |

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 | ListBox 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.

369 |

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.

373 | 374 |

ListBox Options

375 |

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:

377 |
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.

384 |

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 |

ListView

388 |

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 | ListView 395 |

See the separate ListView page for more information.

396 | 397 |

MonthCal

398 |

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 | MonthCal 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").

406 |

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.

407 |

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, "-").

410 |

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.

412 | 413 |

MonthCal Options

414 |

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.

415 |

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.

416 |

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 |

Picture (or Pic)

423 |

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.

429 |

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").

432 |

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.

441 | 442 |

Progress

443 |

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 | Progress 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 |

Progress Options

456 |

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.

457 |

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.

458 |

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.

459 |

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 |

Radio

464 |

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 | Radio 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.

474 |

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.

478 | 479 |

Slider

480 |

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 | Slider 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 |

Detecting Changes

492 |

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 |
495 |
Info
496 |
497 |

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 |
500 |
501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 |
ValueNameMeaning
0TB_LINEUPThe user pressed ← or ↑.
1TB_LINEDOWNThe user pressed → or ↓.
2TB_PAGEUPThe user pressed PgUp.
3TB_PAGEDOWNThe user pressed PgDn.
4TB_THUMBPOSITIONThe user moved the slider via the mouse wheel, or finished a drag-and-drop to a new position.
6TB_TOPThe user pressed Home to send the slider to the left or top side.
7TB_BOTTOMThe user pressed End to send the slider to the right or bottom side.
511 |

Only if the AltSubmit option is used:

512 | 513 | 514 | 515 | 516 |
ValueNameMeaning
5TB_THUMBTRACKThe user is currently dragging the slider via the mouse; that is, the mouse button is currently down.
8TB_ENDTRACKThe 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.
517 | 518 |

Slider Options

519 |

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.

520 |

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.

524 |

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.

526 |

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.

527 |

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).

528 |

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.

529 |

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).

530 |

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 |

StatusBar

534 |

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 | StatusBar 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 |

StatusBar Methods

546 | 547 |
548 |

SetText

549 |

Displays NewText in the specified part of the status bar.

550 |
GuiCtrl.SetText(NewText , PartNumber, Style)
551 |

Parameters

552 |
NewText
553 |

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.

PartNumber
555 |

Type: Integer

556 |

If omitted, it defaults to 1. Otherwise, specify an integer between 1 and 256.

Style
557 |

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.

559 |
560 | 561 |
562 |

SetParts

563 |

Divides the bar into multiple sections according to the specified widths (in pixels).

564 |
GuiCtrl.SetParts(Width1, Width2, ... Width255)
565 |

Parameters

566 |
Width1 ... Width255
567 |

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.

569 |

Return Value

570 |

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 |

Remarks

573 |

Any parts "deleted" by this method will start off with no text the next time they are shown (furthermore, their icons are automatically destroyed).

574 | 575 |
576 |

SetIcon

577 |

Displays a small icon to the left of the text in the specified part.

578 |
GuiCtrl.SetIcon(FileName , IconNumber, PartNumber)
579 |

Parameters

580 |
FileName
581 |

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.

583 |
IconNumber
584 |

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.

PartNumber
586 |

Type: Integer

587 |

If omitted, it defaults to 1. Otherwise, specify an integer between 1 and 256.

588 |

Return Value

589 |

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.
592 | 593 |

StatusBar Usage

594 |

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.

596 |

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").

597 |

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 |

Tab3 / Tab2 / Tab

602 |

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 |
    605 |
  • Tab3: Fixes some issues which affect Tab2 and Tab. Controls are placed within an invisible "tab dialog" which moves and resizes with the tab control. The tab control is themed by default.
  • 606 |
  • Tab2: Fixes rare redrawing problems in the original "Tab" control but introduces some other problems.
  • 607 |
  • Tab: Retained for backward compatibility because of differences in behavior between Tab2/Tab3 and Tab.
  • 608 |
609 |

For example:

610 |
MyGui.Add("Tab3",, ["General", "View", "Settings"])
611 |

Or:

612 |
MyGui.AddTab3(, ["General", "View", "Settings"])
613 |

Appearance:

614 | Tab 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 |

Tab Methods

618 |
619 |

UseTab

620 |

Specifies the tab to which subsequently created controls will be added.

621 |
GuiCtrl.UseTab(Value, ExactMatch)
622 |

Parameters

623 |
624 |
Value
625 |

Type: Integer or String

626 |

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 |
629 |
ExactMatch
630 |

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 |
635 |
636 |
637 | 638 |

Tab Usage

639 |

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.

640 |

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.

648 |

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 |

Tab3 vs. Tab2 vs. Tab

654 |

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 |
    661 |
  • The first time the Tab3 control ceases to be the current tab control. This can occur as a result of calling the UseTab method (with or without parameters) or creating another tab control.
  • 662 |
  • The first time Gui.Show is called for that particular Gui.
  • 663 |
664 |

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 |
    668 |
  • Tab and Tab2 allow their sub-controls to be mixed with other controls within the tab-key order.
  • 669 |
  • Tab2 puts its tab buttons after its sub-controls in the tab-key order.
  • 670 |
  • Tab3 groups its sub-controls within the tab-key order and puts them after its tab buttons.
  • 671 |
672 |

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 |
    675 |
  • BackgroundTrans has no effect inside a Tab2 control.
  • 676 |
  • WebBrowser controls do not redraw correctly.
  • 677 |
  • AnimateWindow and possibly other Win32 API calls can cause the tab's controls to disappear.
  • 678 |
679 |

Known issues with Tab:

680 |
    681 |
  • Activating a GUI window by clicking certain parts of its controls, such as scrollbars, might redraw improperly.
  • 682 |
  • BackgroundTrans has no effect if the Tab control contains a ListView.
  • 683 |
  • WebBrowser controls are invisible.
  • 684 |
685 | 686 |

Tab Options

687 |

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.

689 |

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).

692 |

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 |

Text

696 |

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 | Text 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 |

TreeView

728 |

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 | TreeView 735 |

See the separate TreeView page for more information.

736 | 737 |

UpDown

738 |

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 | UpDown 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 |

UpDown Options

754 |

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.

755 |

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).

757 |

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_SETBASE
763 |

However, this affects only the buddy control, not the UpDown's reported position.

764 |

See also: positioning and sizing of controls.

765 | 766 |

Related

767 |

ListView, TreeView, Gui(), Gui object, GuiControl object, Menu object

768 | 769 | 770 | 771 | -------------------------------------------------------------------------------- /docs/lib/GuiCtrlFromHwnd.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | GuiCtrlFromHwnd - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

GuiCtrlFromHwnd

15 | 16 |

Retrieves the GuiControl object of a GUI control associated with the specified window handle.

17 |
GuiControlObj := GuiCtrlFromHwnd(Hwnd)
18 | 19 |

Parameters

20 |
21 |
Hwnd
22 |
23 |

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 |
26 |
27 | 28 |

Return Value

29 |

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 |

Remarks

33 |

For example, a HWND of a GUI control can be retrieved via GuiControl.Hwnd, MouseGetPos or OnMessage.

34 | 35 |

Related

36 |

Gui(), Gui object, GuiControl object, GuiFromHwnd, Control Types, ListView, TreeView, Menu object, Control functions, MsgBox, FileSelect, DirSelect

37 | 38 |

Examples

39 |

See the ToolTip example on the Gui object page.

40 | 41 | 42 | -------------------------------------------------------------------------------- /docs/lib/GuiFromHwnd.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | GuiFromHwnd - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

GuiFromHwnd

15 | 16 |

Retrieves the Gui object of a GUI window associated with the specified window handle.

17 |
GuiObj := GuiFromHwnd(Hwnd , RecurseParent)
18 | 19 |

Parameters

20 |
21 |
Hwnd
22 |
23 |

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 |
26 |
RecurseParent
27 |
28 |

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 |
31 |
32 | 33 |

Return Value

34 |

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 |

Remarks

38 |

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 |

Related

41 |

Gui(), Gui object, GuiControl object, GuiCtrlFromHwnd, Control Types, ListView, TreeView, Menu object, Control functions, MsgBox, FileSelect, DirSelect

42 | 43 |

Examples

44 |
45 |

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 |
52 | 53 | 54 | -------------------------------------------------------------------------------- /docs/lib/GuiOnCommand.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | OnCommand (GUI) - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

OnCommand

15 |

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 |

Parameters

19 |
20 |
NotifyCode
21 |
22 |

Type: Integer

23 |

The control-defined notification code to monitor.

24 |
25 | 26 |
Callback
27 |
28 |

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(*).

35 |

The notes for OnEvent regarding this and bound functions also apply to OnCommand.

36 |

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 |
39 | 40 |
AddRemove
41 |
42 |

Type: Integer

43 |

If omitted, it defaults to 1. Otherwise, specify one of the following numbers:

44 |
    45 |
  • 1 = Call the callback after any previously registered callbacks.
  • 46 |
  • -1 = Call the callback before any previously registered callbacks.
  • 47 |
  • 0 = Do not call the callback.
  • 48 |
49 |
50 |
51 | 52 |

WM_COMMAND

53 |

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 |

Related

58 |

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 | OnEvent (GUI) - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

OnEvent

15 |

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 |

Parameters

20 |
21 |
EventName
22 |
23 |

Type: String

24 |

The name of the event. See Events further below.

25 |
26 | 27 |
Callback
28 |
29 |

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 |
34 | 35 |
AddRemove
36 |
37 |

Type: Integer

38 |

If omitted, it defaults to 1. Otherwise, specify one of the following numbers:

39 |
    40 |
  • 1 = Call the callback after any previously registered callbacks.
  • 41 |
  • -1 = Call the callback before any previously registered callbacks.
  • 42 |
  • 0 = Do not call the callback.
  • 43 |
44 |
45 |
46 | 47 |

Callback Parameters

48 |

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.

51 |

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).

53 |

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 |

Callback Return Value

56 |

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.

58 | 59 |

Callback Name

60 |

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.

61 | 62 |

Threads

63 |

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 |

Destroying the GUI

68 |

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 |

Events

71 |

The following events are supported by Gui objects:

72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 |
EventRaised when...
CloseThe window is closed.
ContextMenuThe user right-clicks within the window or presses Menu or Shift+F10.
DropFilesFiles/folders are dragged and dropped onto the window.
EscapeThe user presses Esc while the GUI window is active.
SizeThe window is resized, minimized, maximized or restored.
80 |

The following events are supported by GuiControl objects, depending on the control type:

81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 |
EventRaised when...
ChangeThe control's value changes.
ClickThe control is clicked.
DoubleClickThe control is double-clicked.
ColClickOne of the ListView's column headers is clicked.
ContextMenuThe user right-clicks the control or presses Menu or Shift+F10 while the control has the keyboard focus.
FocusThe control gains the keyboard focus.
LoseFocusThe control loses the keyboard focus.
ItemCheckA ListView or TreeView item is checked or unchecked.
ItemEditA ListView or TreeView item's label is edited by the user.
ItemExpandA TreeView item is expanded or collapsed.
ItemFocusThe focused item changes in a ListView.
ItemSelectA ListView or TreeView item is selected, or a ListView item is deselected.
96 | 97 |

Window Events

98 | 99 |

Close

100 |

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.

103 |

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 |

ContextMenu

114 |

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 |
GuiCtrlObj
117 |

Type: Object or String (empty)

118 |

The GuiControl object of the control that received the event (blank if none).

119 |
Item
120 |

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.

124 |
IsRightClick
125 |

Type: Integer (boolean)

126 |

One of the following values:

127 |
    128 |
  • 1 (true) = The user clicked the right mouse button.
  • 129 |
  • 0 (false) = The user pressed Menu or Shift+F10.
  • 130 |
131 |
X, Y
132 |

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.

134 |
135 |

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 |

DropFiles

140 |

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 |
143 |
GuiCtrlObj
144 |
145 |

Type: Object or String (empty)

146 |

The GuiControl object of the control upon which the files were dropped (blank if none).

147 | 148 |
FileArray
149 |
150 |

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:

152 |
Gui_DropFiles(GuiObj, GuiCtrlObj, FileArray, X, Y) {
153 |     for i, DroppedFile in FileArray
154 |         MsgBox "File " i " is:`n" DroppedFile
155 | }
156 | 157 |
X, Y
158 |
159 |

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 |
162 |
163 | 164 |

Escape

165 |

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 |

Size

170 |

Launched when the window is resized, minimized, maximized, or restored.

171 |
Gui_Size(GuiObj, MinMax, Width, Height)
172 |
173 |
MinMax
174 |

Type: Integer

175 |

One of the following values:

176 |
    177 |
  • 0 = The window is neither minimized nor maximized.
  • 178 |
  • 1 = The window is maximized.
  • 179 |
  • -1 = The window is minimized.
  • 180 |
181 |

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.

182 |
Width, Height
183 |

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.

185 |
186 |

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 -1
190 |

Gui.Show automatically does a Sleep -1, so it is generally not necessary to call Sleep in that case.

191 | 192 |

Control Events

193 | 194 |

Change

195 |

Raised when the control's value changes.

196 |
Ctrl_Change(GuiCtrlObj, Info)
197 |
198 |
Info
199 |
200 |

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 |
204 |
205 |

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 |

Click

209 |

Raised when the control is clicked.

210 |
Ctrl_Click(GuiCtrlObj, Info)
211 | Link_Click(GuiCtrlObj, Info, Href)
212 |
213 |
Info
214 |
215 |

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 |
222 |
Href
223 |
224 |

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 |
227 |
228 |

Applies to: Text, Pic, Button, CheckBox, Radio, ListView, TreeView, Link, StatusBar.

229 | 230 |

DoubleClick

231 |

Raised when the control is double-clicked.

232 |
Ctrl_DoubleClick(GuiCtrlObj, Info)
233 |
234 |
Info
235 |
236 |

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 |
240 |
241 |

Applies to: Text, Pic, Button, CheckBox, Radio, ComboBox, ListBox, ListView, TreeView, StatusBar.

242 | 243 |

ColClick

244 |

Raised when one of the ListView's column headers is clicked.

245 |
Ctrl_ColClick(GuiCtrlObj, Info)
246 |
247 |
Info
248 |
249 |

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 |
252 |
253 |

Applies to: ListView.

254 | 255 |

ContextMenu

256 |

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 |

Focus / LoseFocus

262 |

Raised when the control gains or loses the keyboard focus.

263 |
Ctrl_Focus(GuiCtrlObj, Info)
264 | Ctrl_LoseFocus(GuiCtrlObj, Info)
265 |
266 |
Info
267 |

Reserved.

268 |
269 |

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 |

ItemCheck

273 |

Raised when a ListView or TreeView item is checked or unchecked.

274 |
Ctrl_ItemCheck(GuiCtrlObj, Item, Checked)
275 |

Applies to: ListView, TreeView.

276 | 277 |

ItemEdit

278 |

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.

281 |

Applies to: ListView, TreeView.

282 | 283 |

ItemExpand

284 |

Raised when a TreeView item is expanded or collapsed.

285 |
Ctrl_ItemExpand(GuiCtrlObj, Item, Expanded)
286 |

Applies to: TreeView.

287 | 288 |

ItemFocus

289 |

Raised when the focused item changes in a ListView.

290 |
Ctrl_ItemFocus(GuiCtrlObj, Item)
291 |

Applies to: ListView.

292 | 293 |

ItemSelect

294 |

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 Events

302 |

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 | OnNotify (GUI) - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

OnNotify

15 |

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 |

Parameters

19 |
20 |
NotifyCode
21 |
22 |

Type: Integer

23 |

The control-defined notification code to monitor.

24 |
25 | 26 |
Callback
27 |
28 |

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 |
    35 |
  1. The GuiControl object of the current GUI control.
  2. 36 |
  3. The address of a notification structure derived from NMHDR. Its exact type depends on the type of control and notification code. If the structure contains additional information about the notification, the callback can retrieve it with NumGet and/or StrGet.
  4. 37 |
38 |

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, *).

39 |

The notes for OnEvent regarding this and bound functions also apply to OnNotify.

40 |

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 |
43 | 44 |
AddRemove
45 |
46 |

Type: Integer

47 |

If omitted, it defaults to 1. Otherwise, specify one of the following numbers:

48 |
    49 |
  • 1 = Call the callback after any previously registered callbacks.
  • 50 |
  • -1 = Call the callback before any previously registered callbacks.
  • 51 |
  • 0 = Do not call the callback.
  • 52 |
53 |
54 |
55 | 56 |

WM_NOTIFY

57 |

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 |

Related

62 |

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 | HasBase - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

HasBase

15 | 16 |

Returns a non-zero number if the specified value is derived from the specified base object.

17 | 18 |
HasBase := HasBase(Value, BaseObj)
19 |

Parameters

20 |
21 |
Value
22 |
23 |

Any value, of any type.

24 |
25 |
BaseObj
26 |
27 |

Type: Object

28 |

The potential base object to test.

29 |
30 |
31 | 32 |

Return Value

33 |

Type: Integer (boolean)

34 |

This function returns 1 (true) if BaseObj is in Value's chain of base objects, otherwise 0 (false).

35 | 36 |

Remarks

37 |

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.

46 |

HasBase accepts both objects and primitive values. For example, HasBase(1, 0.base) returns true.

47 | 48 |

Related

49 |

Objects, Obj.Base, ObjGetBase, HasMethod, HasProp

50 | 51 |

Examples

52 |
53 |

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 |
61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /docs/lib/HasMethod.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | HasMethod - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

HasMethod

15 | 16 |

Returns a non-zero number if the specified value has a method by the specified name.

17 | 18 |
HasMethod := HasMethod(Value , Name, ParamCount)
19 |

Parameters

20 |
21 |
Value
22 |
23 |

Type: Any

24 |

Any value, of any type except ComObject.

25 |
26 |
Name
27 |
28 |

Type: String

29 |

If omitted, Value itself is checked whether it is callable. Otherwise, specify the method name to check for.

30 |
31 |
ParamCount
32 |
33 | Type: Integer 34 |

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.

37 |
38 |
39 | 40 |

Return Value

41 |

Type: Integer (boolean)

42 |

This function returns 1 (true) if a method was found and passed validation (if performed), otherwise 0 (false).

43 | 44 |

Remarks

45 |

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 |

Related

52 |

Objects, HasBase, HasProp, GetMethod

53 | 54 |

Examples

55 |
56 |

Illustrates the use of this function.

57 |
58 | MsgBox HasMethod(0, "HasMethod") ; 1
59 | MsgBox HasMethod(0, "Call") ; 0
60 | 
61 |
62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /docs/lib/HasProp.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | HasProp - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

HasProp

15 | 16 |

Returns a non-zero number if the specified value has a property by the specified name.

17 | 18 |
HasProp := HasProp(Value, Name)
19 |

Parameters

20 |
21 |
Value
22 |
23 |

Type: Any

24 |

Any value, of any type except ComObject.

25 |
26 |
Name
27 |
28 |

Type: String

29 |

The property name to check for.

30 |
31 |
32 | 33 |

Return Value

34 |

Type: Integer (boolean)

35 |

This function returns 1 (true) if the value has a property by this name, otherwise 0 (false).

36 | 37 |

Remarks

38 |

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 |

Related

42 |

Objects, HasBase, HasMethod

43 | 44 |

Examples

45 |
46 |

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 |
53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /docs/lib/HotIf.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | HotIf / HotIfWin... - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

HotIf / HotIfWin...

15 | 16 |

Specifies the criteria for subsequently created or modified hotkey variants and hotstring variants.

17 | 18 |

HotIf

19 |
 20 | HotIf "Expression"
 21 | HotIf Callback
 22 | 
23 | 24 |

Parameters

25 |
26 | 27 |
"Expression"
28 |
29 |

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".

32 |

For an example, see #HotIf example #5.

33 |
34 | 35 |
Callback
36 |
37 |

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).

39 |

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(*).

43 |

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 |
46 | 47 |
48 | 49 |

HotIfWin...

50 |
 51 | HotIfWinActive WinTitle, WinText
 52 | HotIfWinExist WinTitle, WinText
 53 | HotIfWinNotActive WinTitle, WinText
 54 | HotIfWinNotExist WinTitle, WinText
 55 | 
56 | 57 |

Parameters

58 |
59 | 60 |
WinTitle, WinText
61 |
62 |

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 |
69 | 70 |
71 | 72 |

Error Handling

73 |

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 |

General Remarks

76 |

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.

81 |

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.

82 |

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 |

Related

85 |

Hotkeys, Hotstrings, Hotkey function, Hotstring function, #HotIf, Threads

86 | 87 |

Examples

88 |
89 |

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 |
102 |
103 |

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 |
124 | 125 | 126 | 127 | -------------------------------------------------------------------------------- /docs/lib/Hotkey.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Hotkey - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Hotkey

14 | 15 |

Creates, modifies, enables, or disables a hotkey while the script is running.

16 |
 17 | Hotkey KeyName , Action, Options
 18 | 
19 | 20 |

Parameters

21 |
22 | 23 |
KeyName
24 |
25 |

Type: String

26 |

Name of the hotkey's activation key, including any modifier symbols. For example, specify "#c" for the Win+C hotkey.

27 |

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.

29 |

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 |
33 | 34 |
Action
35 |
36 |

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 |
39 |

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(*).

44 |

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.

45 |

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 |
47 |

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 |
49 |

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 |
55 | 56 |
Options
57 |
58 |

Type: String

59 |

A string of zero or more of the following options with optional spaces in between. For example: "On B0".

60 |

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.

63 |

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.

66 |

In (InputLevel): Specify the letter I (or i) followed by the hotkey's input level. For example: I1.

67 |

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 |
69 | 70 |
71 | 72 |

Error Handling

73 |

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 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 |
Error Class.MessageDescription
ValueErrorInvalid key name.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.
Unsupported prefix key.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.
This AltTab hotkey must have exactly one modifier/prefix.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.
This AltTab hotkey must specify which key (L or R).
TargetErrorNonexistent hotkey.The function attempted to modify a nonexistent hotkey. Exception.Extra contains KeyName.
Nonexistent hotkey variant (IfWin).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.
ErrorMax hotkeys.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).
112 |

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 |

Remarks

121 |

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).

123 |

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 |

Variant (Duplicate) Hotkeys

130 |

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", MyFuncForAllOtherWindows
137 |

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.

139 |

For more information, see HotIf and #HotIf's General Remarks.

140 | 141 |

Related

142 |

Hotkeys, HotIf, A_ThisHotkey, #MaxThreadsBuffer, #MaxThreadsPerHotkey, Suspend, Threads, Thread, Critical, Return, Menu object, SetTimer, Hotstring function

143 | 144 |

Examples

145 |
146 |

Creates a Ctrl-Alt-Z hotkey.

147 |
Hotkey "^!z", MyFunc
148 | 
149 | MyFunc(ThisHotkey)
150 | {
151 |     MsgBox "You pressed " ThisHotkey
152 | }
153 |
154 | 155 |
156 |

Makes RCtrl & RShift operate like Alt-Tab.

157 |
Hotkey "RCtrl & RShift", "AltTab"
158 |
159 | 160 | 161 |
162 |

Disables the Shift-Win-C hotkey.

163 |
Hotkey "$+#c", "Off"
164 |
165 | 166 |
167 |

Changes a hotkey to allow 5 threads.

168 |
Hotkey "^!a",, "T5"
169 |
170 | 171 |
172 |

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 |
182 | 183 |
184 |

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 |
203 | 204 | 205 | 206 | -------------------------------------------------------------------------------- /docs/lib/Hotstring.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Hotstring - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Hotstring

14 | 15 |

Creates, modifies, enables, or disables a hotstring while the script is running.

16 | 17 |
Hotstring String , Replacement, OnOffToggle
 18 | Hotstring NewOptions
 19 | Hotstring SubFunction , Value1
20 | 21 |

Parameters

22 |
23 | 24 |
String
25 |
26 |

Type: String

27 |

The hotstring's trigger string, preceded by the usual colons and option characters. For example, "::btw" or ":*:]d".

28 |

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.

29 |

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.

30 |

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 |
32 | 33 |
Replacement
34 |
35 |

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(*).

42 |

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.

43 |

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.

45 |
46 | 47 |
OnOffToggle
48 |
49 |

Type: String or Integer

50 |

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 |
55 | 56 |
NewOptions
57 |
58 |

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".

60 |

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.

61 |
62 | 63 |
SubFunction, Value1
64 |
65 |

Type: String

66 |

These parameters are dependent upon each other and their usage is described below.

67 |
68 | 69 |
70 | 71 |

Sub-functions

72 |

For SubFunction, specify one of the following:

73 |
    74 |
  • EndChars: Retrieves or modifies the set of ending characters.
  • 75 |
  • MouseReset: Controls whether mouse clicks reset the hotstring recognizer.
  • 76 |
  • Reset: Immediately resets the hotstring recognizer.
  • 77 |
78 | 79 |

EndChars

80 |

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_chars
85 |

#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 |

MouseReset

89 |

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.

94 | 95 |

Reset

96 |

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 |

Errors

101 |

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 |

Remarks

109 |

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 |

Variant (Duplicate) Hotstrings

116 |

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:

117 |
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 |

Related

127 |

Hotstrings, HotIf, A_ThisHotkey, #MaxThreadsPerHotkey, Suspend, Threads, Thread, Critical, Hotkey function

128 | 129 |

Examples

130 | 131 |
132 |

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 |
205 | 206 | 207 | 208 | -------------------------------------------------------------------------------- /docs/lib/If.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | If - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

If

15 |

Specifies one or more statements to execute if an expression evaluates to true.

16 |
If Expression
 17 | {
 18 |     Statements
 19 | }
20 | 21 |

Remarks

22 |

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).

25 |

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 |

Related

40 |

Expressions, Ternary operator (a?b:c), Blocks, Else, While-loop

41 | 42 |

Examples

43 |
44 |

If A_Index is greater than 100, return.

45 |
if (A_Index > 100)
 46 |     return
47 |
48 | 49 |
50 |

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.

51 |
if (A_TickCount - StartTime > 2*MaxTime + 100)
 52 | {
 53 |     MsgBox "Too much time has passed."
 54 |     ExitApp
 55 | }
56 |
57 | 58 |
59 |

This example is executed as follows:

60 |
    61 |
  1. If Color is the word "Blue" or "White": 62 |
      63 |
    1. Show "The color is one of the allowed values.".
    2. 64 |
    3. Terminate the script.
    4. 65 |
    66 |
  2. 67 |
  3. Otherwise if Color is the word "Silver": 68 |
      69 |
    1. Show "Silver is not an allowed color.".
    2. 70 |
    3. Stop further checks.
    4. 71 |
    72 |
  4. 73 |
  5. Otherwise: 74 |
      75 |
    1. Show "This color is not recognized.".
    2. 76 |
    3. Terminate the script.
    4. 77 |
    78 |
  6. 79 |
80 |
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 |
96 |
97 |

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 |
104 | 105 |
106 |

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 |
126 | 127 |
128 |

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 |
154 | 155 | 156 | 157 | -------------------------------------------------------------------------------- /docs/lib/ImageSearch.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ImageSearch - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ImageSearch

14 | 15 |

Searches a region of the screen for an image.

16 | 17 |
ImageSearch &OutputVarX, &OutputVarY, X1, Y1, X2, Y2, ImageFile
18 |

Parameters

19 |
20 | 21 |
&OutputVarX, &OutputVarY
22 |
23 |

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 |
26 | 27 |
X1, Y1
28 |
29 |

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 |
32 | 33 |
X2, Y2
34 |
35 |

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 |
38 | 39 |
ImageFile
40 |
41 |

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".

44 |

*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.

45 |

*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.

46 |

*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.

47 |

*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.

48 |

A bitmap or icon handle can be used instead of a filename. For example, "HBITMAP:*" handle.

49 |
50 | 51 |
52 | 53 |

Return Value

54 |

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 |

Error Handling

58 |

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 |

Remarks

62 |

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 |
    65 |
  1. Press Alt+PrtSc while the image is visible in the active window. This places a screenshot on the clipboard.
  2. 66 |
  3. Open an image processing program such as Paint.
  4. 67 |
  5. Paste the contents of the clipboard (that is, the screenshot).
  6. 68 |
  7. Select a region that does not vary and that is unique to the image.
  8. 69 |
  9. Copy and paste that region to a new image document.
  10. 70 |
  11. Save it as a small file for use with ImageSearch.
  12. 71 |
72 |

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").

79 |

Related

80 |

PixelSearch, PixelGetColor, CoordMode, MouseGetPos

81 |

Examples

82 |
83 |

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 |
86 |
87 |

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 |
100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /docs/lib/InStr.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | InStr - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

InStr

14 | 15 |

Searches for a given occurrence of a string, from the left or the right.

16 | 17 |
FoundPos := InStr(Haystack, Needle , CaseSense, StartingPos, Occurrence)
18 |

Parameters

19 |
20 | 21 |
Haystack
22 |
23 |

Type: String

24 |

The string whose content is searched.

25 |
26 | 27 |
Needle
28 |
29 |

Type: String

30 |

The string to search for.

31 |
32 | 33 |
CaseSense
34 |
35 |

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 |
41 | 42 |
StartingPos
43 |
44 |

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.

48 |

If the absolute value of StartingPos is greater than the length of Haystack, 0 is returned.

49 |
50 | 51 |
Occurrence
52 |
53 |

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 |
58 | 59 |
60 | 61 |

Return Value

62 |

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).

66 | 67 |

Error Handling

68 |

A ValueError is thrown in any of the following cases:

69 |
    70 |
  • Needle is an empty (zero-length) string.
  • 71 |
  • CaseSense is invalid.
  • 72 |
  • Occurrence or StartingPos is 0 or non-numeric.
  • 73 |
74 | 75 |

Remarks

76 |

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 |

Related

80 |

RegExMatch, Is functions

81 | 82 |

Examples

83 |
84 |

Reports the 1-based position of the substring "abc" in the string "123abc789".

85 |
MsgBox InStr("123abc789", "abc") ; Returns 4
86 |
87 | 88 |
89 |

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 |
97 | 98 |
99 |

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 |
106 | 107 | 108 | 109 | -------------------------------------------------------------------------------- /docs/lib/IniDelete.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | IniDelete - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

IniDelete

14 | 15 |

Deletes a value from a standard format .ini file.

16 | 17 |
IniDelete Filename, Section , Key
18 |

Parameters

19 |
20 | 21 |
Filename
22 |
23 |

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 |
26 | 27 |
Section
28 |
29 |

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 |
32 | 33 |
Key
34 |
35 |

Type: String

36 |

If omitted, the entire section will be deleted. Otherwise, specify the key name in the .ini file.

37 |
38 | 39 |
40 |

Error Handling

41 |

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 |

Remarks

45 |

A standard ini file looks like:

46 |
[SectionName]
47 | Key=Value
48 |

Related

49 |

IniRead, IniWrite, RegDelete, RegDeleteKey

50 |

Examples

51 |
52 |

Deletes a key and its value located in section2 from a standard format .ini file.

53 |
IniDelete "C:\Temp\myfile.ini", "section2", "key"
54 |
55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /docs/lib/IniRead.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | IniRead - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

IniRead

14 | 15 |

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 ,, Default)
19 | SectionNames := IniRead(Filename ,,, Default)
20 |

Parameters

21 |
22 | 23 |
Filename
24 |
25 |

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 |
28 | 29 |
Section
30 |
31 |

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 |
34 | 35 |
Key
36 |
37 |

Type: String

38 |

The key name in the .ini file.

39 |
40 | 41 |
Default
42 |
43 |

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 |
46 | 47 |
48 | 49 |

Return Value

50 |

Type: String

51 |

This function returns one of the following depending on the Key and Section parameters:

52 |
    53 |
  • If both parameters are specified, this function returns the actual value of the specified key.
  • 54 |
  • If Key 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.
  • 55 |
  • If Key and Section are omitted, this function returns a linefeed (`n) delimited list of section names.
  • 56 |
57 |

If none of these can be retrieved, the default value indicated by the Default parameter is returned.

58 | 59 |

Error Handling

60 |

An OSError is thrown on failure, but only if Default is omitted.

61 |

Regardless of whether an exception is thrown, A_LastError is set to the result of the operating system's GetLastError() function.

62 | 63 |

Remarks

64 |

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.

65 |

Values longer than 65,535 characters are likely to yield inconsistent results.

66 |

A standard ini file looks like:

67 |
[SectionName]
68 | Key=Value
69 |

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.

70 |

Related

71 |

IniDelete, IniWrite, RegRead, file-reading loop, FileRead

72 |

Examples

73 |
74 |

Reads the value of a key located in section2 from a standard format .ini file and stores it in Value.

75 |
Value := IniRead("C:\Temp\myfile.ini", "section2", "key")
76 | MsgBox "The value is " Value
77 |
78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /docs/lib/IniWrite.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | IniWrite - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

IniWrite

14 | 15 |

Writes a value or section to a standard format .ini file.

16 | 17 |
IniWrite Value, Filename, Section, Key
18 | IniWrite Pairs, Filename, Section
19 |

Parameters

20 |
21 | 22 |
Value
23 |
24 |

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 |
28 | 29 |
Pairs
30 |
31 |

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 |
34 | 35 |
Filename
36 |
37 |

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 |
40 | 41 |
Section
42 |
43 |

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 |
46 | 47 |
Key
48 |
49 |

Type: String

50 |

The key name in the .ini file.

51 |
52 | 53 |
54 |

Error Handling

55 |

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 |

Remarks

59 |

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=Value
63 |

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 |

Related

74 |

IniDelete, IniRead, RegWrite

75 |

Examples

76 |
77 |

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 |
80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /docs/lib/InputBox.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | InputBox - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

InputBox

14 | 15 |

Displays an input box to ask the user to enter a string.

16 | 17 |
InputBoxObj := InputBox(Prompt, Title, Options, Default)
18 |

Parameters

19 |
20 | 21 |
Prompt
22 |
23 |

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 |
26 | 27 |
Title
28 |
29 |

Type: String

30 |

If omitted, it defaults to the current value of A_ScriptName. Otherwise, specify the title of the input box.

31 |
32 | 33 |
Options
34 |
35 |

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).

38 |

Wn and Hn: The width and height of the dialog's client area, which excludes the title bar and borders. For example, w200 h100.

39 |

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.

40 |

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).

41 |
42 | 43 |
Default
44 |
45 |

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 |
48 | 49 |
50 | 51 |

Return Value

52 |

Type: Object

53 |

This function returns an object with the following properties:

54 |
    55 |
  • Value (String): The text entered by the user.
  • 56 |
  • Result (String): One of the following words indicating how the input box was closed: OK, Cancel, or Timeout.
  • 57 |
58 | 59 |

Remarks

60 |

An input box usually looks like this:

61 | InputBox 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 |

Related

65 |

Gui object, MsgBox, FileSelect, DirSelect, ToolTip, InputHook

66 |

Examples

67 |
68 |

Allows the user to enter a hidden password.

69 |
password := InputBox("(your input will be hidden)", "Enter Password", "password").value
70 |
71 | 72 |
73 |

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 |
80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /docs/lib/InputHook.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | InputHook - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

InputHook

14 | 15 |

Creates an object which can be used to collect or intercept keyboard input.

16 | 17 |
InputHookObj := InputHook(Options, EndKeys, MatchList)
18 |

Parameters

19 |
20 | 21 |
Options
22 |
23 |

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.

28 |

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.

29 |

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.

30 |

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).

40 |

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 |
44 | 45 |
EndKeys
46 |
47 |

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 {}}.

50 |

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}".

51 |

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.

52 |

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.

53 |
54 | 55 |
MatchList
56 |
57 |

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.

59 |

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".

60 |

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.

61 |
62 | 63 |
64 | 65 |

Input Stack

66 |

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 |

InputHook Object

72 |

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 |
    75 |
  • Methods: 76 |
      77 |
    • KeyOpt: Sets options for a key or list of keys.
    • 78 |
    • Start: Starts collecting input.
    • 79 |
    • Stop: Terminates the Input and sets EndReason to the word Stopped.
    • 80 |
    • Wait: Waits until the Input is terminated (InProgress is false).
    • 81 |
    82 |
  • 83 |
  • General Properties: 84 |
      85 |
    • EndKey: Returns the name of the end key which was pressed to terminate the Input.
    • 86 |
    • EndMods: Returns a string of the modifiers which were logically down when Input was terminated.
    • 87 |
    • EndReason: Returns an EndReason string indicating how Input was terminated.
    • 88 |
    • InProgress: Returns 1 (true) if the Input is in progress, otherwise 0 (false).
    • 89 |
    • Input: Returns any text collected since the last time Input was started.
    • 90 |
    • Match: Returns the MatchList item which caused the Input to terminate.
    • 91 |
    • OnEnd: Retrieves or sets the function object which is called when Input is terminated.
    • 92 |
    • OnChar: Retrieves or sets the function object which is called after a character is added to the input buffer.
    • 93 |
    • OnKeyDown: Retrieves or sets the function object which is called when a notification-enabled key is pressed.
    • 94 |
    • OnKeyUp: Retrieves or sets the function object which is called when a notification-enabled key is released.
    • 95 |
    96 |
  • 97 |
  • Option Properties: 98 |
      99 |
    • BackspaceIsUndo: Controls whether the Backspace key removes the most recently pressed character from the end of the Input buffer.
    • 100 |
    • CaseSensitive: Controls whether MatchList is case-sensitive.
    • 101 |
    • FindAnywhere: Controls whether each match can be a substring of the input text.
    • 102 |
    • MinSendLevel: Retrieves or sets the minimum send level of input to collect.
    • 103 |
    • NotifyNonText: Controls whether the OnKeyDown and OnKeyUp callbacks are called whenever a non-text key is pressed.
    • 104 |
    • Timeout: Retrieves or sets the timeout value in seconds.
    • 105 |
    • VisibleNonText: Controls whether keys or key combinations which do not produce text are visible (not blocked).
    • 106 |
    • VisibleText: Controls whether keys or key combinations which produce text are visible (not blocked).
    • 107 |
    108 |
  • 109 |
110 | 111 |

Methods

112 |

KeyOpt

113 |

Sets options for a key or list of keys.

114 |
InputHookObj.KeyOpt(Keys, KeyOptions)
115 |

Parameters

116 |
117 |
Keys
118 |
119 |

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.

121 |

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.

122 |

Specify {sc000} to apply KeyOptions to all events which lack a scan code.

123 |

Specify {vkE7} to apply KeyOptions to Unicode events, such as those sent by SendEvent "{U+221e}" or SendEvent "{Text}∞".

124 |
125 |
KeyOptions
126 |
127 |

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 +.

130 |

+ (plus): Cancels any previous -, otherwise has no effect.

131 |

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.

132 |

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.

135 |

V: Visible. Prevents the key from being suppressed (blocked). This overrides VisibleText or VisibleNonText until -V is used. +V implies -S.

136 |
137 |
138 |

Remarks

139 |

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:

144 |
InputHookObj.KeyOpt("{All}", "+I")  ; Ignore text produced by any event
145 | InputHookObj.KeyOpt("{vkE7}{sc000}", "-I")  ; except Unicode events.
146 |
147 | 148 |

Start

149 |

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 |
155 | 156 |

Stop

157 |

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 |
161 | 162 |

Wait

163 |

Waits until the Input is terminated (InProgress is false).

164 |
EndReason := InputHookObj.Wait(MaxTime)
165 |

Parameters

166 |
167 |
MaxTime
168 |
169 |

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 |
172 |
173 |

Return Value

174 |

Type: String

175 |

This method returns EndReason.

176 |
177 | 178 |

General Properties

179 |

EndKey

180 |

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.

183 |

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 |
186 | 187 |

EndMods

188 |

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 ^!+#:

194 |
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 |
197 | 198 |

EndReason

199 |

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 |
203 | 204 |

InProgress

205 |

Returns 1 (true) if the Input is in progress, otherwise 0 (false).

206 |
Boolean := InputHookObj.InProgress
207 |
208 | 209 |

Input

210 |

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 |
214 | 215 |

Match

216 |

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 |
220 | 221 |

OnEnd

222 |

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(*).

230 |

The function is called as a new thread, so starts off fresh with the default values for settings such as SendMode and DetectHiddenWindows.

231 |
232 | 233 |

OnChar

234 |

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 |
    242 |
  1. A reference to the InputHook object.
  2. 243 |
  3. A string containing the character (or multiple characters, see below for details).
  4. 244 |
245 |

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, *).

246 |

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.

247 |

The function is never called when an end key is pressed.

248 |
249 | 250 |

OnKeyDown

251 |

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 |
    260 |
  1. A reference to the InputHook object.
  2. 261 |
  3. An integer representing the virtual key code of the key.
  4. 262 |
  5. An integer representing the scan code of the key.
  6. 263 |
264 |

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, *).

265 |

To retrieve the key name (if any), use GetKeyName(Format("vk{:x}sc{:x}", VK, SC)).

266 |

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 |
269 | 270 |

OnKeyUp

271 |

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 |
    280 |
  1. A reference to the InputHook object.
  2. 281 |
  3. An integer representing the virtual key code of the key.
  4. 282 |
  5. An integer representing the scan code of the key.
  6. 283 |
284 |

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, *).

285 |

To retrieve the key name (if any), use GetKeyName(Format("vk{:x}sc{:x}", VK, SC)).

286 |

The function is called as a new thread, so starts off fresh with the default values for settings such as SendMode and DetectHiddenWindows.

287 |
288 | 289 |

Option Properties

290 |

BackspaceIsUndo

291 |

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 |
300 | 301 |

CaseSensitive

302 |

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 |
308 | 309 |

FindAnywhere

310 |

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 |
316 | 317 |

MinSendLevel

318 |

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 |
325 | 326 |

NotifyNonText

327 |

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 |
335 | 336 |

Timeout

337 |

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 |
344 | 345 |

VisibleNonText

346 |

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 |
353 | 354 |

VisibleText

355 |

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).

361 |

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 |
365 | 366 |

EndReason

367 |

The EndReason property returns one of the following strings:

368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 394 | 395 | 396 | 397 | 398 | 399 |
StringDescription
StoppedThe Stop method was called or the Start method has not yet been called for the first time.
MaxThe Input reached the maximum allowed length and it does not match any of the items in MatchList.
TimeoutThe Input timed out.
MatchThe Input matches one of the items in MatchList. The Match property contains the matched item.
EndKey 392 |

One of the EndKeys was pressed to terminate the Input. The EndKey property contains the terminating key name or character without braces.

393 |
If the Input is in progress, EndReason is blank.
400 | 401 |

Remarks

402 |

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.

405 |

Keys are either suppressed (blocked) or not depending on the following factors (in order):

406 |
    407 |
  • If the V option is in effect for this VK or SC, it is not suppressed.
  • 408 |
  • If the S option is in effect for this VK or SC, it is suppressed.
  • 409 |
  • If the key is a standard modifier key or CapsLock, NumLock or ScrollLock, it is not suppressed.
  • 410 |
  • VisibleText or VisibleNonText is consulted, depending on whether the key produces text. If the property is 0 (false), the key is suppressed. See VisibleText for details about which keys are counted as producing text.
  • 411 |
412 |

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 |

InputHook vs. Input (v1)

419 |

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 |
    432 |
  • The Input command limits the length of the input to 16383, while InputHook limits it to 1023. This can be overridden with the L option, and there is no absolute maximum.
  • 433 |
  • The Input command blocks both text and non-text keystrokes by default, and blocks neither if the V option is present. By contrast, InputHook blocks only text keystrokes by default (VisibleNonText defaults to true), so most hotkeys can be used while an Input is in progress.
  • 434 |
435 |

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 |
    443 |
  • The Input command stores end keys A-Z in uppercase even though other letters on some keyboard layouts are lowercase. Passing the value to Send would produce a shifted keystroke instead of a plain one. By contrast, InputHook's EndKeys property always returns the normalized name; i.e. whichever character is produced by pressing the key without holding Shift or other modifiers.
  • 444 |
  • 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.

    445 |

    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 the ↑ arrow key on the main keyboard, but ErrorLevel would contain EndKey:NumpadUp since only the VK is considered.

    446 |

    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.

  • 447 |
448 | 449 |

Related

450 |

KeyWait, Hotstrings, InputBox, InstallKeybdHook, Threads

451 | 452 |

Examples

453 |
454 |

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 |
473 |
474 |

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 |
492 |
493 |

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 |
529 |
530 |

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 |
535 |
536 |

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.

537 |
~[::
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 |
569 | 570 | 571 | 572 | -------------------------------------------------------------------------------- /docs/lib/InstallKeybdHook.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | InstallKeybdHook - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

InstallKeybdHook

15 | 16 |

Installs or uninstalls the keyboard hook.

17 |
InstallKeybdHook Install, Force
18 | 19 |

Parameters

20 |
21 | 22 |
Install
23 |
24 |

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 |
29 | 30 |
Force
31 |
32 |

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 |
38 | 39 |
40 | 41 |

Remarks

42 |

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 |
    46 |
  • KeyHistory can be used to display the last 20 keystrokes (for debugging purposes).
  • 47 |
  • The physical state of the modifier keys can be tracked reliably, which removes the need for A_HotkeyModifierTimeout and may improve the reliability with which Send restores the modifier keys to their proper states after temporarily releasing them.
  • 48 |
  • GetKeyState can retrieve the physical state of a key.
  • 49 |
  • A_TimeIdleKeyboard and A_TimeIdlePhysical can work correctly (ignoring mouse input or artificial input, respectively).
  • 50 |
  • Mouse hotkeys which use the Alt modifier (such as !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.
  • 51 |
52 |

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 |

Related

56 |

InstallMouseHook, #UseHook, Hotkey, InputHook, KeyHistory, Hotstrings, GetKeyState, KeyWait

57 |

Examples

58 |
59 |

Installs the keyboard hook unconditionally.

60 |
InstallKeybdHook
61 |
62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /docs/lib/InstallMouseHook.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | InstallMouseHook - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

InstallMouseHook

15 | 16 |

Installs or uninstalls the mouse hook.

17 |
InstallMouseHook Install, Force
18 | 19 |

Parameters

20 |
21 | 22 |
Install
23 |
24 |

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 |
29 | 30 |
Force
31 |
32 |

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 |
38 | 39 |
40 | 41 |

Remarks

42 |

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 |
    46 |
  • KeyHistory can be used to monitor mouse clicks.
  • 47 |
  • GetKeyState can retrieve the physical state of a button.
  • 48 |
  • A_TimeIdleMouse and A_TimeIdlePhysical can work correctly (ignoring keyboard input or artificial input, respectively).
  • 49 |
50 |

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 |

Related

53 |

InstallKeybdHook, #UseHook, Hotkey, KeyHistory, GetKeyState, KeyWait

54 |

Examples

55 |
56 |

Installs the mouse hook unconditionally.

57 |
InstallMouseHook
58 |
59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /docs/lib/Integer.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Integer - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Integer

15 |

Converts a numeric string or floating-point value to an integer.

16 |
IntValue := Integer(Value)
17 | 18 |

Return Value

19 |

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 |

Remarks

23 |

Any fractional part of Value is dropped, equivalent to Value < 0 ? Ceil(Value) : Floor(Value).

24 |

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.

27 | 28 |

Related

29 |

Type, Float, Number, String, Values, Expressions, Is functions

30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /docs/lib/Is.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | List of Is Functions - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Is Functions

15 |

Functions for checking the type and other conditions of a given value.

16 |
Result := IsSomething(Value , Mode)
17 | 18 |

There are three categories:

19 |
    20 |
  • Type: Check the type of a value, or whether a string can be interpreted as a value of that type.
  • 21 |
  • Misc: Check miscellaneous conditions based on a given value or variable reference.
  • 22 |
  • String: Check whether a string matches a specific pattern.
  • 23 |
24 |

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.

25 | 26 |

Type

27 |

Check the type of a value, or whether a string can be interpreted as a value of that type.

28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 |
FunctionDescription
IsIntegerTrue 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.
IsFloatTrue 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.
IsNumberTrue if IsInteger(Value) or IsFloat(Value) is true.
IsObjectTrue 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.
50 | 51 |

Misc

52 |

Check miscellaneous conditions based on a given value or variable reference.

53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 |
FunctionDescription
IsLabelTrue if Value is the name of a label defined within the current scope.
IsSetTrue if the variable Value has been assigned a value.
IsSetRefTrue if the VarRef contained by Value has been assigned a value.
71 | 72 |

String

73 |

Check whether a string matches a specific pattern. Value must be a string, otherwise a TypeError is thrown.

74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 93 | 94 | 95 | 96 | 100 | 101 | 102 | 103 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 122 | 123 |
FunctionDescription
IsDigitTrue 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.
IsXDigitHexadecimal digit: Same as IsDigit except the characters A through F (uppercase or lowercase) are also allowed. A prefix of 0x is tolerated if present.
IsAlpha 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 IsAlpha(Value, "Locale").

92 |
IsUpper 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 IsUpper(Value, "Locale").

99 |
IsLower 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 IsLower(Value, "Locale").

106 |
IsAlnumSame as IsAlpha except that integers and characters 0 through 9 are also allowed.
IsSpaceTrue 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).
IsTime

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 |
124 | 125 |

Remarks

126 |

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.

127 | 128 |

Related

129 |

A_YYYY, FileGetTime, If, StrLen, InStr, StrUpper, DateAdd

130 | 131 |

Examples

132 |
133 |

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 |
143 | 144 | 145 | 146 | -------------------------------------------------------------------------------- /docs/lib/IsLabel.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | IsLabel - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

IsLabel

14 | 15 |

Returns a non-zero number if the specified label exists in the current scope.

16 | 17 |
Boolean := IsLabel(LabelName)
18 |

Parameters

19 |
20 | 21 |
LabelName
22 |
23 |

Type: String

24 |

The name of a label. The trailing colon should not be included.

25 |
26 | 27 |
28 | 29 |

Return Value

30 |

Type: Integer (boolean)

31 |

This function returns 1 (true) if the specified label exists within the current scope, otherwise 0 (false).

32 | 33 |

Remarks

34 |

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 |

Related

38 |

Labels

39 |

Examples

40 |
41 |

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 | return
49 |
50 | 51 | 52 | -------------------------------------------------------------------------------- /docs/lib/IsObject.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | IsObject - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

IsObject

14 | 15 |

Returns a non-zero number if the specified value is an object.

16 | 17 |
Boolean := IsObject(Value)
18 |

Parameters

19 |
20 | 21 |
Value
22 |
23 |

Type: Any

24 |

The value to check.

25 |
26 | 27 |
28 | 29 |

Return Value

30 |

Type: Integer (boolean)

31 |

This function returns 1 (true) if Value is an object, otherwise 0 (false).

32 | 33 |

Remarks

34 |

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 |
    36 |
  • Each object is dynamically allocated and reference-counted. Any number of variables, properties or array elements may refer to the same object. For immutable values this distinction isn't important, but objects can have mutable properties.
  • 37 |
  • Each object has a unique address which is also an interface pointer compatible with IDispatch.
  • 38 |
  • An object compares equal to another value only if it is the same object.
  • 39 |
  • An object cannot be implicitly converted to a string or number.
  • 40 |
41 | 42 |

Related

43 |

Objects

44 |

Examples

45 |
46 |

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 |
54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /docs/lib/IsSet.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | IsSet / IsSetRef - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

IsSet / IsSetRef

14 | 15 |

Returns a non-zero number if the specified variable has been assigned a value.

16 | 17 |
Boolean := IsSet(Var)
18 | Boolean := IsSetRef(&Ref)
19 |

Parameters

20 |
21 | 22 |
Var
23 |
24 |

Type: Variable

25 |

A direct variable reference. For example: IsSet(MyVar).

26 |
27 | 28 |
&Ref
29 |
30 |

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.

32 |
33 | 34 |
35 | 36 |

Return Value

37 |

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 |

Remarks

41 |

Use IsSet to check a variable directly, as in IsSet(MyGlobalVar).

42 |

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.

45 |

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.

47 | 48 |

Related

49 |

ByRef parameters

50 |

Examples

51 |
52 |

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 |
76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /docs/lib/KeyHistory.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | KeyHistory - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

KeyHistory

14 | 15 |

Displays script info and a history of the most recent keystrokes and mouse clicks.

16 | 17 |
KeyHistory MaxEvents
18 |

Parameters

19 |
20 | 21 |
MaxEvents
22 |
23 |

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 |
26 | 27 |
28 | 29 |

Remarks

30 |

If KeyHistory is not used, the default setting is 40.

31 |

To disable key history, use the following:

32 |
KeyHistory 0
33 |

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 | InstallMouseHook
38 |

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.

39 | 40 |

Related

41 |

InstallKeybdHook, InstallMouseHook, ListHotkeys, ListLines, ListVars, GetKeyState, KeyWait, A_PriorKey

42 | 43 |

Examples

44 | 45 |
46 |

Displays the history info in a window.

47 |
KeyHistory
48 |
49 | 50 |
51 |

Causes KeyHistory to display the last 100 instead 40 keyboard and mouse events.

52 |
KeyHistory 100
53 |
54 | 55 |
56 |

Disables key history entirely.

57 |
KeyHistory 0
58 |
59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /docs/lib/KeyWait.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | KeyWait - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

KeyWait

14 | 15 |

Waits for a key or mouse/controller button to be released or pressed down.

16 | 17 |
KeyWait KeyName , Options
18 |

Parameters

19 |
20 | 21 |
KeyName
22 |
23 |

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.

26 | 27 |
Options
28 |
29 |

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.

35 |

The timeout value can be a floating point number such as 2.5, but it should not be a hexadecimal value such as 0x03.

36 | 37 |
38 | 39 |

Return Value

40 |

Type: Integer (boolean)

41 |

This function returns 0 (false) if the function timed out or 1 (true) otherwise.

42 | 43 |

Remarks

44 |

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 |

Related

51 |

GetKeyState, Key List, InputHook, KeyHistory, InstallKeybdHook, InstallMouseHook, ClipWait, WinWait

52 |

Examples

53 |
54 |

Waits for the A key to be released.

55 |
KeyWait "a"
56 |
57 | 58 |
59 |

Waits for the left mouse button to be pressed down.

60 |
KeyWait "LButton", "D"
61 |
62 | 63 |
64 |

Waits up to 3 seconds for the first controller button to be pressed down.

65 |
KeyWait "Joy1", "D T3"
66 |
67 | 68 |
69 |

Waits for the left Alt key to be logically released.

70 |
KeyWait "LAlt", "L"
71 |
72 | 73 |
74 |

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::.

75 |
~CapsLock::
 76 | {
 77 |     KeyWait "CapsLock"  ; Wait for user to physically release it.
 78 |     MsgBox "You pressed and released the CapsLock key."
 79 | }
80 |
81 | 82 |
83 |

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 |
91 | 92 |
93 |

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 != ThisHotkey 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 |
105 | 106 | 107 | 108 | -------------------------------------------------------------------------------- /docs/lib/ListHotkeys.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ListHotkeys - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ListHotkeys

14 | 15 |

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 |
    24 |
  • reg: The hotkey is implemented via the operating system's RegisterHotkey() function.
  • 25 |
  • reg(no): Same as above except that this hotkey is inactive (due to being unsupported, disabled, or suspended).
  • 26 |
  • k-hook: The hotkey is implemented via the keyboard hook.
  • 27 |
  • m-hook: The hotkey is implemented via the mouse hook.
  • 28 |
  • 2-hooks: The hotkey requires both the hooks mentioned above.
  • 29 |
  • joypoll: The hotkey is implemented by polling the controller at regular intervals.
  • 30 |
31 | 32 |

Related

33 |

InstallKeybdHook, InstallMouseHook, #UseHook, KeyHistory, ListLines, ListVars, #MaxThreadsPerHotkey, A_MaxHotkeysPerInterval

34 | 35 |

Examples

36 |
37 |

Displays information about the hotkeys used by the current script.

38 |
ListHotkeys
39 |
40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /docs/lib/ListLines.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ListLines - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ListLines

14 | 15 |

Enables or disables line logging or displays the script lines most recently executed.

16 | 17 |
ListLines Mode
18 |

Parameters

19 |
20 | 21 |
Mode
22 |
23 |

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.

27 | 28 |
29 | 30 |

Return Value

31 |

Type: Integer (boolean)

32 |

This function returns the previous setting; either 0 (false) or 1 (true).

33 | 34 |

Remarks

35 |

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.

37 |

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.

38 |

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 |

Related

44 |

KeyHistory, ListHotkeys, ListVars

45 |

Examples

46 |
47 |

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 | MsgBox
54 |
55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /docs/lib/ListVars.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ListVars - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ListVars

14 | 15 |

Displays the script's variables: their names and current contents.

16 | 17 |
ListVars
18 |

Remarks

19 |

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.

21 |

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 |
    32 |
  • Local variables, including variables of outer functions which are referenced by the current function.
  • 33 |
  • Static variables for the current function. Global variables declared inside the function are also listed in this section.
  • 34 |
  • If the current function is nested inside another function, static variables of each outer function are also listed.
  • 35 |
  • All global variables.
  • 36 |
37 | 38 |

Related

39 |

KeyHistory, ListHotkeys, ListLines

40 |

The DebugVars script can be used to inspect and change the contents of variables and objects.

41 | 42 |

Examples

43 |
44 |

Displays information about the script's variables.

45 |
var1 := "foo"
46 | var2 := "bar"
47 | obj := []
48 | ListVars
49 | Pause
50 |
51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /docs/lib/ListView.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ListView (GUI) - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ListView

14 | 15 |

Table of Contents

16 |
    17 |
  • Introduction and Simple Example
  • 18 |
  • Options and Styles for the Options Parameter
  • 19 |
  • View Modes: Report (default), Icon, Tile, IconSmall, and List.
  • 20 |
  • Built-in Methods for ListViews
  • 21 |
  • Events
  • 22 |
  • ImageLists (the means by which icons are added to a ListView)
  • 23 |
  • Remarks
  • 24 |
  • Examples
  • 25 |
26 |

Introduction and Simple Example

27 |

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 | ListView 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 |

Options and Styles for the Options Parameter

60 |

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").

61 |

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.

62 |

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.

64 |

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").

66 |

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.

67 |

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.

68 |

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.

69 |

Multi: Specify -Multi (minus Multi) to prevent the user from selecting more than one row at a time.

70 |

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.

73 |

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.

74 |

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.

77 |

(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 |

View Modes

79 |

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").

80 |

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").

85 |

Built-in Methods for ListViews

86 |

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 |
    90 |
  • Add: Adds a new row to the bottom of the list.
  • 91 |
  • Insert: Inserts a new row at the specified row number.
  • 92 |
  • Modify: Modifies the attributes and/or text of a row.
  • 93 |
  • Delete: Deletes the specified row or all rows.
  • 94 |
95 |

Column methods:

96 |
    97 |
  • ModifyCol: Modifies the attributes and/or text of the specified column and its header.
  • 98 |
  • InsertCol: Inserts a new column at the specified column number.
  • 99 |
  • DeleteCol: Deletes the specified column and all of the contents beneath it.
  • 100 |
101 |

Retrieval methods:

102 |
    103 |
  • GetCount: Returns the number of rows or columns in the control.
  • 104 |
  • GetNext: Returns the row number of the next selected, checked, or focused row.
  • 105 |
  • GetText: Retrieves the text at the specified row and column number.
  • 106 |
107 |

Other methods:

108 |
    109 |
  • SetImageList: Sets or replaces an ImageList for displaying icons.
  • 110 |
111 | 112 |
113 |

Add

114 |

Adds a new row to the bottom of the list.

115 |
RowNumber := LV.Add(Options, Col1, Col2, ...)
116 |

Parameters

117 |
118 |
Options
119 |
120 |

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").

123 |

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").

125 |

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.

127 |

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.

128 |

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").

129 |
130 |
Col1, Col2, ...
131 |
132 |

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.

134 |
135 |
136 |

Return Value

137 |

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 |
140 | 141 |
142 |

Insert

143 |

Inserts a new row at the specified row number.

144 |
RowNumber := LV.Insert(RowNumber , Options, Col1, Col2, ...)
145 |

Parameters

146 |
147 |
RowNumber
148 |
149 |

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 |
152 |
Options
153 |
154 |

Type: String

155 |

If blank or omitted, it defaults to no options. Otherwise, specify one or more options from the list above.

156 |
157 |
Col1, Col2, ...
158 |
159 |

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.

161 |
162 |
163 |

Return Value

164 |

Type: Integer

165 |

This method returns the specified row number.

166 |
167 | 168 |
169 |

Modify

170 |

Modifies the attributes and/or text of a row.

171 |
LV.Modify(RowNumber , Options, NewCol1, NewCol2, ...)
172 |

Parameters

173 |
174 |
RowNumber
175 |
176 |

Type: Integer

177 |

The number of the row to modify. If 0, all rows in the control are modified.

178 |
179 |
Options
180 |
181 |

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 |
184 |
NewCol1, NewCol2, ...
185 |
186 |

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.

188 |
189 |
190 |

Remarks

191 |

When only the first two parameters are present, only the row's attributes and not its text are changed.

192 |
193 | 194 |
195 |

Delete

196 |

Deletes the specified row or all rows.

197 |
LV.Delete(RowNumber)
198 |

Parameters

199 |
200 |
RowNumber
201 |
202 |

Type: Integer

203 |

If omitted, all rows in the ListView are deleted. Otherwise, specify the number of the row to delete.

204 |
205 |
206 |
207 | 208 |
209 |

ModifyCol

210 |

Modifies the attributes and/or text of the specified column and its header.

211 |
LV.ModifyCol(ColumnNumber, Options, ColumnTitle)
212 |

Parameters

213 |
214 |
ColumnNumber
215 |
216 |

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 |
220 |
Options
221 |
222 |

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 |
225 |

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").

227 |

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.

230 |

IconRight: Puts the icon on the right side of the column rather than the left.

231 |
232 |

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).

235 |

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 |
237 |

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".

241 |
242 |

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 |
252 |
ColumnTitle
253 |
254 |

Type: String

255 |

If omitted, the current header is left unchanged. Otherwise, specify the new header of the column.

256 |
257 |
258 |
259 | 260 |
261 |

InsertCol

262 |

Inserts a new column at the specified column number.

263 |
ColumnNumber := LV.InsertCol(ColumnNumber, Options, ColumnTitle)
264 |

Parameters

265 |
266 |
ColumnNumber
267 |
268 |

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 |
272 |
Options
273 |
274 |

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 |
277 |
ColumnTitle
278 |
279 |

Type: String

280 |

If blank or omitted, it defaults to an empty header. Otherwise, specify the header of the column.

281 |
282 |
283 |

Return Value

284 |

Type: Integer

285 |

This method returns the new column's position number.

286 |

Remarks

287 |

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 |
290 | 291 |
292 |

DeleteCol

293 |

Deletes the specified column and all of the contents beneath it.

294 |
LV.DeleteCol(ColumnNumber)
295 |

Parameters

296 |
297 |
ColumnNumber
298 |
299 |

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.

301 |
302 |
303 |
304 | 305 |
306 |

GetCount

307 |

Returns the number of rows or columns in the control.

308 |
Count := LV.GetCount(Mode)
309 |

Parameters

310 |
311 |
Mode
312 |
313 |

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 |
318 |
319 |

Return Value

320 |

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 |

Remarks

323 |

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 |
337 | 338 |
339 |

GetNext

340 |

Returns the row number of the next selected, checked, or focused row.

341 |
RowNumber := LV.GetNext(StartingRowNumber, RowType)
342 |

Parameters

343 |
344 |
StartingRowNumber
345 |
346 |

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 |
349 |
RowType
350 |
351 |

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 |
356 |
357 |

Return Value

358 |

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 |

Remarks

361 |

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 |
376 |
377 |

GetText

378 |

Retrieves the text at the specified row and column number.

379 |
Text := LV.GetText(RowNumber , ColumnNumber)
380 |
381 |
RowNumber
382 |
383 |

Type: Integer

384 |

The number of the row whose text to be retrieved. If 0, the column header text is retrieved.

385 |
386 |
ColumnNumber
387 |
388 |

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 |
391 |
392 |

Return Value

393 |

Type: String

394 |

The method returns the retrieved text. Only up to 8191 characters are retrieved.

395 |

Remarks

396 |

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 |
399 |
400 |

SetImageList

401 |

Sets or replaces an ImageList for displaying icons.

402 |
PrevImageListID := LV.SetImageList(ImageListID , IconType)
403 |

Parameters

404 |
405 |
ImageListID
406 |
407 |

Type: Integer

408 |

The ID number returned from a previous call to IL_Create.

409 |
410 |
IconType
411 |
412 |

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 |
415 |
416 |

Return Value

417 |

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 |

Remarks

420 |

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 |
424 | 425 |

Events

426 |

The following events can be detected by calling OnEvent to register a callback function or method:

427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 |
EventRaised when...
ClickThe control is clicked.
DoubleClickThe control is double-clicked.
ColClickA column header is clicked.
ContextMenuThe user right-clicks the control or presses Menu or Shift+F10 while the control has the keyboard focus.
FocusThe control gains the keyboard focus.
LoseFocusThe control loses the keyboard focus.
ItemCheckAn item is checked or unchecked.
ItemEditAn item's label is edited by the user.
ItemFocusThe focused item changes.
ItemSelectAn item is selected or deselected.
440 |

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 |

ImageLists

443 |

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 |

IL_Create

455 |

Creates a new ImageList that is initially empty.

456 |
ImageListID := IL_Create(InitialCount, GrowCount, LargeIcons)
457 |

Parameters

458 |
459 |
InitialCount
460 |
461 |

Type: Integer

462 |

If omitted, it defaults to 2. Otherwise, specify the number of icons you expect to put into the list immediately.

463 |
464 |
GrowCount
465 |
466 |

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 |
469 |
LargeIcons
470 |
471 |

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 |
477 |
478 |

Return Value

479 |

Type: Integer

480 |

On success, this function returns the unique ID of the newly created ImageList. On failure, it returns 0.

481 | 482 |

IL_Add

483 |

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 |

Parameters

487 |
488 |
ImageListID
489 |
490 |

Type: Integer

491 |

The ID number returned from a previous call to IL_Create.

492 |
493 |
IconFileName
494 |
495 |

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.

497 |
498 |
IconNumber
499 |
500 |

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).

502 |
503 |
PicFileName
504 |
505 |

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.

507 |
508 |
MaskColor
509 |
510 |

Type: Integer

511 |

The mask/transparency color number. 0xFFFFFF (the color white) might be best for most pictures.

512 |
513 |
Resize
514 |
515 |

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 |
519 |
520 |

Return Value

521 |

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 |

IL_Destroy

525 |

Deletes the specified ImageList.

526 |
IsDestroyed := IL_Destroy(ImageListID)
527 |

Parameters

528 |
529 |
ImageListID
530 |
531 |

Type: Integer

532 |

The ID number returned from a previous call to IL_Create.

533 |
534 |
535 |

Return Value

536 |

Type: Integer (boolean)

537 |

On success, this function returns 1 (true). On failure, it returns 0 (false).

538 |

Remarks

539 |

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 |

Remarks

542 |

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.

544 |

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 |

Related

562 |

TreeView, Other Control Types, Gui(), ContextMenu event, Gui object, GuiControl object, ListView styles table

563 |

Examples

564 | 565 |
566 |

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 |
571 | 572 |
573 |

Auto-sizes all columns to fit their contents.

574 |
LV.ModifyCol()  ; There are no parameters in this mode.
575 |
576 | 577 |
578 |

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 |
766 | 767 | 768 | -------------------------------------------------------------------------------- /docs/lib/ListViewGetContent.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ListViewGetContent - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ListViewGetContent

15 | 16 |

Returns a list of items/rows from a ListView.

17 | 18 |
List := ListViewGetContent(Options, Control, WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
Options
23 |
24 |

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 |
34 |
Control
35 |
36 |

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. This parameter is required; that is, it cannot be omitted.

38 |
39 |
WinTitle, WinText, ExcludeTitle, ExcludeText
40 |
41 |

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 |
46 |
47 | 48 |

Return Value

49 |

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 |

Error Handling

53 |

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 |

Remarks

58 |

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 |

Related

64 |

ControlGetItems, WinGetList, Control functions

65 | 66 |

Examples

67 |
68 |

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 |
77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /docs/lib/LoadPicture.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | LoadPicture - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

LoadPicture

14 | 15 |

Loads a picture from file and returns a bitmap or icon handle.

16 |
Handle := LoadPicture(Filename , Options, &OutImageType)
17 | 18 |

Parameters

19 |
20 | 21 |
Filename
22 |
23 |

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 |
26 | 27 |
Options
28 |
29 |

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).

32 |

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.

33 |

GDI+: Use GDI+ to load the image, if available. For example, "GDI+ w100".

34 |
35 | 36 |
&OutImageType
37 |
38 |

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 |
41 | 42 |
43 | 44 |

Return Value

45 |

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 |

Remarks

49 |

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 |

Related

59 |

Image Handles

60 | 61 |

Examples

62 |
63 |

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 |
90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /docs/lib/Loop.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Loop - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Loop (normal)

14 | 15 |

Performs one or more statements repeatedly: either the specified number of times or until Break is encountered.

16 | 17 |
Loop Count
18 |

Parameters

19 |
20 | 21 |
Count
22 |
23 |

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)

27 |
28 | 29 |
30 | 31 |

Remarks

32 |

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.

37 |

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 |

Related

48 |

Until, While-loop, For-loop, Files-and-folders loop, Registry loop, File-reading loop, Parsing loop, Break, Continue, Blocks, Else

49 | 50 |

Examples

51 |
52 |

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 |
59 | 60 |
61 |

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 |
71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /docs/lib/LoopFiles.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Loop Files - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Loop Files

15 |

Retrieves the specified files or folders, one at a time.

16 | 17 |
Loop Files FilePattern , Mode
18 | 19 |

Parameters

20 |
21 | 22 |
FilePattern
23 |
24 |

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.

26 |

Both asterisks (*) and question marks (?) are supported as wildcards. * matches zero or more characters and ? matches any single character. Usage examples:

27 |
    28 |
  • *.* or * matches all files.
  • 29 |
  • *.htm matches files with the extension .htm, .html, etc.
  • 30 |
  • *. matches files without an extension.
  • 31 |
  • log?.txt matches e.g. log1.txt but not log10.txt.
  • 32 |
  • *report* matches any filename containing the word "report".
  • 33 |
34 |

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.

37 |
38 | 39 |
Mode
40 |
41 |

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 |
    44 |
  • D = Include directories (folders).
  • 45 |
  • F = Include files. If both F and D are omitted, files are included but not folders.
  • 46 |
  • R = Recurse into subdirectories (subfolders). All subfolders will be recursed into, not just those whose names match FilePattern. If R is omitted, files and folders in subfolders are not included.
  • 47 |
48 |
49 | 50 |
51 | 52 |

Special Variables Available Inside a File Loop

53 |

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 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 |
VariableDescription
A_LoopFileNameThe name of the file or folder currently retrieved (without the path).
A_LoopFileExtThe file's extension (e.g. TXT, DOC, or EXE). The period (.) is not included.
A_LoopFilePathThe 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).
A_LoopFileFullPathThis 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.
A_LoopFileShortPath

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_LoopFileShortPath
81 |

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.

A_LoopFileShortNameThe 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.
A_LoopFileDirThe 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:
A_LoopFileTimeModifiedThe time the file was last modified. Format YYYYMMDDHH24MISS.
A_LoopFileTimeCreatedThe time the file was created. Format YYYYMMDDHH24MISS.
A_LoopFileTimeAccessedThe time the file was last accessed. Format YYYYMMDDHH24MISS.
A_LoopFileAttribThe attributes of the file currently retrieved.
A_LoopFileSizeThe size in bytes of the file currently retrieved. Files larger than 4 gigabytes are also supported.
A_LoopFileSizeKBThe size in Kbytes of the file currently retrieved, rounded down to the nearest integer.
A_LoopFileSizeMBThe size in Mbytes of the file currently retrieved, rounded down to the nearest integer.
120 | 121 |

Remarks

122 |

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.

127 |

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_LoopField
133 |

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 |
    136 |
  • The system has long path support enabled (requires Windows 10 version 1607 or later).
  • 137 |
  • The \\?\ long path prefix is used (caveats apply).
  • 138 |
139 |

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" {.

141 |

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 |

Related

146 |

Loop, Break, Continue, Blocks, SplitPath, FileSetAttrib, FileSetTime

147 | 148 |

Examples

149 |
150 |

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 |
158 | 159 |
160 |

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 |
167 | 168 |
169 |

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 |
183 | 184 |
185 |

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 |
200 | 201 |
202 |

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 |
227 | 228 |
229 |

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 |
237 | 238 | 239 | 240 | -------------------------------------------------------------------------------- /docs/lib/LoopParse.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Loop Parse - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Loop Parse

14 | 15 |

Retrieves substrings (fields) from a string, one at a time.

16 | 17 |
Loop Parse String , DelimiterChars, OmitChars
18 |

Parameters

19 |
20 | 21 |
String
22 |
23 |

Type: String

24 |

The string to analyze.

25 |
26 | 27 |
DelimiterChars
28 |
29 |

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:

32 |
"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.

36 |

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:

37 |
NewHTML := StrReplace(HTMLString, "<br>", "¢")
 38 | Loop Parse, NewHTML, "¢" ; Parse the string based on the cent symbol.
 39 | {
 40 |     ; ...
 41 | }
42 |
43 | 44 |
OmitChars
45 |
46 |

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.

48 |

If DelimiterChars is blank, OmitChars indicates which characters should be excluded from consideration (the loop will not see them).

49 |
50 | 51 |
52 | 53 |

Remarks

54 |

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 |

Related

63 |

StrSplit, file-reading loop, Loop, Break, Continue, Blocks, Sort, FileSetAttrib, FileSetTime

64 | 65 |

Examples

66 |
67 |

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 |
74 | 75 |
76 |

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 |
83 | 84 |
85 |

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 |
92 | 93 |
94 |

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 |
106 | 107 |
108 |

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 |
124 | 125 | 126 | 127 | -------------------------------------------------------------------------------- /docs/lib/LoopRead.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Loop Read - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Loop Read

15 | 16 |

Retrieves the lines in a text file, one at a time.

17 | 18 |
Loop Read InputFile , OutputFile
19 |

Parameters

20 |
21 | 22 |
InputFile
23 |
24 |

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 |
27 | 28 |
OutputFile
29 |
30 |

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.

35 |

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 |
37 | 38 |
39 | 40 |

Remarks

41 |

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 {.

55 |

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 |

Related

60 |

FileEncoding, FileOpen/File Object, FileRead, FileAppend, Sort, Loop, Break, Continue, Blocks, FileSetAttrib, FileSetTime

61 | 62 |

Examples

63 |
64 |

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 |
75 | 76 |
77 |

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 |
81 | 82 |
83 |

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 |
157 | 158 | 159 | 160 | -------------------------------------------------------------------------------- /docs/lib/LoopReg.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Loop Reg - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Loop Reg

14 | 15 |

Retrieves the contents of the specified registry subkey, one item at a time.

16 | 17 |
Loop Reg KeyName , Mode
18 |

Parameters

19 |
20 | 21 |
KeyName
22 |
23 |

Type: String

24 |

The full name of the registry key, e.g. "HKLM\Software\SomeApplication".

25 |

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".

27 |
28 | 29 |
Mode
30 |
31 |

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 |
    34 |
  • K = Include keys.
  • 35 |
  • V = Include values. Values are also included if both K and V are omitted.
  • 36 |
  • R = Recurse into subkeys. If R is omitted, keys and values within subkeys of KeyName are not included.
  • 37 |
38 |
39 | 40 | 41 |
42 | 43 |

Remarks

44 |

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 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 |
VariableDescription
A_LoopRegNameName 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.
A_LoopRegTypeThe 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.
A_LoopRegKeyThe full name of the key which contains the current loop item. For remote registry access, this value will not include the computer name.
A_LoopRegTimeModifiedThe 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).
68 |

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 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 |
SyntaxDescription
Value := RegRead()Reads the current item. If the current item is a key, an exception is thrown.
RegWrite Value
RegWrite
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.
RegDeleteDeletes the current item if it is a value. If the current item is a key, its default value will be deleted instead.
RegDeleteKeyDeletes 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.
RegCreateKeyTargets 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.
95 |

When accessing a remote registry (via the KeyName parameter described above), the following notes apply:

96 |
    97 |
  • The target machine must be running the Remote Registry service.
  • 98 |
  • Access to a remote registry may fail if the target computer is not in the same domain as yours or the local or remote username lacks sufficient permissions (however, see below for possible workarounds).
  • 99 |
  • Depending on your username's domain, workgroup, and/or permissions, you may have to connect to a shared device, such as by mapping a drive, prior to attempting remote registry access. Making such a connection -- using a remote username and password that has permission to access or edit the registry -- may as a side-effect enable remote registry access.
  • 100 |
  • If you're already connected to the target computer as a different user (for example, a mapped drive via user Guest), you may have to terminate that connection to allow the remote registry feature to reconnect and re-authenticate you as your own currently logged-on username.
  • 101 |
102 |

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" {.

103 |

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 |

Related

107 |

Loop, Break, Continue, Blocks, RegRead, RegWrite, RegDelete, RegDeleteKey, SetRegView

108 | 109 |

Examples

110 |
111 |

Retrieves the contents of the specified registry subkey, one item at a time.

112 |
Loop Reg, "HKEY_LOCAL_MACHINE\Software\SomeApplication"
113 |     MsgBox A_LoopRegName
114 |
115 | 116 |
117 |

Deletes Internet Explorer's history of URLs typed by the user.

118 |
Loop Reg, "HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\TypedURLs"
119 |     RegDelete
120 |
121 | 122 |
123 |

A working test script.

124 |
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 |
139 | 140 |
141 |

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 |
193 | 194 | 195 | 196 | -------------------------------------------------------------------------------- /docs/lib/Map.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Map Object - Methods & Properties | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Map Object

15 |
class Map extends Object
16 | 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 |

Table of Contents

31 |
    32 |
  • Static Methods: 33 |
      34 |
    • Call: Creates a Map and sets items.
    • 35 |
    36 |
  • 37 |
  • Methods: 38 |
      39 |
    • Clear: Removes all key-value pairs from a map.
    • 40 |
    • Clone: Returns a shallow copy of a map.
    • 41 |
    • Delete: Removes a key-value pair from a map.
    • 42 |
    • Get: Returns the value associated with a key, or a default value.
    • 43 |
    • Has: Returns true if the specified key has an associated value within a map.
    • 44 |
    • Set: Sets zero or more items.
    • 45 |
    • __Enum: Enumerates key-value pairs.
    • 46 |
    • __New: Sets items. Equivalent to Set.
    • 47 |
    48 |
  • 49 |
  • Properties: 50 |
      51 |
    • Count: Retrieves the number of key-value pairs present in a map.
    • 52 |
    • Capacity: Retrieves or sets the current capacity of a map.
    • 53 |
    • CaseSense: Retrieves or sets a map's case sensitivity setting.
    • 54 |
    • Default: Defines the default value returned when a key is not found.
    • 55 |
    • __Item: Retrieves or sets the value of a key-value pair.
    • 56 |
    57 |
  • 58 |
59 | 60 |

Static Methods

61 | 62 |

Call

63 |

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.

67 |

Parameters are defined by __New.

68 |
69 | 70 |

Methods

71 | 72 |

Clear

73 |

Removes all key-value pairs from a map.

74 |
MapObj.Clear()
75 |
76 | 77 |

Clone

78 |

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 |
83 | 84 |

Delete

85 |

Removes a key-value pair from a map.

86 |
RemovedValue := MapObj.Delete(Key)
87 |

Parameters

88 |
89 |
Key
90 |
91 |

Type: Integer, Object or String

92 |

Any single key. If the map does not contain this key, an UnsetItemError is thrown.

93 |
94 |
95 |

Return Value

96 |

Type: Any

97 |

This method returns the removed value.

98 |
99 | 100 |

Get

101 |

Returns the value associated with a key, or a default value.

102 |
Value := MapObj.Get(Key , Default)
103 |

This method does the following:

104 |
    105 |
  • Return the value associated with Key, if found.
  • 106 |
  • Return the value of the Default parameter, if specified.
  • 107 |
  • Return the value of MapObj.Default, if defined.
  • 108 |
  • Throw an UnsetItemError.
  • 109 |
110 |

When Default is omitted, this is equivalent to MapObj[Key], except that __Item is not called.

111 |
112 | 113 |

Has

114 |

Returns true if the specified key has an associated value within a map, otherwise false.

115 |
MapObj.Has(Key)
116 |
117 | 118 |

Set

119 |

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.

122 |

Return Value

123 |

Type: Object

124 |

This method returns the Map.

125 |
126 | 127 |

__Enum

128 |

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 |
132 |
Key
133 |
134 |

Type: Integer, Object or String

135 |

The key.

136 |
137 |
Value
138 |
139 |

Type: Any

140 |

The value.

141 |
142 |
143 |
144 | 145 |

__New

146 |

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 |
150 | 151 |

Properties

152 | 153 |

Count

154 |

Retrieves the number of key-value pairs present in a map.

155 |
Count := MapObj.Count
156 |
157 | 158 |

Capacity

159 |

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 |
164 | 165 |

CaseSense

166 |

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 |
176 | 177 |

Default

178 |

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 |
182 | 183 |

__Item

184 |

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 |
193 | 194 | 195 | 196 | -------------------------------------------------------------------------------- /docs/lib/Math.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Math Functions - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Math Functions

14 |

Functions for performing various mathematical operations such as rounding, exponentiation, squaring, etc.

15 | 16 |

Table of Contents

17 |
    18 |
  • General Math: 19 |
      20 |
    • Abs: Returns the absolute value of a number.
    • 21 |
    • Ceil: Returns a number rounded up to the nearest integer.
    • 22 |
    • Exp: Returns the result of raising e to the Nth power.
    • 23 |
    • Floor: Returns a number rounded down to the nearest integer.
    • 24 |
    • Log: Returns the logarithm (base 10) of a number.
    • 25 |
    • Ln: Returns the natural logarithm (base e) of a number.
    • 26 |
    • Max: Returns the highest number from a set of numbers.
    • 27 |
    • Min: Returns the lowest number from a set of numbers.
    • 28 |
    • Mod: Modulo. Returns the remainder of a division.
    • 29 |
    • Round: Returns a number rounded to N decimal places.
    • 30 |
    • Sqrt: Returns the square root of a number.
    • 31 |
    32 |
  • 33 |
  • Trigonometry: 34 |
      35 |
    • Sin: Returns the trigonometric sine of a number.
    • 36 |
    • Cos: Returns the trigonometric cosine of a number.
    • 37 |
    • Tan: Returns the trigonometric tangent of a number.
    • 38 |
    • ASin: Returns the arcsine of a number in radians.
    • 39 |
    • ACos: Returns the arccosine of a number in radians.
    • 40 |
    • ATan: Returns the arctangent of a number in radians.
    • 41 |
    42 |
  • 43 |
  • Error-handling
  • 44 |
45 | 46 |

General Math

47 | 48 |

Abs

49 |

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.2
53 | 54 |

Ceil

55 |

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 -1
59 | 60 |

Exp

61 |

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.320117
65 | 66 |

Floor

67 |

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 -2
71 | 72 |

Log

73 |

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.079181
77 | 78 |

Ln

79 |

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.182322
83 | 84 |

Max

85 |

Returns the highest number from a set of numbers.

86 |
Number := Max(Number1 , Number2, ...)
87 |
MsgBox Max(2.11, -2, 0) ; Returns 2.11
88 |

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 |

Min

94 |

Returns the lowest number from a set of numbers.

95 |
Number := Min(Number1 , Number2, ...)
96 |
MsgBox Min(2.11, -2, 0) ; Returns -2
97 |

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 1
100 | 101 |

Mod

102 |

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 |

Round

108 |

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 3
112 |

If N is positive, Number is rounded to N decimal places:

113 |
MsgBox Round(3.14, 1) ; Returns 3.1
114 |

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 300
117 |

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.

118 | 119 |

Sqrt

120 |

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 4
124 | 125 |

Trigonometry

126 |

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 |

Sin

129 |

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.932039
133 | 134 |

Cos

135 |

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.362358
139 | 140 |

Tan

141 |

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.572152
145 | 146 |

ASin

147 |

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.201358
151 | 152 |

ACos

153 |

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.369438
157 | 158 |

ATan

159 |

Returns the arctangent (the number whose tangent is the specified number) in radians.

160 |
Value := ATan(Number)
161 |
MsgBox ATan(1.2) ; Returns 0.876058
162 | 163 |

Error-Handling

164 |

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 | Menu/MenuBar Object - Methods & Properties | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Menu/MenuBar Object

15 |

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 Object
17 |

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 Menu
19 |

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 |

Table of Contents

25 |
    26 |
  • Static Methods: 27 |
      28 |
    • Call: Creates a new Menu or MenuBar object.
    • 29 |
    30 |
  • 31 |
  • Methods: 32 |
      33 |
    • Add: Adds or modifies a menu item.
    • 34 |
    • AddStandard: Adds the standard tray menu items.
    • 35 |
    • Check: Adds a visible checkmark next to a menu item.
    • 36 |
    • Delete: Deletes one or all menu items.
    • 37 |
    • Disable: Grays out a menu item to indicate that the user cannot select it.
    • 38 |
    • Enable: Allows the user to once again select a menu item if it was previously disabled (grayed out).
    • 39 |
    • Insert: Inserts a new item before the specified item.
    • 40 |
    • Rename: Renames a menu item.
    • 41 |
    • SetColor: Changes the background color of the menu.
    • 42 |
    • SetIcon: Sets the icon to be displayed next to a menu item.
    • 43 |
    • Show: Displays the menu.
    • 44 |
    • ToggleCheck: Toggles the checkmark next to a menu item.
    • 45 |
    • ToggleEnable: Enables or disables a menu item.
    • 46 |
    • Uncheck: Removes the checkmark (if there is one) from a menu item.
    • 47 |
    48 |
  • 49 |
  • Properties: 50 |
      51 |
    • ClickCount: Retrieves or sets how many times the tray icon must be clicked to select its default menu item.
    • 52 |
    • Default: Retrieves or sets the default menu item.
    • 53 |
    • Handle: Retrieves the menu's Win32 handle.
    • 54 |
    55 |
  • 56 |
  • General: 57 |
      58 |
    • MenuItemName
    • 59 |
    • Win32 Menus
    • 60 |
    • Remarks
    • 61 |
    • Related
    • 62 |
    • Examples
    • 63 |
    64 |
  • 65 |
66 | 67 |

Static Methods

68 |
69 |

Call

70 |

Creates a new Menu or MenuBar object.

71 |
 72 | MyMenu := Menu()
 73 | MyMenuBar := MenuBar()
 74 | MyMenu := Menu.Call()
 75 | MyMenuBar := MenuBar.Call()
 76 | 
77 |
78 | 79 |

Methods

80 |
81 |

Add

82 |

Adds or modifies a menu item.

83 |
MyMenu.Add(MenuItemName, CallbackOrSubmenu, Options)
84 |

Parameters

85 |
86 |
MenuItemName
87 |
88 |

Type: String

89 |

The text to display on the menu item, or the position of an existing item to modify. See MenuItemName.

90 |
91 |
CallbackOrSubmenu
92 |
93 |

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 |
    100 |
  1. The name of the menu item.
  2. 101 |
  3. The position number of the menu item.
  4. 102 |
  5. The Menu object of the menu to which the menu item was added.
  6. 103 |
104 |

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, *).

105 |
106 |
Options
107 |
108 |

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.

111 |

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 |
117 |
118 |

Remarks

119 |

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 |
123 | 124 |
125 |

AddStandard

126 |

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 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 |
&Open10
&Help2
3
&Window Spy4
&Reload Script5
&Edit Script6
7
&Suspend Hotkeys81
&Pause Script92
E&xit103
163 |

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.

164 |

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.

166 |
167 | 168 |
169 |

Check

170 |

Adds a visible checkmark in the menu next to a menu item (if there isn't one already).

171 |
MyMenu.Check(MenuItemName)
172 |

Parameters

173 |
174 |
MenuItemName
175 |
176 |

Type: String

177 |

The name or position of a menu item. See MenuItemName.

178 |
179 |
180 |
181 | 182 |
183 |

Delete

184 |

Deletes one or all menu items.

185 |
MyMenu.Delete(MenuItemName)
186 |

Parameters

187 |
188 |
MenuItemName
189 |
190 |

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 |
193 |
194 |

Remarks

195 |

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.

197 |

If the default menu item is deleted, the effect will be similar to having set MyMenu.Default := "".

198 |
199 | 200 |
201 |

Disable

202 |

Grays out a menu item to indicate that the user cannot select it.

203 |
MyMenu.Disable(MenuItemName)
204 |

Parameters

205 |
206 |
MenuItemName
207 |
208 |

Type: String

209 |

The name or position of a menu item. See MenuItemName.

210 |
211 |
212 |
213 | 214 |
215 |

Enable

216 |

Allows the user to once again select a menu item if it was previously disabled (grayed out).

217 |
MyMenu.Enable(MenuItemName)
218 |

Parameters

219 |
220 |
MenuItemName
221 |
222 |

Type: String

223 |

The name or position of a menu item. See MenuItemName.

224 |
225 |
226 |
227 | 228 |
229 |

Insert

230 |

Inserts a new item before the specified item.

231 |
MyMenu.Insert(MenuItemName, ItemToInsert, CallbackOrSubmenu, Options)
232 |

Parameters

233 |
234 |
MenuItemName
235 |
236 |

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 |
239 |
ItemToInsert
240 |
241 |

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 |
244 |
CallbackOrSubmenu
245 |
246 |

See the Add method's CallbackOrSubmenu parameter.

247 |
248 |
Options
249 |
250 |

See the Add method's Options parameter.

251 |
252 |
253 |

Remarks

254 |

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 |
256 | 257 |
258 |

Rename

259 |

Renames a menu item.

260 |
MyMenu.Rename(MenuItemName , NewName)
261 |

Parameters

262 |
263 |
MenuItemName
264 |
265 |

Type: String

266 |

The name or position of a menu item. See MenuItemName.

267 |
268 |
NewName
269 |
270 |

Type: String

271 |

If blank or omitted, MenuItemName will be converted into a separator line. Otherwise, specify the new name.

272 |
273 |
274 |

Remarks

275 |

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.

277 |
278 | 279 |
280 |

SetColor

281 |

Changes the background color of the menu.

282 |
MyMenu.SetColor(ColorValue, ApplyToSubmenus)
283 |

Parameters

284 | 285 |
286 |
ColorValue
287 |
288 |

Type: String or Integer

289 |

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".

290 |
291 |
ApplyToSubmenus
292 |
293 |

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 |
298 |
299 |
300 | 301 |
302 |

SetIcon

303 |

Sets the icon to be displayed next to a menu item.

304 |
MyMenu.SetIcon(MenuItemName, FileName , IconNumber, IconWidth)
305 |

Parameters

306 |
307 |
MenuItemName
308 |
309 |

Type: String

310 |

The name or position of a menu item. See MenuItemName.

311 |
312 |
FileName
313 |
314 |

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.

316 |

Specify an empty string or "*" to remove the item's current icon.

317 |
318 |
IconNumber
319 |
320 |

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.

322 |
323 |
IconWidth
324 |
325 |

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 |
328 |
329 |

Remarks

330 |

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).

332 |
333 | 334 |
335 |

Show

336 |

Displays the menu.

337 |
MyMenu.Show(X, Y)
338 |

Parameters

339 |
340 |
X, Y
341 |
342 |

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 |
345 |
346 |

Remarks

347 |

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 |
350 | 351 |
352 |

ToggleCheck

353 |

Adds a checkmark if there wasn't one; otherwise, removes it.

354 |
MyMenu.ToggleCheck(MenuItemName)
355 |

Parameters

356 |
357 |
MenuItemName
358 |
359 |

Type: String

360 |

The name or position of a menu item. See MenuItemName.

361 |
362 |
363 |
364 | 365 |
366 |

ToggleEnable

367 |

Disables a menu item if it was previously enabled; otherwise, enables it.

368 |
MyMenu.ToggleEnable(MenuItemName)
369 |

Parameters

370 |
371 |
MenuItemName
372 |
373 |

Type: String

374 |

The name or position of a menu item. See MenuItemName.

375 |
376 |
377 |
378 | 379 |
380 |

Uncheck

381 |

Removes the checkmark (if there is one) from a menu item.

382 |
MyMenu.Uncheck(MenuItemName)
383 |

Parameters

384 |
385 |
MenuItemName
386 |
387 |

Type: String

388 |

The name or position of a menu item. See MenuItemName.

389 |
390 |
391 |
392 | 393 |

Properties

394 |
395 |

ClickCount

396 |

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 |
402 | 403 |
404 |

Default

405 |

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.

412 |

If the default item is deleted, the menu is left without one.

413 |
414 | 415 |
416 |

Handle

417 |

Returns a handle to a Win32 menu (a handle of type HMENU), constructing it if necessary.

418 |
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 |
421 | 422 |

MenuItemName

423 |

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"

425 |

When referring to an existing menu item, the name is not case-sensitive but any ampersands must be included. For example: "&Open"

426 |

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.

428 | 429 |

Win32 Menus

430 |

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.

433 |

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 |

Remarks

437 |

A menu usually looks like this:

438 | Menu 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).

440 |

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 |

Related

445 |

GUI, Threads, Thread, Critical, #NoTrayIcon, Functions, Return, SetTimer

446 | 447 |

Examples

448 | 449 |
450 |

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 |
459 | 460 |
461 |

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 |
485 | 486 |
487 |

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 |
560 | 561 |
562 |

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 |
581 | 582 |
583 |

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 |
603 | 604 | 605 | 606 | -------------------------------------------------------------------------------- /docs/lib/MenuFromHandle.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | MenuFromHandle - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

MenuFromHandle

15 | 16 |

Retrieves the Menu or MenuBar object corresponding to a Win32 menu handle.

17 | 18 |
Menu := MenuFromHandle(Handle)
19 |

Parameters

20 |
21 |
Handle
22 |

Type: Integer

23 |

A handle to a Win32 menu (of type HMENU).

24 |
25 |
26 | 27 |

Remarks

28 |

If the handle is invalid or does not correspond to a menu created by this script, the function returns an empty string.

29 | 30 |

Related

31 |

Win32 Menus, Menu/MenuBar object, Menu.Handle, Menu()

32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /docs/lib/MenuSelect.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | MenuSelect - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

MenuSelect

15 | 16 |

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, ExcludeText
19 |

Parameters

20 |
21 | 22 |
WinTitle, WinText, ExcludeTitle, ExcludeText
23 |
24 |

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 |
29 | 30 |
Menu
31 |
32 |

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. This parameter is required; that is, it cannot be blank or omitted.

34 |

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").

35 |

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.

36 |

Specify "0&" to use the window's system menu.

37 |
38 | 39 |
SubMenu1
40 |
41 |

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 |
44 | 45 |
SubMenu2, SubMenu3, SubMenu4, SubMenu5, SubMenu6
46 |
47 |

Type: String

48 |

If the previous submenu itself contains a menu, this is the name of the menu item inside, or its position.

49 |
50 | 51 |
52 | 53 |

Error Handling

54 |

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 |

Remarks

58 |

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 |

System Menu

63 |

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:

64 |
; 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 |

Related

75 |

ControlSend, PostMessage

76 |

Examples

77 |
78 |

Selects File -> Open in Notepad. This example may fail on Windows 11 or later, as it requires the classic version of Notepad.

79 |
MenuSelect "Untitled - Notepad",, "File", "Open"
80 |
81 | 82 |
83 |

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 |
86 | 87 |
88 |

Selects View -> Lines most recently executed in the main window.

89 |
WinShow "ahk_class AutoHotkey"
90 | MenuSelect "ahk_class AutoHotkey",, "View", "Lines most recently executed"
91 |
92 | 93 | 94 | 95 | -------------------------------------------------------------------------------- /docs/lib/Monitor.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | List of Monitor Functions | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Monitor Functions

15 | 16 |

Functions for retrieving screen resolution and multi-monitor info. Click on a function name for details.

17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 |
FunctionDescription
MonitorGetChecks if the specified monitor exists and optionally retrieves its bounding coordinates.
MonitorGetCountReturns the total number of monitors.
MonitorGetNameReturns the operating system's name of the specified monitor.
MonitorGetPrimaryReturns the number of the primary monitor.
MonitorGetWorkAreaChecks if the specified monitor exists and optionally retrieves the bounding coordinates of its working area.
43 | 44 |

Remarks

45 |

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 |

Related

50 |

DllCall, Win functions, SysGet

51 | 52 |

Examples

53 |
54 |

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 |
73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /docs/lib/MonitorGet.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | MonitorGet - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

MonitorGet

15 | 16 |

Checks if the specified monitor exists and optionally retrieves its bounding coordinates.

17 | 18 |
ActualN := MonitorGet(N, &Left, &Top, &Right, &Bottom)
19 | 20 |

Parameters

21 |
22 |
N
23 |
24 |

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 |
27 | 28 |
&Left, &Top, &Right, &Bottom
29 |
30 |

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 |
33 |
34 | 35 |

Return Value

36 |

Type: Integer

37 |

This function returns the monitor number (the same as N unless N was omitted).

38 | 39 |

Error Handling

40 |

On failure, an exception is thrown and the output variables are not modified.

41 | 42 |

Remarks

43 |

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 |

Related

48 |

MonitorGetWorkArea, SysGet, Monitor functions

49 | 50 |

Examples

51 |
52 |

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 |
61 | 62 |

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 | MonitorGetCount - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

MonitorGetCount

15 | 16 |

Returns the total number of monitors.

17 | 18 |
Count := MonitorGetCount()
19 | 20 |

Parameters

21 |

This function has no parameters.

22 | 23 |

Return Value

24 |

Type: Integer

25 |

This function returns the total number of monitors.

26 | 27 |

Remarks

28 |

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.

29 | 30 |

Related

31 |

SysGet, Monitor functions

32 | 33 |

Examples

34 |

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 | MonitorGetName - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

MonitorGetName

15 | 16 |

Returns the operating system's name of the specified monitor.

17 | 18 |
Name := MonitorGetName(N)
19 | 20 |

Parameters

21 |
22 |
N
23 |
24 |

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 |
27 |
28 | 29 |

Return Value

30 |

Type: String

31 |

This function returns the operating system's name for the specified monitor.

32 | 33 |

Error Handling

34 |

An exception is thrown on failure.

35 | 36 |

Related

37 |

SysGet, Monitor functions

38 | 39 |

Examples

40 |

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 | MonitorGetPrimary - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

MonitorGetPrimary

15 | 16 |

Returns the number of the primary monitor.

17 | 18 |
Primary := MonitorGetPrimary()
19 | 20 |

Parameters

21 |

This function has no parameters.

22 | 23 |

Return Value

24 |

Type: Integer

25 |

This function returns the number of the primary monitor. In a single-monitor system, this will be always 1.

26 | 27 |

Related

28 |

SysGet, Monitor functions

29 | 30 |

Examples

31 |

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 | MonitorGetWorkArea - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

MonitorGetWorkArea

15 | 16 |

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 |

Parameters

21 |
22 |
N
23 |
24 |

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 |
27 | 28 |
&Left, &Top, &Right, &Bottom
29 |
30 |

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 |
33 |
34 | 35 |

Return Value

36 |

Type: Integer

37 |

This function returns the monitor number (the same as N unless N was omitted).

38 | 39 |

Error Handling

40 |

On failure, an exception is thrown and the output variables are not modified.

41 | 42 |

Remarks

43 |

The working area of a monitor excludes the area occupied by the taskbar and other registered desktop toolbars.

44 | 45 |

Related

46 |

MonitorGet, SysGet, Monitor functions

47 | 48 |

Examples

49 |

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 | MouseClick - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

MouseClick

14 | 15 |

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, Relative
18 |

Parameters

19 |
20 | 21 |
WhichButton
22 |
23 |

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".

26 |

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 |
29 | 30 |
X, Y
31 |
32 |

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 |
35 | 36 |
ClickCount
37 |
38 |

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 |
41 | 42 |
Speed
43 |
44 |

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).

47 |
48 | 49 |
DownOrUp
50 |
51 |

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 |
56 | 57 |
Relative
58 |
59 |

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 |
63 | 64 |
65 | 66 |

Remarks

67 |

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 |

Related

86 |

CoordMode, SendMode, SetDefaultMouseSpeed, SetMouseDelay, Click, MouseClickDrag, MouseGetPos, MouseMove, ControlClick, BlockInput

87 |

Examples

88 |
89 |

Double-clicks at the current mouse position.

90 |
MouseClick "left"
 91 | MouseClick "left"
92 |
93 | 94 |
95 |

Same as above.

96 |
MouseClick "left",,, 2
97 |
98 | 99 |
100 |

Moves the mouse cursor to a specific position, then right-clicks once.

101 |
MouseClick "right", 200, 300
102 |
103 | 104 |
105 |

Simulates the turning of the mouse wheel.

106 |
#up::MouseClick "WheelUp",,, 2  ; Turn it by two notches.
107 | #down::MouseClick "WheelDown",,, 2
108 |
109 | 110 | 111 | 112 | -------------------------------------------------------------------------------- /docs/lib/MouseClickDrag.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | MouseClickDrag - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

MouseClickDrag

14 | 15 |

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, Relative
18 |

Parameters

19 |
20 | 21 |
WhichButton
22 |
23 |

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.

25 |

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 |
27 | 28 |
X1, Y1
29 |
30 |

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 |
34 | 35 |
X2, Y2
36 |
37 |

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 |
40 | 41 |
Speed
42 |
43 |

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).

46 |
47 | 48 |
Relative
49 |
50 |

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".

53 |
54 | 55 |
56 | 57 |

Remarks

58 |

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 |

Related

67 |

CoordMode, SendMode, SetDefaultMouseSpeed, SetMouseDelay, Click, MouseClick, MouseGetPos, MouseMove, BlockInput

68 |

Examples

69 |
70 |

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, 400
72 |
73 | 74 |
75 |

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, 450
87 |
88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /docs/lib/MouseGetPos.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | MouseGetPos - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

MouseGetPos

14 | 15 |

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, Flag
18 |

Parameters

19 |
20 | 21 |
&OutputVarX, &OutputVarY
22 |
23 |

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 |
26 | 27 |
&OutputVarWin
28 |
29 |

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 |
33 | 34 |
&OutputVarControl
35 |
36 |

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 |
40 | 41 |
Flag
42 |
43 |

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 |
49 | 50 |
51 | 52 |

Remarks

53 |

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 |

Related

57 |

CoordMode, Win functions, SetDefaultMouseSpeed, Click

58 | 59 |

Examples

60 |
61 |

Reports the position of the mouse cursor.

62 |
MouseGetPos &xpos, &ypos 
63 | MsgBox "The cursor is at X" xpos " Y" ypos
64 |
65 | 66 |
67 |

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 |
82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /docs/lib/MouseMove.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | MouseMove - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

MouseMove

14 | 15 |

Moves the mouse cursor.

16 | 17 |
MouseMove X, Y , Speed, Relative
18 |

Parameters

19 |
20 | 21 |
X, Y
22 |
23 |

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 |
26 | 27 |
Speed
28 |
29 |

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).

32 |
33 | 34 |
Relative
35 |
36 |

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 |
40 | 41 |
42 | 43 |

Remarks

44 |

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 |

Related

52 |

CoordMode, SendMode, SetDefaultMouseSpeed, SetMouseDelay, Click, MouseClick, MouseClickDrag, MouseGetPos, BlockInput

53 |

Examples

54 |
55 |

Moves the mouse cursor to a new position.

56 |
MouseMove 200, 100
57 |
58 | 59 |
60 |

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 |
63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /docs/lib/MsgBox.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | MsgBox - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 18 | 19 | 20 | 21 |

MsgBox

22 | 23 |

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 |

Parameters

28 |
29 | 30 |
Text
31 |
32 |

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.

35 |

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 |
37 | 38 |
Title
39 |
40 |

Type: String

41 |

If omitted, it defaults to the current value of A_ScriptName. Otherwise, specify the title of the message box.

42 |
43 | 44 |
Options
45 |
46 |

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 |
52 | 53 |
54 | 55 |

Values for the Options parameter

56 |

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 |

Group #1: Buttons

59 |

To indicate the buttons displayed in the message box, add one of the following values:

60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 |
FunctionDecHexString
OK00x0OK or O
OK, Cancel10x1OKCancel, O/C or OC
Abort, Retry, Ignore20x2AbortRetryIgnore, A/R/I or ARI
Yes, No, Cancel30x3YesNoCancel, Y/N/C or YNC
Yes, No40x4YesNo, Y/N or YN
Retry, Cancel50x5RetryCancel, R/C or RC
Cancel, Try Again, Continue60x6CancelTryAgainContinue, C/T/C or CTC
110 | 111 |

Group #2: Icon

112 |

To display an icon in the message box, add one of the following values:

113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 |
FunctionDecHexString
Icon Hand (stop/error)160x10Iconx
Icon Question320x20Icon?
Icon Exclamation480x30Icon!
Icon Asterisk (info)640x40Iconi
145 | 146 |

Group #3: Default Button

147 |

To indicate the default button, add one of the following values:

148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 |
FunctionDecHexString
Makes the 2nd button the default2560x100Default2
Makes the 3rd button the default5120x200Default3
Makes the 4th button the default
(requires the Help button to be present)
7680x300Default4
174 | 175 |

Group #4: Modality

176 |

To indicate the modality of the dialog box, add one of the following values:

177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 |
FunctionDecHexString
System Modal (always on top)40960x1000N/A
Task Modal81920x2000N/A
Always-on-top (style WS_EX_TOPMOST)
(like System Modal but omits title bar icon)
2621440x40000N/A
203 | 204 |

Group #5: Other Options

205 |

To specify other options, add one or more of the following values:

206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 |
FunctionDecHexString
Adds a Help button (see remarks below)163840x4000N/A
Makes the text right-justified5242880x80000N/A
Right-to-left reading order for Hebrew/Arabic10485760x100000N/A
233 | 234 |

Return Value

235 |

Type: String

236 |

This function returns one of the following strings to represent which button the user pressed:

237 |
    238 |
  • OK
  • 239 |
  • Cancel
  • 240 |
  • Yes
  • 241 |
  • No
  • 242 |
  • Abort
  • 243 |
  • Retry
  • 244 |
  • Ignore
  • 245 |
  • TryAgain
  • 246 |
  • Continue
  • 247 |
  • Timeout (that is, the word "timeout" is returned if the message box timed out)
  • 248 |
249 |

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 |

Error Handling

252 |

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 |

Remarks

255 |

A message box usually looks like this:

256 | MsgBox 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.

271 |

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 |
    273 |
  1. The message box is owned by a GUI window by means of the OwnDialogs option.
  2. 274 |
  3. The script is monitoring the WM_HELP message (0x0053). For example: 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.
  4. 275 |
276 |

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 |

Related

280 |

InputBox, FileSelect, DirSelect, ToolTip, Gui object

281 |

Examples

282 |
283 |

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 |
286 | 287 |
288 |

Shows a message box with specific text and a title.

289 |
MsgBox "This MsgBox has a custom title.", "A Custom Title"
290 |
291 | 292 |
293 |

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 |
296 | 297 |
298 |

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 |
308 | 309 |
310 |

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 |     return
314 |
315 | 316 |
317 |

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 |     return
323 |
324 | 325 |
326 |

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 |
334 | 335 | 336 | -------------------------------------------------------------------------------- /docs/lib/NumGet.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | NumGet - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

NumGet

14 |

Returns the binary number stored at the specified address+offset.

15 |
Number := NumGet(Source, Offset, Type)
16 | Number := NumGet(Source, Type)
17 | 18 |

Parameters

19 |
20 | 21 |
Source
22 |
23 |

Type: Object or Integer

24 |

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 |
27 | 28 |
Offset
29 |
30 |

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 |
33 | 34 |
Type
35 |
36 |

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 |
41 | 42 |
43 | 44 |

Return Value

45 |

Type: Integer or Float

46 |

This function returns the binary number at the specified address+offset.

47 | 48 |

General Remarks

49 |

If only two parameters are present, the second parameter must be Type. For example, NumGet(var, "int") is valid.

50 |

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 |

Related

53 |

NumPut, DllCall, Buffer object, VarSetStrCapacity

54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /docs/lib/NumPut.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | NumPut - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

NumPut

14 |

Stores one or more numbers in binary format at the specified address+offset.

15 |
NumPut Type, Number, Type2, Number2, ... Target , Offset
16 | 17 |

Parameters

18 |
19 | 20 |
Type
21 |
22 |

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 |
27 | 28 |
Number
29 |
30 |

Type: Integer

31 |

The number to store.

32 |
33 | 34 |
Target
35 |
36 |

Type: Object or Integer

37 |

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 |
40 | 41 |
Offset
42 |
43 |

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 |
46 | 47 |
48 | 49 |

Return Value

50 |

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 |

General Remarks

54 |

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.

56 |

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 |

Related

59 |

NumGet, DllCall, Buffer object, VarSetStrCapacity

60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /docs/lib/Number.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Number - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Number

15 |

Converts a numeric string to a pure integer or floating-point number.

16 |
NumValue := Number(Value)
17 | 18 |

Return Value

19 |

Type: Integer or Float

20 |

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 |

Remarks

23 |

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.

26 | 27 |

Related

28 |

Type, Float, Integer, String, Values, Expressions, Is functions

29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /docs/lib/ObjAddRef.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ObjAddRef / ObjRelease - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ObjAddRef / ObjRelease

15 | 16 |

Increments or decrements an object's reference count.

17 | 18 |
NewRefCount := ObjAddRef(Ptr)
19 | NewRefCount := ObjRelease(Ptr)
20 |

Parameters

21 |
22 | 23 |
Ptr
24 |
25 |

Type: Integer

26 |

An unmanaged object pointer or COM interface pointer.

27 |
28 | 29 |
30 | 31 |

Return Value

32 |

Type: Integer

33 |

These functions return the new reference count. This value should be used only for debugging purposes.

34 | 35 |

Related

36 |

Reference Counting

37 |

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 | ObjBindMethod - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ObjBindMethod

14 | 15 |

Creates a BoundFunc object which calls a method of a given object.

16 | 17 |
BoundFunc := ObjBindMethod(Obj , Method, Params)
18 | 19 |

Parameters

20 |
21 | 22 |
Obj
23 |
24 |

Type: Object

25 |

Any object.

26 |
27 | 28 |
Method
29 |
30 |

Type: String

31 |

A method name. If omitted, the bound function calls Obj itself.

32 |
33 | 34 |
Params
35 |
36 |

Any number of parameters.

37 |
38 | 39 |
40 | 41 |

Remarks

42 |

For details and examples, see BoundFunc object.

43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /docs/lib/Object.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Object - Methods & Properties | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Object

14 |
class Object extends Any
15 | 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.

20 | 21 |

Table of Contents

22 |
    23 |
  • Static Methods: 24 |
      25 |
    • Call: Creates a new Object.
    • 26 |
    27 |
  • 28 |
  • Methods: 29 |
      30 |
    • Clone: Returns a shallow copy of an object.
    • 31 |
    • DefineProp: Defines or modifies an own property.
    • 32 |
    • DeleteProp: Removes an own property from an object.
    • 33 |
    • GetOwnPropDesc: Returns a descriptor for a given own property, compatible with DefineProp.
    • 34 |
    • HasOwnProp: Returns 1 (true) if an object owns a property by the specified name.
    • 35 |
    • OwnProps: Enumerates an object's own properties.
    • 36 |
    37 |
  • 38 |
  • Properties: 39 |
      40 |
    • Base: Retrieves or sets an object's base object.
    • 41 |
    42 |
  • 43 |
  • Functions: 44 |
      45 |
    • ObjSetBase: Set an object's base object.
    • 46 |
    • ObjGetCapacity, ObjSetCapacity: Retrieve or set an Object's capacity to contain properties.
    • 47 |
    • ObjOwnPropCount: Retrieve the number of own properties contained by an object.
    • 48 |
    • ObjHasOwnProp, ObjOwnProps: Equivalent to the corresponding predefined method, but cannot be overridden.
    • 49 |
    50 |
  • 51 |
52 | 53 |

Static Methods

54 | 55 |

Call

56 |

Creates a new Object.

57 |
Obj := Object()
 58 | Obj := Object.Call()
59 |
60 | 61 |

Methods

62 | 63 |

Clone

64 |

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 |
71 | 72 |

DefineProp

73 |

Defines or modifies an own property.

74 |
Obj := Obj.DefineProp(Name, Descriptor)
75 |

Parameters

76 |
77 |
Name
78 |
79 |

Type: String

80 |

The name of the property.

81 |
82 |
Descriptor
83 |
84 |

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 |
92 |
93 |

Return Value

94 |

Type: Object

95 |

This method returns the target object.

96 |

Remarks

97 |

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 |
    101 |
  • An inherited value property is equivalent to a set of accessor functions which return or call the value, or store a new value in this. Note that a new value would overwrite any dynamic property in this itself, and override any inherited accessor functions.
  • 102 |
  • If no Set or value is defined or inherited, attempting to set the property will throw an exception.
  • 103 |
  • If no Call is defined or inherited, Get may be called to retrieve a function object, which is then called.
  • 104 |
  • If no Get is defined or inherited but there is a Call accessor function, the function itself becomes the property's value (read-only).
  • 105 |
106 |

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.

107 |

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 |
109 | 110 |

DeleteProp

111 |

Removes an own property from an object.

112 |
RemovedValue := Obj.DeleteProp(Name)
113 |

Parameters

114 |
115 |
Name
116 |
117 |

Type: String

118 |

A property name.

119 |
120 |
121 |

Return Value

122 |

Type: Any

123 |

This method returns the value of the removed property (blank if none).

124 |
125 | 126 |

GetOwnPropDesc

127 |

Returns a descriptor for a given own property, compatible with DefineProp.

128 |
Descriptor := Obj.GetOwnPropDesc(Name)
129 |

Parameters

130 |
131 |
Name
132 |
133 |

Type: String

134 |

A property name.

135 |
136 |
137 |

Return Value

138 |

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%.

140 |

Modifying the returned object has no effect on Obj unless DefineProp is called.

141 |

Error Handling

142 |

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.

143 |
144 | 145 |

HasOwnProp

146 |

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).

149 |
150 | 151 |

OwnProps

152 |

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 |
156 |
Name
157 |
158 |

Type: String

159 |

The property's name.

160 |
161 |
Value
162 |
163 |

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 |
167 |
168 |

Dynamic properties are included in the enumeration. However:

169 |
    170 |
  • Since only the object's own properties are enumerated, the property must be defined directly in Obj.
  • 171 |
  • If only the first variable was specified, the property's name is returned and its getter is not called.
  • 172 |
  • If two variables were specified, the enumerator attempts to call the property's getter to retrieve the value. 173 |
      174 |
    • If the getter requires parameters, the property is skipped.
    • 175 |
    • If Obj itself does not define a getter for this property, it is skipped. 176 |

      Note: Properties defined by a method definition typically do not have a getter, so are skipped.

      177 |
    • 178 |
    • If Obj is a class prototype object, the getter should not (and in some cases cannot) be called; so the property is skipped.
    • 179 |
    • If the getter throws an exception, it is propagated (not suppressed). The caller can continue enumeration at the next property only if it retained a reference to the enumerator (i.e. not if it passed the enumerator directly to a for-loop, since in that case the enumerator is freed when the for-loop aborts).
    • 180 |
    181 |
  • 182 |
183 |

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 |
    186 |
  • If OwnProps returned the method itself when no getter is defined, defining a getter would then prevent the method from being returned. Scripts relying on the two variable mode to retrieve methods would then miss some methods.
  • 187 |
  • If OwnProps returned the method itself when a getter is defined by a base object, this would be inconsistent with normal evaluation of the property.
  • 188 |
189 |

The default implementation of this method is also defined as a function: ObjOwnProps(Obj).

190 |
191 | 192 |

Properties

193 | 194 |

Base

195 |

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.

200 |

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 |
204 | 205 |

Functions

206 |

ObjSetBase

207 |

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 |

ObjOwnPropCount

214 |

Returns the number of properties owned by an object.

215 |
Count := ObjOwnPropCount(Obj)
216 | 217 |

ObjSetCapacity

218 |

Sets the current capacity of the object's internal array of own properties.

219 |
MaxProps := ObjSetCapacity(Obj, MaxProps)
220 |

Parameters

221 |
222 |
MaxProps
223 |
224 |

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 |
227 |
228 |

Return Value

229 |

Type: Integer

230 |

This function returns the new capacity.

231 |

Error Handling

232 |

An exception is thrown if Obj is of an incorrect type.

233 | 234 |

ObjGetCapacity

235 |

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 | OnClipboardChange - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

OnClipboardChange

14 |

Registers a function to be called automatically whenever the clipboard's content changes.

15 | 16 |
OnClipboardChange Callback , AddRemove
17 |

Parameters

18 |
19 | 20 |
Callback
21 |
22 |

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 |
    28 |
  • 0 = Clipboard is now empty.
  • 29 |
  • 1 = Clipboard contains something that can be expressed as text (this includes files copied from an Explorer window).
  • 30 |
  • 2 = Clipboard contains something entirely non-text such as a picture.
  • 31 |
32 |

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(*).

33 |

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 |
35 | 36 |
AddRemove
37 |
38 |

Type: Integer

39 |

If omitted, it defaults to 1. Otherwise, specify one of the following numbers:

40 |
    41 |
  • 1 = Call the callback after any previously registered callbacks.
  • 42 |
  • -1 = Call the callback before any previously registered callbacks.
  • 43 |
  • 0 = Do not call the callback.
  • 44 |
45 |
46 | 47 |
48 | 49 |

Remarks

50 |

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.

52 | 53 |

Related

54 |

A_Clipboard, OnExit, OnMessage, CallbackCreate

55 | 56 |

Examples

57 |
58 |

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 |
67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /docs/lib/OnError.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | OnError - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

OnError

14 |

Registers a function to be called automatically whenever an unhandled error occurs.

15 | 16 |
OnError Callback , AddRemove
17 | 18 |

Parameters

19 |
20 | 21 |
Callback
22 |
23 |

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 |
    29 |
  1. The thrown value, usually an Error object.
  2. 30 |
  3. The error mode: Return, Exit, or ExitApp. For details, see the table below.
  4. 31 |
32 |

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, *).

33 |

The callback can return one of the following values (other values are reserved for future use and should be avoided):

34 |
    35 |
  • 0, "" or no Return: Allow error handling to proceed as normal.
  • 36 |
  • 1: Suppress the default error dialog and any remaining error callbacks.
  • 37 |
  • -1: As above, but if Mode (the second parameter) contains the word Return, execution of the current thread is permitted to continue.
  • 38 |
39 |
40 | 41 |
AddRemove
42 |
43 |

Type: Integer

44 |

If omitted, it defaults to 1. Otherwise, specify one of the following numbers:

45 |
    46 |
  • 1 = Call the callback after any previously registered callbacks.
  • 47 |
  • -1 = Call the callback before any previously registered callbacks.
  • 48 |
  • 0 = Do not call the callback.
  • 49 |
50 |
51 | 52 |
53 | 54 |

Error Modes

55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 |
ModeDescription
ReturnThe thrown value is a continuable runtime error. The thread continues if the callback returns -1; otherwise the thread exits.
ExitThe thrown value is a non-continuable runtime error or a value thrown by the script. The thread will exit.
ExitAppThe thrown value is a critical runtime error, such as corruption detected by DllCall. The program will exit.
73 | 74 |

Remarks

75 |

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 |

Related

79 |

Try, Catch, Throw, OnExit

80 | 81 |

Examples

82 |
83 |

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 |
94 | 95 |
96 |

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 |
163 | 164 | 165 | 166 | -------------------------------------------------------------------------------- /docs/lib/OnExit.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | OnExit - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

OnExit

14 | 15 |

Registers a function to be called automatically whenever the script exits.

16 | 17 |
OnExit Callback , AddRemove
18 |

Parameters

19 |
20 | 21 |
Callback
22 |
23 |

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 |
    29 |
  1. The exit reason (one of the words from the table below).
  2. 30 |
  3. The exit code passed to Exit or ExitApp.
  4. 31 |
32 |

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, *).

33 |

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 |
35 | 36 |
AddRemove
37 |
38 |

Type: Integer

39 |

If omitted, it defaults to 1. Otherwise, specify one of the following numbers:

40 |
    41 |
  • 1 = Call the callback after any previously registered callbacks.
  • 42 |
  • -1 = Call the callback before any previously registered callbacks.
  • 43 |
  • 0 = Do not call the callback.
  • 44 |
45 |
46 | 47 |
48 | 49 |

Remarks

50 |

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).

53 |

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 |

Exit Reasons

59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 |
ReasonDescription
LogoffThe user is logging off.
ShutdownThe system is being shut down or restarted, such as by the Shutdown function.
Close 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 |
ErrorA 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.
MenuThe user selected Exit from the main window's menu or from the standard tray menu.
ExitExit or ExitApp was used (includes custom menu items).
ReloadThe script is being reloaded via the Reload function or menu item.
SingleThe script is being replaced by a new instance of itself as a result of #SingleInstance.
101 | 102 |

Related

103 |

OnError, OnMessage, CallbackCreate, OnClipboardChange, ExitApp, Shutdown, Persistent, Threads, Return

104 | 105 |

Examples

106 |
107 |

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 |
122 | 123 |
124 |

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 |
140 | 141 | 142 | 143 | -------------------------------------------------------------------------------- /docs/lib/OnMessage.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | OnMessage - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

OnMessage

14 | 15 |

Registers a function to be called automatically whenever the script receives the specified message.

16 | 17 |
OnMessage MsgNumber, Callback , MaxThreads
18 |

Parameters

19 |
20 | 21 |
MsgNumber
22 |
23 |

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 |
26 | 27 |
Callback
28 |
29 |

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 |
    35 |
  1. The message's WPARAM value.
  2. 36 |
  3. The message's LPARAM value.
  4. 37 |
  5. The message number, which is useful in cases where a callback monitors more than one message.
  6. 38 |
  7. The HWND (unique ID) of the window or control to which the message was sent. The HWND can be used directly in a WinTitle parameter.
  8. 39 |
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, *).

41 |

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) - 1
44 |
45 | 46 |
MaxThreads
47 |
48 |

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.

53 |
54 | 55 |
56 | 57 |

Usage

58 |

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 1
62 |

This registers a callback to be called before any previously registered callbacks:

63 |
OnMessage MsgNumber, Callback, -1
64 |

To unregister a callback, specify 0 for MaxThreads:

65 |
OnMessage MsgNumber, Callback, 0
66 | 67 |

Additional Information Available to the Callback

68 |

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 |

What the Callback Should Return

74 |

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).

76 |

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 |

General Remarks

79 |

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 |
    84 |
  • If the message is posted rather than sent and has a number greater than 0x0311, it can be buffered until its callback completes by specifying Critical as the first line of the callback. Alternatively, Thread Interrupt can achieve the same effect as long as it lasts long enough for the callback to finish.
  • 85 |
  • Using Critical to increase the message check interval gives the callback more time to complete before any messages are dispatched. An interval greater than 16 may be needed for reliability. Due to the granularity of the system timer (usually 15.6 milliseconds), the default interval for non-Critical threads (5 milliseconds) might appear to pass the instant after the callback starts.
  • 86 |
  • Ensuring that the callback returns quickly reduces the risk that messages will be missed due to MaxThreads. One way to do this is to have it queue up a future thread by posting to its own script a monitored message number greater than 0x0311. That message's callback should use Critical as its first line to ensure that its messages are buffered. Alternatively, a timer can be used to queue up a future thread.
  • 87 |
  • Specifying a higher value for MaxThreads allows the callback to be interrupted to process the newly-received message.
  • 88 |
89 |

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 |

Related

96 |

CallbackCreate, OnExit, OnClipboardChange, PostMessage, SendMessage, Functions, Windows Messages, Threads, Critical, DllCall

97 |

Examples

98 |
99 |

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 |
121 | 122 |
123 |

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 |
170 | 171 |
172 |

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 |
190 | 191 |
192 |

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 |
243 | 244 |

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 | Ord - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Ord

14 | 15 |

Returns the ordinal value (numeric character code) of the first character in the specified string.

16 | 17 |
Number := Ord(String)
18 |

Parameters

19 |
20 | 21 |
String
22 |
23 |

Type: String

24 |

The string whose ordinal value is retrieved.

25 |
26 | 27 |
28 | 29 |

Return Value

30 |

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 |

Related

34 |

Chr

35 |

Examples

36 |
37 |

Both message boxes below show 116, because only the first character is considered.

38 |
MsgBox Ord("t") 
39 | MsgBox Ord("test")
40 |
41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /docs/lib/OutputDebug.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | OutputDebug - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

OutputDebug

14 | 15 |

Sends a string to the debugger (if any) for display.

16 | 17 |
OutputDebug Text
18 |

Parameters

19 |
20 | 21 |
Text
22 |
23 |

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 |
26 | 27 |
28 | 29 |

Remarks

30 |

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 |

Related

34 |

FileAppend, continuation sections

35 |

Examples

36 |
37 |

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 |
40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /docs/lib/Pause.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Pause - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Pause

14 | 15 |

Pauses the script's current thread or sets the pause state of the underlying thread.

16 | 17 |
18 | Pause UnderlyingThreadState
19 | 
20 |

Parameters

21 |
22 | 23 |
UnderlyingThreadState
24 |
25 |

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).

28 |

0 or False: Unpauses the underlying thread.

29 |

-1: Toggles the pause state of the underlying thread.

30 |
31 | 32 |
33 | 34 |

Remarks

35 |

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 a green icon with a Pause symbol (or to a green icon with a transparent Pause symbol 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).

39 |

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 |

Related

44 |

Suspend, Menu object, ExitApp, Threads, SetTimer

45 | 46 |

Examples

47 |
48 |

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 |
53 | 54 |
55 |

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+P
58 |
59 | 60 |
61 |

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 |
67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /docs/lib/Persistent.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Persistent - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Persistent

15 | 16 |

Prevents the script from exiting automatically when its last thread completes, allowing it to stay running in an idle state.

17 |
Persistent Persist
18 | 19 |

Parameters

20 |
21 |
Persist
22 |
23 |

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 |
28 |
29 | 30 |

Return Value

31 |

Type: Integer (boolean)

32 |

This function returns the previous setting; either 0 (false) or 1 (true).

33 | 34 |

Remarks

35 |

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 |
    39 |
  • Scripts which use OnMessage or CallbackCreate and DllCall to respond to events, since those functions don't make the script persistent.
  • 40 |
  • Scripts that are executed by selecting a custom tray menu item.
  • 41 |
  • Scripts which create or retrieve COM objects and use ComObjConnect to respond to the object's events.
  • 42 |
43 |

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 |

Related

46 |

Exit, ExitApp

47 |

Examples

48 |
49 |

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 | Persistent
54 |
55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /docs/lib/PixelGetColor.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | PixelGetColor - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

PixelGetColor

14 | 15 |

Retrieves the color of the pixel at the specified X and Y coordinates.

16 | 17 |
Color := PixelGetColor(X, Y , Mode)
18 |

Parameters

19 |
20 | 21 |
X, Y
22 |
23 |

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 |
26 | 27 |
Mode
28 |
29 |

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").

31 |

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 |
34 | 35 |
36 | 37 |

Return Value

38 |

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 |

Error Handling

42 |

An OSError is thrown on failure.

43 | 44 |

Remarks

45 |

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 |
    49 |
  • A window that is partially transparent or that has one of its colors marked invisible (WinSetTransColor) typically yields colors for the window behind itself rather than its own.
  • 50 |
  • PixelGetColor might not produce accurate results for certain applications. If this occurs, try specifying the word Alt or Slow in the last parameter.
  • 51 |
52 |

Related

53 |

PixelSearch, ImageSearch, CoordMode, MouseGetPos

54 |

Examples

55 |
56 |

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 |
63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /docs/lib/PixelSearch.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | PixelSearch - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

PixelSearch

14 | 15 |

Searches a region of the screen for a pixel of the specified color.

16 | 17 |
PixelSearch &OutputVarX, &OutputVarY, X1, Y1, X2, Y2, ColorID , Variation
18 |

Parameters

19 |
20 | 21 |
&OutputVarX, &OutputVarY
22 |
23 |

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 |
26 | 27 |
X1, Y1
28 |
29 |

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 |
32 | 33 |
X2, Y2
34 |
35 |

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 |
38 | 39 |
ColorID
40 |
41 |

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.

43 |
44 | 45 |
Variation
46 |
47 |

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 |
50 | 51 |
52 | 53 |

Return Value

54 |

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 |

Error Handling

58 |

An OSError is thrown if there was a problem that prevented the function from conducting the search.

59 | 60 |

Remarks

61 |

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 |

Related

68 |

PixelGetColor, ImageSearch, CoordMode, MouseGetPos

69 |

Examples

70 |
71 |

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 |
78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /docs/lib/PostMessage.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | PostMessage - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

PostMessage

14 | 15 |

Places a message in the message queue of a window or control.

16 | 17 |
PostMessage MsgNumber , wParam, lParam, Control, WinTitle, WinText, ExcludeTitle, ExcludeText
18 |

Parameters

19 |
20 | 21 |
MsgNumber
22 |
23 |

Type: Integer

24 |

The message number to send. See the message list to determine the number.

25 |
26 | 27 |
wParam, lParam
28 |
29 |

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 |
34 | 35 |
Control
36 |
37 |

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.

39 |

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 |
41 | 42 |
WinTitle, WinText, ExcludeTitle, ExcludeText
43 |
44 |

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 |
49 | 50 |
51 | 52 |

Error Handling

53 |

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 |

Remarks

57 |

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.

61 |

To have a script receive a message, use OnMessage.

62 |

See the Message Tutorial for an introduction to using this function.

63 | 64 |

Related

65 |

SendMessage, Message List, Message Tutorial, OnMessage, Automating Winamp, DllCall, ControlSend, MenuSelect

66 |

Examples

67 |
68 |

Switches the active window's keyboard layout/language to English (US).

69 |
PostMessage 0x0050, 0, 0x4090409,, "A"  ; 0x0050 is WM_INPUTLANGCHANGEREQUEST.
70 |
71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /docs/lib/Process.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | List of Process Functions | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Process Functions

14 | 15 |

Functions for retrieving information about a process or for performing various operations on a process. Click on a function name for details.

16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 |
FunctionDescription
ProcessCloseForces the first matching process to close.
ProcessExistChecks if the specified process exists.
ProcessGetNameReturns the name of the specified process.
ProcessGetParentReturns the process ID (PID) of the process which created the specified process.
ProcessGetPathReturns the path of the specified process.
ProcessSetPriorityChanges the priority level of the first matching process.
ProcessWaitWaits for the specified process to exist.
ProcessWaitCloseWaits for all matching processes to close.
54 | 55 |

Remarks

56 |

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 |

Related

59 |

Run, WinClose, WinKill, WinWait, WinWaitClose, WinExist, Win functions

60 | 61 |

Examples

62 | 63 |
64 |

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", 0
109 |
110 | 111 |
112 |

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 |
119 | 120 | 121 | 122 | -------------------------------------------------------------------------------- /docs/lib/ProcessClose.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ProcessClose - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ProcessClose

15 | 16 |

Forces the first matching process to close.

17 | 18 |
ProcessClose PIDOrName
19 | 20 |

Parameters

21 |
22 |
PIDOrName
23 |
24 |

Type: Integer or String

25 |

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 |
29 |
30 | 31 |

Return Value

32 |

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 |

Remarks

36 |

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 |

Related

39 |

Run, WinClose, WinKill, Process functions, Win functions

40 | 41 |

Examples

42 |
43 |

Forces the first matching process to close (be warned that any unsaved data will be lost).

44 |
ProcessClose "notepad.exe"
45 |
46 |
47 |

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 |
60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /docs/lib/ProcessExist.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ProcessExist - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ProcessExist

15 | 16 |

Checks if the specified process exists.

17 | 18 |
PID := ProcessExist(PIDOrName)
19 | 20 |

Parameters

21 |
22 |
PIDOrName
23 |
24 |

Type: Integer or String

25 |

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 |
29 |
30 | 31 |

Return Value

32 |

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 |

Related

36 |

Run, WinExist, Process functions, Win functions

37 | 38 |

Examples

39 |
40 |

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 |
46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /docs/lib/ProcessGetName.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ProcessGetName / ProcessGetPath - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ProcessGetName / ProcessGetPath

15 | 16 |

Returns the name or path of the specified process.

17 | 18 |
Name := ProcessGetName(PIDOrName)
19 | Path := ProcessGetPath(PIDOrName)
20 | 21 |

Parameters

22 |
23 |
PIDOrName
24 |
25 |

Type: Integer or String

26 |

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 |
30 |
31 | 32 |

Return Value

33 |

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 |

Error Handling

38 |

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 |

Related

42 |

Process functions, Run, WinGetProcessName, WinGetProcessPath

43 | 44 |

Examples

45 |
46 |

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 |
56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /docs/lib/ProcessGetParent.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ProcessGetParent - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ProcessGetParent

15 | 16 |

Returns the process ID (PID) of the process which created the specified process.

17 | 18 |
PID := ProcessGetParent(PIDOrName)
19 | 20 |

Parameters

21 |
22 |
PIDOrName
23 |
24 |

Type: Integer or String

25 |

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 |
29 |
30 | 31 |

Return Value

32 |

Type: Integer

33 |

This function returns the process ID (PID) of the process which created the specified process.

34 | 35 |

Error Handling

36 |

A TargetError is thrown if the specified process could not be found.

37 | 38 |

Remarks

39 |

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 |

Related

42 |

Process functions

43 | 44 |

Examples

45 |
46 |

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 |
53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /docs/lib/ProcessSetPriority.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ProcessSetPriority - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ProcessSetPriority

15 | 16 |

Changes the priority level of the first matching process.

17 | 18 |
ProcessSetPriority Level , PIDOrName
19 | 20 |

Parameters

21 |
22 |
Level
23 |
24 |

Type: String

25 |

Specify one of the following words or letters:

26 |
    27 |
  • Low (or L)
  • 28 |
  • BelowNormal (or B)
  • 29 |
  • Normal (or N)
  • 30 |
  • AboveNormal (or A)
  • 31 |
  • High (or H)
  • 32 |
  • Realtime (or R)
  • 33 |
34 |

Note that any process not designed to run at Realtime priority might reduce system stability if set to that level.

35 |
36 |
PIDOrName
37 |
38 |

Type: Integer or String

39 |

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 |
43 |
44 | 45 |

Return Value

46 |

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 |

Remarks

50 |

The current priority level of a process can be seen in the Windows Task Manager.

51 | 52 |

Related

53 |

Run, Process functions, Win functions

54 | 55 |

Examples

56 | 57 |
58 |

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 " NewPID
62 |
63 | 64 |
65 |

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 |
95 | 96 | 97 | 98 | -------------------------------------------------------------------------------- /docs/lib/ProcessWait.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ProcessWait - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ProcessWait

15 | 16 |

Waits for the specified process to exist.

17 | 18 |
PID := ProcessWait(PIDOrName , Timeout)
19 | 20 |

Parameters

21 |
22 |
PIDOrName
23 |
24 |

Type: Integer or String

25 |

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 |
29 |
Timeout
30 |
31 |

Type: Integer or Float

32 |

If omitted, the function will wait indefinitely. Otherwise, specify the number of seconds (can contain a decimal point) to wait before timing out.

33 |
34 |
35 | 36 |

Return Value

37 |

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 |

Remarks

41 |

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 |

Related

44 |

ProcessWaitClose, Run, WinWait, Process functions, Win functions

45 | 46 |

Examples

47 | 48 |
49 |

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 |
65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /docs/lib/ProcessWaitClose.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ProcessWaitClose - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

ProcessWaitClose

15 | 16 |

Waits for all matching processes to close.

17 | 18 |
PID := ProcessWaitClose(PIDOrName , Timeout)
19 | 20 |

Parameters

21 |
22 |
PIDOrName
23 |
24 |

Type: Integer or String

25 |

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 |
29 |
Timeout
30 |
31 |

Type: Integer or Float

32 |

If omitted, the function will wait indefinitely. Otherwise, specify the number of seconds (can contain a decimal point) to wait before timing out.

33 |
34 |
35 | 36 |

Return Value

37 |

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 |

Remarks

41 |

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 |

Related

44 |

ProcessWait, Run, WinWaitClose, Process functions, Win functions

45 | 46 |

Examples

47 |

See example #1 on the ProcessWait page.

48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /docs/lib/Random.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Random - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Random

14 | 15 |

Generates a pseudo-random number.

16 | 17 |
N := Random(A, B)
18 |

Parameters

19 |
20 | 21 |
A, B
22 |
23 |

Type: Integer or Float

24 |

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 |
28 | 29 |
30 | 31 |

Return Value

32 |

Type: Integer or Float

33 |

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 |

Remarks

37 |

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 |

Examples

41 |
42 |

Generates a random integer in the range 1 to 10 and stores it in N.

43 |
N := Random(1, 10)
44 |
45 | 46 |
47 |

Generates a random integer in the range 0 to 9 and stores it in N.

48 |
N := Random(9)
49 |
50 | 51 |
52 |

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 |
56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /docs/lib/RegCreateKey.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | RegCreateKey - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

RegCreateKey

15 | 16 |

Creates a registry key without writing a value.

17 | 18 |
RegCreateKey KeyName
19 |

Parameters

20 |
21 | 22 |
KeyName
23 |
24 |

Type: String

25 |

The full name of the registry key, e.g. "HKLM\Software\SomeApplication".

26 |

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".

28 |

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 |
30 | 31 |
32 |

Error Handling

33 |

An OSError is thrown on failure.

34 |

A_LastError is set to the result of the operating system's GetLastError() function.

35 | 36 |

Remarks

37 |

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 |

Related

42 |

RegDelete, RegDeleteKey, RegRead, RegWrite, registry loop, SetRegView

43 | 44 |

Examples

45 |
46 |

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 |
49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /docs/lib/RegDelete.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | RegDelete - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

RegDelete

14 | 15 |

Deletes a value from the registry.

16 | 17 |
RegDelete KeyName, ValueName
18 |

Parameters

19 |
20 | 21 |
KeyName
22 |
23 |

Type: String

24 |

The full name of the registry key, e.g. "HKLM\Software\SomeApplication".

25 |

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".

27 |

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 |
29 | 30 |
ValueName
31 |
32 |

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 |
35 | 36 |
37 |

Error Handling

38 |

An OSError is thrown on failure.

39 |

A_LastError is set to the result of the operating system's GetLastError() function.

40 | 41 |

Remarks

42 |

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.

45 |

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 |

Related

49 |

RegCreateKey, RegDeleteKey, RegRead, RegWrite, registry loop, SetRegView, IniDelete

50 | 51 |

Examples

52 |
53 |

Deletes a value from the registry.

54 |
RegDelete "HKEY_LOCAL_MACHINE\Software\SomeApplication", "TestValue"
55 |
56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /docs/lib/RegDeleteKey.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | RegDeleteKey - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

RegDeleteKey

15 | 16 |

Deletes a subkey from the registry.

17 | 18 |
RegDeleteKey KeyName
19 |

Parameters

20 |
21 | 22 |
KeyName
23 |
24 |

Type: String

25 |

The full name of the registry key, e.g. "HKLM\Software\SomeApplication".

26 |

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".

28 |

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 |
30 | 31 |
32 |

Error Handling

33 |

An OSError is thrown on failure.

34 |

A_LastError is set to the result of the operating system's GetLastError() function.

35 | 36 |

Remarks

37 |

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.

40 |

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 |

Related

44 |

RegCreateKey, RegDelete, RegRead, RegWrite, registry loop, SetRegView, IniDelete

45 | 46 |

Examples

47 |
48 |

Deletes a subkey from the registry.

49 |
RegDeleteKey "HKEY_LOCAL_MACHINE\Software\SomeApplication"
50 |
51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /docs/lib/RegExMatch.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | RegExMatch - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

RegExMatch

14 | 15 |

Determines whether a string contains a pattern (regular expression).

16 | 17 |
FoundPos := RegExMatch(Haystack, NeedleRegEx , &OutputVar, StartingPos)
18 |

Parameters

19 |
20 | 21 |
Haystack
22 |
23 |

Type: String

24 |

The string whose content is searched. This may contain binary zero.

25 |
26 | 27 |
NeedleRegEx
28 |
29 |

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.

32 |
33 | 34 |
&OutputVar
35 |
36 |

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 |
40 | 41 |
StartingPos
42 |
43 |

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).

47 |

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 |
49 | 50 |
51 | 52 |

Return Value

53 |

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 |

Errors

57 |

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 |

Options

61 |

See RegEx Quick Reference for options such as i)abc, which turns off case-sensitivity.

62 | 63 |

Match Object (RegExMatchInfo)

64 |

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 |
    73 |
  • 0 for the overall match.
  • 74 |
  • The number of a subpattern, even one that also has a name.
  • 75 |
  • The name of a subpattern.
  • 76 |
77 |

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.

78 |

The object also supports enumeration; that is, the for-loop is supported. Alternatively, use Loop Match.Count.

79 | 80 |

Performance

81 |

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 |

Remarks

86 |

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].

87 |

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.

88 |

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).

92 |

Related

93 |

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 |

Examples

97 |

For general RegEx examples, see the RegEx Quick Reference.

98 | 99 |
100 |

Reports 4, which is the position where the match was found.

101 |
MsgBox RegExMatch("xxxabc123xyz", "abc.*xyz")
102 |
103 | 104 |
105 |

Reports 7 because the $ requires the match to be at the end.

106 |
MsgBox RegExMatch("abc123123", "123$")
107 |
108 | 109 |
110 |

Reports 1 because a match was achieved via the case-insensitive option.

111 |
MsgBox RegExMatch("abc123", "i)^ABC")
112 |
113 | 114 |
115 |

Reports 1 and stores "XYZ" in SubPat[1].

116 |
MsgBox RegExMatch("abcXYZ123", "abc(.*)123", &SubPat)
117 |
118 | 119 |
120 |

Reports 7 instead of 1 due to the starting position 2 instead of 1.

121 |
MsgBox RegExMatch("abc123abc456", "abc\d+",, 2)
122 |
123 | 124 |
125 |

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 |
129 | 130 |
131 |

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 |
136 | 137 |
138 |

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 |
168 | 169 | 170 | 171 | -------------------------------------------------------------------------------- /docs/lib/RegExReplace.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | RegExReplace - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

RegExReplace

14 | 15 |

Replaces occurrences of a pattern (regular expression) inside a string.

16 | 17 |
NewStr := RegExReplace(Haystack, NeedleRegEx , Replacement, &OutputVarCount, Limit, StartingPos)
18 |

Parameters

19 |
20 | 21 |
Haystack
22 |
23 |

Type: String

24 |

The string whose content is searched and replaced. This may contain binary zero.

25 |
26 | 27 |
NeedleRegEx
28 |
29 |

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.

32 |
33 | 34 |
Replacement
35 |
36 |

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 |
42 | 43 |
&OutputVarCount
44 |
45 |

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 |
48 | 49 |
Limit
50 |
51 |

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 |
54 | 55 |
StartingPos
56 |
57 |

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).

61 |

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 |
63 | 64 |
65 | 66 |

Return Value

67 |

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 |

Errors

71 |

An Error is thrown if:

72 |
    73 |
  • the pattern contains a syntax error; or
  • 74 |
  • an error occurred during the execution of the regular expression.
  • 75 |
76 |

For details, see RegExMatch.

77 | 78 |

Options

79 |

See RegEx Quick Reference for options such as i)abc, which turns off case-sensitivity.

80 |

Performance

81 |

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 |

Remarks

86 |

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.

87 |

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 |

Related

90 |

RegExMatch, RegEx Quick Reference, Regular Expression Callouts, StrReplace, InStr

91 |

Common sources of text data: FileRead, Download, A_Clipboard, GUI Edit controls

92 |

Examples

93 |

For general RegEx examples, see the RegEx Quick Reference.

94 |
95 |

Reports "abc123xyz" because the $ allows a match only at the end.

96 |
MsgBox RegExReplace("abc123123", "123$", "xyz")
97 |
98 | 99 |
100 |

Reports "123" because a match was achieved via the case-insensitive option.

101 |
MsgBox RegExReplace("abc123", "i)^ABC")
102 |
103 | 104 |
105 |

Reports "aaaXYZzzz" by means of the $1 backreference.

106 |
MsgBox RegExReplace("abcXYZ123", "abc(.*)123", "aaa$1zzz")
107 |
108 | 109 |
110 |

Reports an empty string and stores 2 in ReplacementCount.

111 |
MsgBox RegExReplace("abc123abc456", "abc\d+", "", &ReplacementCount)
112 |
113 | 114 | 115 | 116 | -------------------------------------------------------------------------------- /docs/lib/RegRead.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | RegRead - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

RegRead

14 | 15 |

Reads a value from the registry.

16 | 17 |
Value := RegRead(KeyName, ValueName, Default)
18 | 
19 |

Parameters

20 |
21 | 22 |
KeyName
23 |
24 |

Type: String

25 |

The full name of the registry key, e.g. "HKLM\Software\SomeApplication".

26 |

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".

28 |

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 |
30 | 31 |
ValueName
32 |
33 |

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 |
36 | 37 |
Default
38 |
39 |

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 |
42 | 43 |
44 | 45 |

Return Value

46 |

Type: String or Integer

47 |

This function returns a value of the specified registry key.

48 | 49 |

Error Handling

50 |

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 |

Remarks

54 |

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.

56 |

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 |

Related

63 |

RegCreateKey, RegDelete, RegDeleteKey, RegWrite, registry loop, SetRegView, IniRead

64 | 65 |

Examples

66 |
67 |

Reads a value from the registry and store it in TestValue.

68 |
TestValue := RegRead("HKEY_LOCAL_MACHINE\Software\SomeApplication", "TestValue")
69 |
70 | 71 |
72 |

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: " ProgramFilesDir
79 |
80 | 81 | 82 |
83 |

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 |
95 | 96 | 97 | 98 | -------------------------------------------------------------------------------- /docs/lib/RegWrite.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | RegWrite - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

RegWrite

14 | 15 |

Writes a value to the registry.

16 | 17 |
RegWrite Value, ValueType, KeyName , ValueName
18 | RegWrite Value , ValueType, , ValueName
19 | 
20 |

Parameters

21 |
22 | 23 |
Value
24 |
25 |

Type: String or Integer

26 |

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 |
28 | 29 |
ValueType
30 |
31 |

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 |
35 | 36 |
KeyName
37 |
38 |

Type: String

39 |

The full name of the registry key, e.g. "HKLM\Software\SomeApplication".

40 |

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".

42 |

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 |
44 | 45 |
ValueName
46 |
47 |

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 |
50 | 51 |
52 | 53 |

Error Handling

54 |

An OSError is thrown on failure.

55 |

A_LastError is set to the result of the operating system's GetLastError() function.

56 | 57 |

Remarks

58 |

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.

61 |

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 |

Related

68 |

RegCreateKey, RegDelete, RegDeleteKey, RegRead, registry loop, SetRegView, IniWrite

69 | 70 |

Examples

71 |
72 |

Writes a string to the registry.

73 |
RegWrite "Test Value", "REG_SZ", "HKEY_LOCAL_MACHINE\SOFTWARE\TestKey", "MyValueName"
74 |
75 | 76 |
77 |

Writes binary data to the registry.

78 |
RegWrite "01A9FF77", "REG_BINARY", "HKEY_CURRENT_USER\Software\TEST_APP", "TEST_NAME"
79 |
80 | 81 |
82 |

Writes a multi-line string to the registry.

83 |
RegWrite "Line1`nLine2", "REG_MULTI_SZ", "HKEY_CURRENT_USER\Software\TEST_APP", "TEST_NAME"
84 |
85 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /docs/lib/Reload.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Reload - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Reload

14 | 15 |

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.

22 |

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 | return
30 |

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 | ExitApp
37 | 38 |

Related

39 |

Edit

40 |

Examples

41 |
42 |

Press a hotkey to restart the script.

43 |
^!r::Reload  ; Ctrl+Alt+R
44 |
45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/lib/Return.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Return - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Return

14 | 15 |

Returns from a function to which execution had previously jumped via function-call, Hotkey activation, or other means.

16 | 17 |
Return Expression
18 |

Parameters

19 |
20 | 21 |
Expression
22 |
23 |

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 |
34 | 35 |
36 | 37 |

Remarks

38 |

The space or tab after Return is optional if the expression is enclosed in parentheses, as in return(expression).

39 |

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 |

Related

43 |

Functions, Exit, ExitApp

44 | 45 |

Examples

46 |
47 |

Reports the value returned by the function.

48 |
MsgBox returnTest() ; Shows 123
49 | 
50 | returnTest() {
51 |     return 123
52 | }
53 |
54 |
55 |

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 |
71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /docs/lib/Run.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Run / RunWait - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 13 | 14 | 15 | 16 |

Run / RunWait

17 | 18 |

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 |

Parameters

25 |
26 | 27 |
Target
28 |
29 |

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 |
36 | 37 |
WorkingDir
38 |
39 |

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 |
42 | 43 |
Options
44 |
45 |

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 |
52 | 53 |
&OutputVarPID
54 |
55 |

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.

58 |
59 | 60 |
61 | 62 |

Return Value

63 |

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 |

Error Handling

67 |

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 |

Interpretation of Target

75 |

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 |
    77 |
  • If no verb is specified, Target is passed as-is to the lpCommandLine parameter of CreateProcess.
  • 78 |
  • If a verb is specified or CreateProcess fails, and RunAs is not in effect, ShellExecuteEx is attempted.
  • 79 |
80 |

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.

81 |

When ShellExecuteEx is being attempted, Target is interpreted as follows:

82 |
    83 |
  • The substring of Target ending at the first space or tab may be either a predefined verb name or an asterisk followed by a verb name. If present, the optional asterisk, verb name and a single delimiting space or tab are excluded from further consideration. Verb names containing spaces or tabs are not supported, but symbols such as hyphen are permitted.
  • 84 |
  • If a leading double-quote mark is present, the substring between that and the next double-quote mark is considered to be the target file or action.
  • 85 |
  • Otherwise, the first substring which ends at a space and is either an existing file (specified by absolute path or relative to WorkingDir) or ends in .exe, .bat, .com, .cmd or .hta is considered the action. This allows file types such as .ahk, .vbs or .lnk to accept parameters while still allowing "known" executables such as wordpad.exe to be launched without an absolute path.
  • 86 |
  • A single delimiting space is ignored, if present, and the remainder of Target is passed as-is to CreateProcess or ShellExecuteEx as command-line parameters.
  • 87 |
88 |

Remarks

89 |

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".

92 |

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 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 |
VerbDescription
*verbAny 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.
properties 109 |

Displays the Explorer's properties window for the indicated file. For example: Run 'properties "C:\My File.txt"'

110 |

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 |
findOpens an instance of the Explorer's Search Companion or Find File window at the indicated folder. For example: Run "find D:\"
exploreOpens an instance of Explorer at the indicated folder. For example: Run "explore " A_ProgramFiles.
editOpens 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"'
openOpens the indicated file (normally not needed because it is the default action for most file types). For example: Run 'open "My File.txt"'.
printPrints the indicated file with the associated application, if any. For example: Run 'print "My File.txt"'
134 |

While RunWait is in a waiting state, new threads can be launched via hotkey, custom menu item, or timer.

135 | 136 |

Run as Administrator

137 |

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_line
153 |

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.

156 |

The example can be modified to fit the script's needs:

157 |
    158 |
  • If the script absolutely requires admin rights, check A_IsAdmin a second time in case *RunAs failed to elevate the script (i.e. because UAC is disabled).
  • 159 |
  • To keep the script running even if the user cancels the UAC prompt, move ExitApp into the try block.
  • 160 |
  • To keep the script running even if it failed to restart (i.e. because the script file has been changed or deleted), remove ExitApp and use RunWait instead of Run. On success, /restart causes the new instance to terminate the old one. On failure, the new instance exits and RunWait returns.
  • 161 |
162 |

AutoHotkey's installer registers the RunAs verb for .ahk files, which allows Run "*RunAs script.ahk" to launch a script as admin.

163 | 164 |

Related

165 |

RunAs, Process functions, Exit, CLSID List, DllCall

166 | 167 |

Examples

168 |
169 |

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 |
172 | 173 |
174 |

Run is able to launch URLs:

175 |

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 |
182 | 183 |
184 |

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 |
189 | 190 |
191 |

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 |
197 | 198 |
199 |

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 |
205 | 206 |
207 |

To run multiple commands consecutively, use "&&" between each.

208 |
Run A_ComSpec "/c dir /b > C:\list.txt && type C:\list.txt && pause"
209 |
210 | 211 |
212 |

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 |
241 | 242 |
243 |

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 |
262 | 263 | 264 | 265 | -------------------------------------------------------------------------------- /docs/lib/RunAs.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | RunAs - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

RunAs

14 | 15 |

Specifies a set of user credentials to use for all subsequent Run and RunWait functions.

16 | 17 |
RunAs User, Password, Domain
18 |

Parameters

19 |
20 | 21 |
User
22 |
23 |

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 |
26 | 27 |
Password
28 |
29 |

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 |
32 | 33 |
Domain
34 |
35 |

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 |
38 | 39 |
40 |

Remarks

41 |

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 |

Related

47 |

Run, RunWait

48 |

Examples

49 |
50 |

Opens the registry editor as administrator.

51 |
RunAs "Administrator", "MyPassword"
52 | Run "RegEdit.exe"
53 | RunAs  ; Reset to normal behavior.
54 |
55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /docs/lib/Send.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Send - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Send / SendText / SendInput / SendPlay / SendEvent

14 | 15 |

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 Keys
22 | 23 |

Parameters

24 |
25 | 26 |
Keys
27 |
28 |

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.

31 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 |
SymbolKeyPressReleaseExamples
^{Ctrl}{Ctrl down}{Ctrl up}Send "^{Home}" presses Ctrl+Home
+{Shift}{Shift down}{Shift up}Send "+abC" sends the text "AbC"
58 | Send "!+a" presses Alt+Shift+A
!{Alt}{Alt down}{Alt up}Send "!a" presses Alt+A
#{LWin}
{RWin}
{LWin down}
{RWin down}
{LWin up}
{RWin up}
Send "#e" holds down Win and presses E
75 |

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.

76 |

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.

77 |

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.

78 |
79 | 80 |
81 | 82 |

Send variants

83 |

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 |

Special modes

90 |

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}.

91 | 92 |

Raw mode

93 |

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.

94 |

The Raw mode does not affect the interpretation of escape sequences and expressions. For example, Send "{Raw}``100`%" sends the string `100%.

95 | 96 |

Text mode

97 |

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.

98 |

`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.

99 |

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}.

100 | 101 |

Blind mode

102 |

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:

103 |
    104 |
  • The Blind mode avoids releasing the modifier keys (Alt, Ctrl, Shift, and Win) if they started out in the down position, unless the modifier is excluded. For example, the hotkey +s::Send "{Blind}abc" would send ABC rather than abc because the user is holding down Shift.
  • 105 |
  • Modifier keys are restored differently to allow a Send to turn off a hotkey's modifiers even if the user is still physically holding them down. For example, ^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.
  • 106 |
  • SetStoreCapsLockMode is ignored; that is, the state of CapsLock is not changed.
  • 107 |
  • Menu masking is disabled. That is, Send omits the extra keystrokes that would otherwise be sent in order to prevent: 1) Start Menu appearance during Win keystrokes (LWin/RWin); 2) menu bar activation during Alt keystrokes. However, the Blind mode does not prevent masking performed by the keyboard hook following activation of a hook hotkey.
  • 108 |
  • Send does not wait for Win to be released even if the text contains an L keystroke. This would normally be done to prevent Send from triggering the system "lock workstation" hotkey (Win+L). See Hotkeys for details.
  • 109 |
110 |

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.

111 |

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.

112 |

{Blind} is not supported by SendText or ControlSendText; use {Blind}{Text} instead.

113 |

The Blind mode is not completely supported by SendPlay, especially when dealing with the modifier keys (Ctrl, Alt, Shift, and Win).

114 | 115 |

Key names

116 |

The following table lists the special keys that can be sent (each key name must be enclosed in braces):

117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 300 | 301 | 302 | 303 | 305 | 306 | 307 | 310 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 |
Key nameDescription
{F1} - {F24}Function keys. For example: {F12} is F12.
{!}!
{#}#
{+}+
{^}^
{{}{
{}}}
{Enter}Enter on the main keyboard
{Escape} or {Esc}Esc
{Space}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)
{Tab}Tab
{Backspace} or {BS}Backspace
{Delete} or {Del}Del
{Insert} or {Ins}Ins
{Up}↑ (up arrow) on main keyboard
{Down}↓ (down arrow) on main keyboard
{Left}← (left arrow) on main keyboard
{Right}→ (right arrow) on main keyboard
{Home}Home on main keyboard
{End}End on main keyboard
{PgUp}PgUp on main keyboard
{PgDn}PgDn on main keyboard
{CapsLock}CapsLock (using SetCapsLockState is more reliable). Sending {CapsLock} might require SetStoreCapsLockMode False beforehand.
{ScrollLock}ScrollLock (see also: SetScrollLockState)
{NumLock}NumLock (see also: SetNumLockState)
{Control} or {Ctrl}Ctrl (technical info: sends the neutral virtual key but the left scan code)
{LControl} or {LCtrl}Left Ctrl (technical info: sends the left virtual key rather than the neutral one)
{RControl} or {RCtrl}Right Ctrl
{Control down} or {Ctrl down}Holds Ctrl down until {Ctrl up} is sent. To hold down the left or right key instead, replace Ctrl with LCtrl or RCtrl.
{Alt}Alt (technical info: sends the neutral virtual key but the left scan code)
{LAlt}Left Alt (technical info: sends the left virtual key rather than the neutral one)
{RAlt}Right Alt (or AltGr, depending on keyboard layout)
{Alt down}Holds Alt down until {Alt up} is sent. To hold down the left or right key instead, replace Alt with LAlt or RAlt.
{Shift}Shift (technical info: sends the neutral virtual key but the left scan code)
{LShift}Left Shift (technical info: sends the left virtual key rather than the neutral one)
{RShift}Right Shift
{Shift down}Holds Shift down until {Shift up} is sent. To hold down the left or right key instead, replace Shift with LShift or RShift.
{LWin}Left Win
{RWin}Right Win
{LWin down}Holds the left Win down until {LWin up} is sent
{RWin down}Holds the right Win down until {RWin up} is sent
{AppsKey}Menu (invokes the right-click or context menu)
{Sleep}Sleep
{ASC nnnnn}

Sends an Alt+nnnnn keypad combination, which can be used to generate special characters that don't exist on the keyboard.

297 |

To generate printable ASCII characters or other characters from the system's OEM (DOS) code page, specify a number between 1 and 255. DllCall("GetOEMCP", "UInt") returns the current OEM code page number, such as 437 (United States) or 850 (Western Europe).

298 |

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}. DllCall("GetACP", "UInt") returns the current ANSI code page number, such as 1252 (United States, Western Europe, etc.).

299 |

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.

{U+nnnn}

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.

304 |

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.

{vkXX}
308 | {scYYY}
309 | {vkXXscYYY}

Sends a keystroke that has virtual key XX and scan code YYY. For example: Send "{vkFFsc159}". If the sc or vk portion is omitted, the most appropriate value is sent in its place.

311 |

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

312 |

Warning: Combining vk and sc in this manner is valid only with Send.

{Numpad0} - {Numpad9}Numpad digit keys (as seen when NumLock is ON). For example: {Numpad5} is 5.
{NumpadDot}. (numpad period) (as seen when NumLock is ON).
{NumpadEnter}Enter on keypad
{NumpadMult}* (numpad multiplication)
{NumpadDiv}/ (numpad division)
{NumpadAdd}+ (numpad addition)
{NumpadSub}- (numpad subtraction)
{NumpadDel}Del on keypad (this key and the following Numpad keys are used when NumLock is OFF)
{NumpadIns}Ins on keypad
{NumpadClear}Clear key on keypad (usually 5 when NumLock is OFF).
{NumpadUp}↑ (up arrow) on keypad
{NumpadDown}↓ (down arrow) on keypad
{NumpadLeft}← (left arrow) on keypad
{NumpadRight}→ (right arrow) on keypad
{NumpadHome}Home on keypad
{NumpadEnd}End on keypad
{NumpadPgUp}PgUp on keypad
{NumpadPgDn}PgDn on keypad
{Browser_Back}Select the browser "back" button
{Browser_Forward}Select the browser "forward" button
{Browser_Refresh}Select the browser "refresh" button
{Browser_Stop}Select the browser "stop" button
{Browser_Search}Select the browser "search" button
{Browser_Favorites}Select the browser "favorites" button
{Browser_Home}Launch the browser and go to the home page
{Volume_Mute}Mute/unmute the master volume. Usually equivalent to SoundSetMute -1.
{Volume_Down}Reduce the master volume. Usually equivalent to SoundSetVolume -5.
{Volume_Up}Increase the master volume. Usually equivalent to SoundSetVolume "+5".
{Media_Next}Select next track in media player
{Media_Prev}Select previous track in media player
{Media_Stop}Stop media player
{Media_Play_Pause}Play/pause media player
{Launch_Mail}Launch the email application
{Launch_Media}Launch media player
{Launch_App1}Launch user app1
{Launch_App2}Launch user app2
{PrintScreen}PrtSc
{CtrlBreak}Ctrl+Pause
{Pause}Pause
{Click [Options]}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).
{WheelDown}, {WheelUp}, {WheelLeft}, {WheelRight}, {LButton}, {RButton}, {MButton}, {XButton1}, {XButton2} 477 |

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.

478 |

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.

479 |
{Blind}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.
{Raw}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.
{Text}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.
494 | 495 |

Repeating or Holding Down a Key

496 |

To repeat a keystroke: Enclose in braces the name of the key followed by the number of times to repeat it. For example:

497 |
Send "{DEL 4}"  ; Presses the Delete key 4 times.
498 | Send "{S 30}"   ; Sends 30 uppercase S characters.
499 | Send "+{TAB 4}"  ; Presses Shift-Tab 4 times.
500 |

To hold down or release a key: Enclose in braces the name of the key followed by the word Down or Up. For example:

501 |
Send "{b down}{b up}"
502 | Send "{TAB down}{TAB up}"
503 | Send "{Up down}"  ; Presses down the up-arrow key.
504 | Sleep 1000  ; Keeps it down for one second.
505 | Send "{Up up}"  ; Releases the up-arrow key.
506 |

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:

507 |
Loop 20
508 | {
509 |     Send "{Tab down}"  ; Auto-repeat consists of consecutive down-events (with no up-events).
510 |     Sleep 30  ; The number of milliseconds between keystrokes (or use SetKeyDelay).
511 | }
512 | Send "{Tab up}"  ; Release the key.
513 |

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).

514 |

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.

515 |

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.

516 |

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 "µ".

517 | 518 |

General Remarks

519 |

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:

520 |
    521 |
  • SendEvent and SendInput use SendInput() with the KEYEVENTF_UNICODE flag.
  • 522 |
  • SendPlay uses the Alt+nnnnn method, which produces Unicode only if supported by the target application.
  • 523 |
  • ControlSend posts a WM_CHAR message.
  • 524 |
525 |

Note: Characters sent using any of the above methods usually do not trigger keyboard shortcuts or hotkeys.

526 |

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):

527 |
    528 |
  • If a naked letter is sent (that is, without modifiers or braces), or if Raw mode is in effect, it is sent as a character. For example, 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.
  • 529 |
  • If one or more modifier keys have been put into effect by the Send function, or if the letter is wrapped in braces, it is sent as a keycode (modified with Shift if the letter is upper-case). This allows the script to easily activate standard keyboard shortcuts. For example, ^c and {Ctrl down}c{Ctrl up} activate the standard Ctrl+C shortcut and {c} is equivalent to {vk43}.
  • 530 |
531 |

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.

532 |

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.

533 |

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.

534 |

When sending a large number of keystrokes, a continuation section can be used to improve readability and maintainability.

535 |

Since the operating system does not allow simulation of the Ctrl+Alt+Del combination, doing something like Send "^!{Delete}" will have no effect.

536 |

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.

537 | 538 |

SendInput

539 |

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.

540 |

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.

541 |

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.

542 |

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.

543 |

If a script other than the one executing SendInput has a low-level keyboard hook installed, SendInput automatically reverts to SendEvent (or SendPlay if SendMode "InputThenPlay" is in effect). This is done because the presence of an external hook disables all of SendInput's advantages, making it inferior to both SendPlay and SendEvent. However, since SendInput is unable to detect a low-level hook in programs other than AutoHotkey v1.0.43+, it will not revert in these cases, making it less reliable than SendPlay/Event.

544 |

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.

545 | 546 |

SendPlay

547 |

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).

548 |

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.

549 |

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.

550 |

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.

551 |

Although SendPlay is considerably slower than SendInput, it is usually faster than the traditional SendEvent mode (even when KeyDelay is -1).

552 |

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).

553 |

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:

554 |
SetKeyDelay 0, 10, "Play"  ; Note that both 0 and -1 are the same in SendPlay mode.
555 | SetMouseDelay 10, "Play"
556 |

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.

557 |

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.

558 |

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.

559 | 560 |

Related

561 |

SendMode, SetKeyDelay, SetStoreCapsLockMode, Escape sequences (e.g. `n), ControlSend, BlockInput, Hotstrings, WinActivate

562 | 563 |

Examples

564 |
565 |

Types a two-line signature.

566 |
Send "Sincerely,{enter}John Smith"
567 |
568 | 569 |
570 |

Selects the File->Save menu (Alt+F followed by S).

571 |
Send "!fs"
572 |
573 | 574 |
575 |

Jumps to the end of the text then send four shift+left-arrow keystrokes.

576 |
Send "{End}+{Left 4}"
577 |
578 | 579 |
580 |

Sends a long series of raw characters via the fastest method.

581 |
SendInput "{Raw}A long series of raw characters sent via the fastest method."
582 |
583 | 584 |
585 |

Holds down a key contained in a variable.

586 |
MyKey := "Shift"
587 | Send "{" MyKey " down}"  ; Holds down the Shift key.
588 | 
589 |
590 | 591 | 592 | 593 | -------------------------------------------------------------------------------- /docs/lib/SendLevel.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SendLevel - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

SendLevel

14 |

Controls which artificial keyboard and mouse events are ignored by hotkeys and hotstrings.

15 |
SendLevel Level
16 | 17 |

Parameters

18 |
19 | 20 |
Level
21 |
22 |

Type: Integer

23 |

An integer between 0 and 100.

24 |
25 | 26 |
27 | 28 |

Return Value

29 |

Type: Integer

30 |

This function returns the previous setting; an integer between 0 and 100.

31 | 32 |

General Remarks

33 |

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 |
    38 |
  • SendPlay is not affected by SendLevel.
  • 39 |
  • SendInput is affected by SendLevel, but the script's own hook hotkeys cannot be activated while a SendInput is in progress, since it temporarily deactivates the hook. However, when Send or SendInput reverts to SendEvent, it is able to activate the script's own hotkeys.
  • 40 |
  • Hotkeys using the "reg" method are incapable of distinguishing physical and artificial input, so are not affected by SendLevel. However, hotkeys above level 0 always use the keyboard or mouse hook.
  • 41 |
  • Hotstrings use #InputLevel only to determine whether the last typed character should trigger a hotstring. For instance, the hotstring ::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.
  • 42 |
  • Auto-replace hotstrings always generate keystrokes at level 0, since it is usually undesirable for the replacement text to trigger another hotstring or hotkey. To work around this, use a non-auto-replace hotstring and the SendEvent function.
  • 43 |
  • Characters sent by the ASC (Alt+nnnnn) method cannot trigger a hotstring, even if SendLevel is used.
  • 44 |
  • Characters sent by SendEvent with the {Text} mode, {U+nnnn} or Unicode fallback method can trigger hotstrings.
  • 45 |
46 |

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.

50 | 51 |

Related

52 |

#InputLevel, Send, Click, MouseClick, MouseClickDrag

53 | 54 |

Examples

55 |
56 |

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 |
65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /docs/lib/SendMessage.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SendMessage - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

SendMessage

15 | 16 |

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 |

Parameters

20 |
21 | 22 |
MsgNumber
23 |
24 |

Type: Integer

25 |

The message number to send. See the message list to determine the number.

26 |
27 | 28 |
wParam, lParam
29 |
30 |

Type: Integer or Object

31 |

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 |
35 | 36 |
Control
37 |
38 |

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.

40 |

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 |
42 | 43 |
WinTitle, WinText, ExcludeTitle, ExcludeText
44 |
45 |

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 |
50 | 51 |
Timeout
52 |
53 |

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 |
56 | 57 |
58 | 59 |

Return Value

60 |

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 >> 32
65 |

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 |

Error Handling

68 |

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 |

Remarks

73 |

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_SETTEXT
79 |

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:

80 |
SendMessage 0x001A,,,, 0xFFFF  ; 0x001A is WM_SETTINGCHANGE
81 |

To have a script receive a message, use OnMessage.

82 |

See the Message Tutorial for an introduction to using this function.

83 | 84 |

Related

85 |

PostMessage, Message List, Message Tutorial, OnMessage, Automating Winamp, DllCall, ControlSend, MenuSelect

86 | 87 |

Examples

88 | 89 |
90 |

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 |
98 | 99 |
100 |

Starts the user's chosen screen saver.

101 |
SendMessage 0x0112, 0xF140, 0,, "Program Manager"  ; 0x0112 is WM_SYSCOMMAND, and 0xF140 is SC_SCREENSAVE.
102 |
103 | 104 |
105 |

Scrolls up by one line (for a control that has a vertical scroll bar).

106 |
SendMessage 0x0115, 0, 0, ControlGetFocus("A")
107 |
108 | 109 |
110 |

Scrolls down by one line (for a control that has a vertical scroll bar).

111 |
SendMessage 0x0115, 1, 0, ControlGetFocus("A")
112 |
113 | 114 |
115 |

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 |
122 | 123 |
124 |

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 |
130 | 131 | 132 | 133 | -------------------------------------------------------------------------------- /docs/lib/SendMode.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SendMode - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

SendMode

14 | 15 |

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 |

Parameters

20 |
21 |
Mode
22 |
23 |

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 |
    28 |
  • Windows Explorer ignores SendInput's simulation of certain navigational hotkeys such as Alt+←. To work around this, use either SendEvent "!{Left}" or SendInput "{Backspace}".
  • 29 |
30 |

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 |
    33 |
  • Characters that do not exist in the current keyboard layout (such as Ô in English) cannot be sent. To work around this, use SendEvent.
  • 34 |
  • Simulated mouse dragging might have no effect in RichEdit controls (and possibly others) such as those of WordPad and Metapad. To use an alternate mode for a particular drag, follow this example: SendEvent "{Click 6 52 Down}{Click 45 52 Up}".
  • 35 |
  • Simulated mouse wheel rotation produces movement in only one direction (usually downward, but upward in some applications). Also, wheel rotation might have no effect in applications such as MS Word and Notepad. To use an alternate mode for a particular rotation, follow this example: SendEvent "{WheelDown 5}".
  • 36 |
  • If 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.
  • 37 |
  • SendPlay does not trigger AutoHotkey's hotkeys or hotstrings, or global hotkeys registered by other programs or the OS.
  • 38 |
39 |
40 |
41 | 42 |

Return Value

43 |

Type: String

44 |

This function returns the previous setting; either Event, Input, InputThenPlay or Play.

45 | 46 |

Remarks

47 |

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.

51 |

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 |

Related

54 |

Send, SetKeyDelay, SetMouseDelay, Click, MouseClick, MouseClickDrag, MouseMove

55 |

Examples

56 |
57 |

Makes Send synonymous with SendInput, but falls back to SendPlay if SendInput is not available.

58 |
SendMode "InputThenPlay"
59 |
60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /docs/lib/SetControlDelay.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SetControlDelay - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

SetControlDelay

14 | 15 |

Sets the delay that will occur after each control-modifying function.

16 | 17 |
SetControlDelay Delay
18 |

Parameters

19 |
20 | 21 |
Delay
22 |
23 |

Type: Integer

24 |

Time in milliseconds. Specify -1 for no delay at all or 0 for the smallest possible delay.

25 |
26 | 27 |
28 | 29 |

Return Value

30 |

Type: Integer

31 |

This function returns the previous setting.

32 | 33 |

Remarks

34 |

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 |

Related

44 |

Control functions, SetWinDelay, SetKeyDelay, SetMouseDelay

45 |

Examples

46 |
47 |

Causes the smallest possible delay to occur after each control-modifying function.

48 |
SetControlDelay 0
49 |
50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /docs/lib/SetDefaultMouseSpeed.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SetDefaultMouseSpeed - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

SetDefaultMouseSpeed

14 | 15 |

Sets the mouse speed that will be used if unspecified in Click, MouseMove, MouseClick, and MouseClickDrag.

16 | 17 |
SetDefaultMouseSpeed Speed
18 |

Parameters

19 |
20 | 21 |
Speed
22 |
23 |

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 |
26 | 27 |
28 | 29 |

Return Value

30 |

Type: Integer

31 |

This function returns the previous setting.

32 | 33 |

Remarks

34 |

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).

36 |

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 |

Related

41 |

SetMouseDelay, SendMode, Click, MouseClick, MouseMove, MouseClickDrag, SetWinDelay, SetControlDelay, SetKeyDelay, SetKeyDelay

42 |

Examples

43 |
44 |

Causes the mouse cursor to be moved instantly.

45 |
SetDefaultMouseSpeed 0
46 |
47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /docs/lib/SetKeyDelay.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SetKeyDelay - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

SetKeyDelay

14 | 15 |

Sets the delay that will occur after each keystroke sent by Send or ControlSend.

16 | 17 |
SetKeyDelay Delay, PressDuration, "Play"
18 |

Parameters

19 |
20 | 21 |
Delay
22 |
23 |

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 |
26 | 27 |
PressDuration
28 |
29 |

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 |
34 | 35 |
Play
36 |
37 |

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 |
40 | 41 |
42 | 43 |

Remarks

44 |

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.

51 |

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 |

Related

54 |

Send, ControlSend, SendMode, SetMouseDelay, SetControlDelay, SetWinDelay, Click

55 |

Examples

56 |
57 |

Causes the smallest possible delay to occur after each keystroke sent via Send or ControlSend.

58 |
SetKeyDelay 0
59 |
60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /docs/lib/SetMouseDelay.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SetMouseDelay - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

SetMouseDelay

14 | 15 |

Sets the delay that will occur after each mouse movement or click.

16 | 17 |
SetMouseDelay Delay , "Play"
18 |

Parameters

19 |
20 | 21 |
Delay
22 |
23 |

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 |
26 | 27 |
Play
28 |
29 |

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 |
32 | 33 |
34 | 35 |

Return Value

36 |

Type: Integer

37 |

This function returns the previous setting.

38 | 39 |

Remarks

40 |

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 |

Related

47 |

SetDefaultMouseSpeed, Click, MouseMove, MouseClick, MouseClickDrag, SendMode, SetKeyDelay, SetControlDelay, SetWinDelay

48 |

Examples

49 |
50 |

Causes the smallest possible delay to occur after each mouse movement or click.

51 |
SetMouseDelay 0
52 |
53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /docs/lib/SetNumScrollCapsLockState.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SetCapsLockState / SetNumLockState / SetScrollLockState - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

SetCapsLockState / SetNumLockState / SetScrollLockState

14 | 15 |

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 State
20 |

Parameters

21 |
22 | 23 |
State
24 |
25 |

Type: String or Integer

26 |

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 |
32 | 33 |
34 | 35 |

Remarks

36 |

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.

37 |

Keeping a key AlwaysOn or AlwaysOff requires the keyboard hook, which will be automatically installed in such cases.

38 |

Related

39 |

SetStoreCapsLockMode, GetKeyState

40 |

Examples

41 | 42 |
43 |

Turns on NumLock and removes the AlwaysOn/Off attribute of the key (if present).

44 |
SetNumLockState True
45 |
46 | 47 |
48 |

Forces ScrollLock to stay off permanently.

49 |
SetScrollLockState "AlwaysOff"
50 |
51 | 52 |
53 |

Toggles CapsLock to its opposite state.

54 |
SetCapsLockState !GetKeyState("CapsLock", "T")
55 |
56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /docs/lib/SetRegView.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SetRegView - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

SetRegView

14 |

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 |

Parameters

18 |
19 | 20 |
RegView
21 |
22 |

Type: Integer or String

23 |

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 |
26 | 27 |
28 | 29 |

Return Value

30 |

Type: String

31 |

This function returns the previous setting; either 32, 64 or Default.

32 | 33 |

Remarks

34 |

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.

37 | 38 |

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 |

Related

42 |

RegRead, RegWrite, RegCreateKey, RegDelete, RegDeleteKey, Loop Reg

43 | 44 |

Examples

45 |
46 |

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 |
65 | 66 |
67 |

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 |
80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /docs/lib/SetStoreCapsLockMode.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SetStoreCapsLockMode - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

SetStoreCapsLockMode

14 | 15 |

Whether to restore the state of CapsLock after a Send.

16 | 17 |
SetStoreCapsLockMode Mode
18 |

Parameters

19 |
20 | 21 |
Mode
22 |
23 |

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 |
27 | 28 |
29 | 30 |

Return Value

31 |

Type: Integer (boolean)

32 |

This function returns the previous setting; either 0 (false) or 1 (true).

33 | 34 |

Remarks

35 |

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 |

Related

42 |

SetCaps/Num/ScrollLockState, Send, ControlSend

43 | 44 |

Examples

45 |
46 |

Causes the state of CapsLock not to be changed at all.

47 |
SetStoreCapsLockMode False
48 |
49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /docs/lib/SetTimer.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SetTimer - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

SetTimer

14 | 15 |

Causes a function to be called automatically and repeatedly at a specified time interval.

16 | 17 |
SetTimer Function, Period, Priority
18 |

Parameters

19 |
20 | 21 |
Function
22 |
23 |

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.

27 |

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 |
29 | 30 |
Period
31 |
32 |

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 |
    35 |
  • If Period is greater than 0, the timer will automatically repeat until it is explicitly disabled by the script.
  • 36 |
  • If Period is less than 0, the timer will run only once. For example, specifying -100 would call Function 100 ms from now then delete the timer as though SetTimer Function, 0 had been used.
  • 37 |
  • If Period is 0, the timer is marked for deletion. If a thread started by this timer is still running, the timer is deleted after the thread finishes (unless it has been reenabled); otherwise, it is deleted immediately. In any case, the timer's previous Period and Priority are not retained.
  • 38 |
39 |

The absolute value of Period must be no larger than 4294967295 ms (49.7 days).

40 |
41 | 42 |
Priority
43 |
44 |

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 |
48 | 49 |
50 | 51 |

Remarks

52 |

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 |
    59 |
  1. Other applications are putting a heavy load on the CPU.
  2. 60 |
  3. The timer's function is still running when the timer period expires again.
  4. 61 |
  5. There are too many other competing timers.
  6. 62 |
  7. The timer has been interrupted by another thread, namely another timed function, hotkey subroutine, or custom menu item (this can be avoided via Critical). If this happens and the interrupting thread takes a long time to finish, the interrupted timer will be effectively disabled for the duration. However, any other timers will continue to run by interrupting the thread that interrupted the first timer.
  8. 63 |
  9. The script is uninterruptible as a result of Critical or Thread Interrupt/Priority. During such times, timers will not run. Later, when the script becomes interruptible again, any overdue timer will run once as soon as possible and then resume its normal schedule.
  10. 64 |
65 |

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 |

Related

75 |

Threads, Thread (function), Critical, Function Objects

76 | 77 |

Examples

78 |
79 |

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 |
88 | 89 |
90 |

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 |
102 | 103 |
104 |

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 |
140 | 141 |
142 |

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 |
    175 |
  • We can also use 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().
  • 176 |
  • If we rename Tick to Call, we can just use 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.
  • 177 |
  • If the timer is being modified or deleted from within a function/method called by the timer, it may be easier to omit the Function parameter. In some cases this avoids the need to retain the original object which was passed to SetTimer.
  • 178 |
179 |
180 | 181 | 182 | 183 | -------------------------------------------------------------------------------- /docs/lib/SetTitleMatchMode.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SetTitleMatchMode - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

SetTitleMatchMode

14 | 15 |

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 |

Parameters

22 |
23 | 24 |
MatchMode
25 |
26 |

Type: Integer or String

27 |

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.

32 |

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 |
35 | 36 |
Speed
37 |
38 |

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 |
43 | 44 |
45 | 46 |

Return Value

47 |

Type: Integer or String

48 |

This function returns the previous value of whichever setting was changed (either A_TitleMatchMode or A_TitleMatchModeSpeed).

49 | 50 |

Remarks

51 |

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".

61 |

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 |

Related

63 |

The WinTitle Parameter, SetWinDelay, WinExist, WinActivate, RegExMatch

64 |

Examples

65 |
66 |

Forces windowing functions to operate upon windows whose titles contain WinTitle at the beginning instead of anywhere.

67 |
SetTitleMatchMode 1
68 |
69 | 70 |
71 |

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 |
74 | 75 |
76 |

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 |
82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /docs/lib/SetWinDelay.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SetWinDelay - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

SetWinDelay

14 | 15 |

Sets the delay that will occur after each windowing function, such as WinActivate.

16 | 17 |
SetWinDelay Delay
18 |

Parameters

19 |
20 | 21 |
Delay
22 |
23 |

Type: Integer

24 |

Time in milliseconds. Specify -1 for no delay at all or 0 for the smallest possible delay.

25 |
26 | 27 |
28 | 29 |

Return Value

30 |

Type: Integer

31 |

This function returns the previous setting.

32 | 33 |

Remarks

34 |

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 |

Related

42 |

SetControlDelay, SetKeyDelay, SetMouseDelay, SendMode

43 |

Examples

44 |
45 |

Causes a delay of 10 ms to occur after each windowing function.

46 |
SetWinDelay 10
47 |
48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /docs/lib/SetWorkingDir.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SetWorkingDir - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

SetWorkingDir

14 | 15 |

Changes the script's current working directory.

16 | 17 |
SetWorkingDir DirName
18 |

Parameters

19 |
20 | 21 |
DirName
22 |
23 |

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 |
26 | 27 |
28 | 29 |

Error Handling

30 |

An OSError is thrown on failure.

31 | 32 |

Remarks

33 |

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".

34 |

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 |

Related

37 |

A_WorkingDir, A_InitialWorkingDir, A_ScriptDir, DirSelect

38 |

Examples

39 |
40 |

Changes the script's current working directory.

41 |
SetWorkingDir "D:\My Folder\Temp"
42 |
43 | 44 |
45 |

Forces the script to use the folder it was initially launched from as its working directory.

46 |
SetWorkingDir A_InitialWorkingDir
47 |
48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /docs/lib/Shutdown.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Shutdown - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Shutdown

14 | 15 |

Shuts down, restarts, or logs off the system.

16 | 17 |
Shutdown Flag
18 |

Parameters

19 |
20 | 21 |
Flag
22 |
23 |

Type: Integer

24 |

A combination (sum) of the following numbers:

25 |
    26 |
  • 0 = Logoff
  • 27 |
  • 1 = Shutdown
  • 28 |
  • 2 = Reboot
  • 29 |
  • 4 = Force
  • 30 |
  • 8 = Power down
  • 31 |
32 |

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 |
36 | 37 |
38 | 39 |

Remarks

40 |

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 |

Related

44 |

Run, ExitApp, OnExit

45 |

Examples

46 |
47 |

Forces a reboot (reboot + force = 2 + 4 = 6).

48 |
Shutdown 6
49 |
50 | 51 |
52 |

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 |
58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /docs/lib/Sleep.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Sleep - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Sleep

14 | 15 |

Waits the specified amount of time before continuing.

16 | 17 |
Sleep Delay
18 |

Parameters

19 |
20 | 21 |
Delay
22 |
23 |

Type: Integer

24 |

The amount of time to pause (in milliseconds) between 0 and 2147483647 (24 days).

25 |
26 | 27 |
28 | 29 |

Remarks

30 |

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 |

Related

36 |

SetKeyDelay, SetMouseDelay, SetControlDelay, SetWinDelay

37 |

Examples

38 |
39 |

Waits 1 second before continuing execution.

40 |
Sleep 1000
41 |
42 | 43 |
44 |

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 |
48 | 49 |
50 |

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) / Iterations
66 |
67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /docs/lib/Sort.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Sort - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Sort

14 | 15 |

Arranges a variable's contents in alphabetical, numerical, or random order (optionally removing duplicates).

16 | 17 |
SortedString := Sort(String , Options, Callback)
18 |

Parameters

19 |
20 | 21 |
String
22 |
23 |

Type: String

24 |

The string to sort.

25 |
26 | 27 |
Options
28 |
29 |

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 |
32 | 33 |
Callback
34 |
35 |

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 |
    41 |
  1. The first item.
  2. 42 |
  3. The second item.
  4. 43 |
  5. The offset (in characters) of the second item from the first as seen in the original/unsorted list (see examples).
  6. 44 |
45 |

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, *).

46 |

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 |
50 | 51 |
52 | 53 |

Return Value

54 |

Type: String

55 |

This function returns the sorted version of the specified string.

56 | 57 |

Options

58 |

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.

63 |

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.

70 |

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).

71 |

\: 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.txt
74 |

Note: Options N and P are ignored when the \ (backslash) option is present.

75 | 76 |

Remarks

77 |

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 := "".

79 | 80 |

Related

81 |

FileRead, File-reading loop, Parsing loop, StrSplit, CallbackCreate, A_Clipboard

82 | 83 |

Examples

84 |
85 |

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,999
89 |
90 | 91 |
92 |

Sorts the contents of a file.

93 |
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 |
98 | 99 |
100 |

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 |
110 | 111 |
112 |

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 |
140 | 141 | 142 | 143 | -------------------------------------------------------------------------------- /docs/lib/Sound.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Sound Functions | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Sound Functions

15 | 16 |

Applies to:

17 |
    18 |
  • SoundGetVolume / SoundSetVolume
  • 19 |
  • SoundGetMute / SoundSetMute
  • 20 |
  • SoundGetName
  • 21 |
  • SoundGetInterface
  • 22 |
23 |

Other sound-related functions:

24 |
    25 |
  • SoundBeep
  • 26 |
  • SoundPlay
  • 27 |
28 | 29 |

Endpoint Devices

30 |

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 | 32 | 33 | 34 | 35 | 36 | 37 |
NameDescription
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.
38 |

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.

40 | 41 |

Components

42 |

Components are as shown on the Levels tab of the sound device's properties dialog.

43 | Levels 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 |

Advanced Details

49 |

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 |

Common Parameters

55 |
56 | 57 |
Component
58 |
59 |

Type: String or Integer

60 |

One of the following:

61 |
    62 |
  • The index of a component, where 1 is the first component.
  • 63 |
  • The full display name of a component (case-insensitive).
  • 64 |
  • As above, but followed by a colon and integer, where 1 is the first occurrence of a component with that name. For example, "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.
  • 65 |
  • If blank or omitted, the function targets the master volume/mute controls or an interface that can be returned by IMMDevice::Activate.
  • 66 |
67 |

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.

68 |

If the sound device lacks the specified Component, a TargetError is thrown.

69 |
70 | 71 |
Device
72 |
73 |

Type: String or Integer

74 |

One of the following:

75 |
    76 |
  • A number (integer) between 1 and the total number of supported devices.
  • 77 |
  • The display name of a device; either the full name or a leading part (case-insensitive). For example, "Speakers" or "Speakers (Example HD Audio)".
  • 78 |
  • As above, but followed by a colon and integer, where 1 is the first device with a matching name. For example, "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.
  • 79 |
  • If blank or omitted, it defaults to the system's default device for playback (which is not necessarily device 1).
  • 80 |
81 |

The soundcard analysis script may help determine which name and/or number to use.

82 |
83 | 84 |
85 | 86 |

Examples

87 |
88 |

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 |
149 | 150 | 151 | 152 | -------------------------------------------------------------------------------- /docs/lib/SoundBeep.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SoundBeep - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

SoundBeep

14 | 15 |

Emits a tone from the PC speaker.

16 | 17 |
SoundBeep Frequency, Duration
18 |

Parameters

19 |
20 | 21 |
Frequency
22 |
23 |

Type: Integer

24 |

If omitted, it defaults to 523. Otherwise, specify the frequency of the sound, a number between 37 and 32767.

25 |
26 | 27 |
Duration
28 |
29 |

Type: Integer

30 |

If omitted, it defaults to 150. Otherwise, specify the duration of the sound, in milliseconds.

31 |
32 | 33 |
34 | 35 |

Remarks

36 |

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 |

Related

40 |

SoundPlay

41 |

Examples

42 |
43 |

Plays the default pitch and duration.

44 |
SoundBeep
45 |
46 | 47 |
48 |

Plays a higher pitch for half a second.

49 |
SoundBeep 750, 500
50 |
51 | 52 | 53 | -------------------------------------------------------------------------------- /docs/lib/SoundGetInterface.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SoundGetInterface - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

SoundGetInterface

15 | 16 |

Retrieves a native COM interface of a sound device or component.

17 | 18 |
InterfacePtr := SoundGetInterface(IID, Component, Device)
19 |

Parameters

20 |
21 | 22 |
IID
23 |
24 |

Type: String

25 |

An interface identifier (GUID) in the form "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}".

26 |
27 | 28 |
Component
29 |
30 |

Type: String or Integer

31 |

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".

32 |

For further details, see Component (Sound Functions).

33 |
34 | 35 |
Device
36 |
37 |

Type: String or Integer

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)".

39 |

For further details, see Device (Sound Functions).

40 |
41 | 42 |
43 | 44 |

Return Value

45 |

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 |

Error Handling

50 |

A TargetError is thrown if the device or component could not be found. Otherwise, an OSError is thrown on failure.

51 | 52 |

Remarks

53 |

The interface is retrieved from one of the following sources:

54 |
    55 |
  • If Component is omitted, IMMDevice::Activate is called to retrieve the interface.
  • 56 |
  • QueryInterface is called for the Connector identified by Component, and if successful, the interface pointer is returned. This can be used to retrieve the IPart or IConnector interface of the Connector.
  • 57 |
  • IPart::Activate is called for each Subunit unique to the given Component. For example, IID can be "{7FB7B48F-531D-44A2-BCB3-5AD5A134B3DC}" to retrieve the IAudioVolumeLevel interface, which provides access to per-channel volume level controls.
  • 58 |
59 |

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 |

Related

64 |

Sound Functions, DeviceTopology API

65 | 66 |

Examples

67 |
68 |

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 |
86 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /docs/lib/SoundGetMute.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SoundGetMute - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

SoundGetMute

15 | 16 |

Retrieves a mute setting of a sound device.

17 | 18 |
Setting := SoundGetMute(Component, Device)
19 |

Parameters

20 |
21 | 22 |
Component
23 |
24 |

Type: String or Integer

25 |

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".

26 |

For further details, see Component (Sound Functions).

27 |
28 | 29 |
Device
30 |
31 |

Type: String or Integer

32 |

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)".

33 |

For further details, see Device (Sound Functions).

34 |
35 | 36 |
37 | 38 |

Return Value

39 |

Type: Integer (boolean)

40 |

This function returns 0 (false) for unmuted or 1 (true) for muted.

41 | 42 |

Error Handling

43 |

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 |

Remarks

46 |

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 |

Related

49 |

Sound Functions

50 | 51 |

Examples

52 |
53 |

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 |
60 | 61 |
62 |

Checks whether "Line In pass-through" is muted.

63 |
if SoundGetMute("Line In") = 0
64 |     MsgBox "Line In pass-through is not muted."
65 |
66 | 67 |
68 |

Checks whether the microphone (recording) is muted.

69 |
if SoundGetMute( , "Microphone") = 0
70 |     MsgBox "The microphone (recording) is not muted."
71 |
72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /docs/lib/SoundGetName.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SoundGetName - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

SoundGetName

15 | 16 |

Retrieves the name of a sound device or component.

17 | 18 |
Name := SoundGetName(Component, Device)
19 |

Parameters

20 |
21 | 22 |
Component
23 |
24 |

Type: String or Integer

25 |

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".

26 |

For further details, see Component (Sound Functions).

27 |
28 | 29 |
Device
30 |
31 |

Type: String or Integer

32 |

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)".

33 |

For further details, see Device (Sound Functions).

34 |
35 | 36 |
37 | 38 |

Return Value

39 |

Type: String

40 |

This function returns the name of the device or component, which can be empty.

41 | 42 |

Error Handling

43 |

A TargetError is thrown if the device or component could not be found. Otherwise, an OSError is thrown on failure.

44 | 45 |

Related

46 |

Sound Functions

47 | 48 |

Examples

49 |
50 |

Retrieves and reports the name of the default playback device.

51 |
default_device := SoundGetName()
52 | MsgBox "The default playback device is " default_device
53 |
54 | 55 |
56 |

Retrieves and reports the name of the first device.

57 |
device1 := SoundGetName( , 1)
58 | MsgBox "Device 1 is " device1
59 |
60 | 61 |
62 |

Retrieves and reports the name of the first component.

63 |
component1 := SoundGetName(1)
64 | MsgBox "Component 1 is " component1
65 |
66 | 67 |

For a more complex example, see the soundcard analysis script.

68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /docs/lib/SoundGetVolume.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SoundGetVolume - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

SoundGetVolume

15 | 16 |

Retrieves a volume setting of a sound device.

17 | 18 |
Setting := SoundGetVolume(Component, Device)
19 |

Parameters

20 |
21 | 22 |
Component
23 |
24 |

Type: String or Integer

25 |

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".

26 |

For further details, see Component (Sound Functions).

27 |
28 | 29 |
Device
30 |
31 |

Type: String or Integer

32 |

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)".

33 |

For further details, see Device (Sound Functions).

34 |
35 | 36 |
37 | 38 |

Return Value

39 |

Type: Float

40 |

This function returns a floating point number between 0.0 and 100.0.

41 | 42 |

Error Handling

43 |

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 |

Remarks

46 |

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 |

Related

49 |

Sound Functions

50 | 51 |

Examples

52 |
53 |

Retrieves and reports the master volume.

54 |
master_volume := SoundGetVolume()
55 | MsgBox "Master volume is " master_volume " percent."
56 |
57 | 58 |
59 |

Retrieves and reports the microphone listening volume.

60 |
mic_volume := SoundGetVolume("Microphone")
61 | MsgBox "Microphone listening volume is " mic_volume " percent."
62 |
63 | 64 |
65 |

Retrieves and reports the microphone recording volume.

66 |
mic_volume := SoundGetVolume( , "Microphone")
67 | MsgBox "Microphone recording volume is " mic_volume " percent."
68 |
69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /docs/lib/SoundPlay.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SoundPlay - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

SoundPlay

14 | 15 |

Plays a sound, video, or other supported file type.

16 | 17 |
SoundPlay Filename , Wait
18 |

Parameters

19 |
20 | 21 |
Filename
22 |
23 |

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 |
    27 |
  • *-1 = Simple beep. If the sound card is not available, the sound is generated using the speaker.
  • 28 |
  • *16 = Hand (stop/error)
  • 29 |
  • *32 = Question
  • 30 |
  • *48 = Exclamation
  • 31 |
  • *64 = Asterisk (info)
  • 32 |
33 |
34 | 35 |
Wait
36 |
37 |

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 |
43 | 44 |
45 | 46 |

Error Handling

47 |

An exception is thrown on failure.

48 | 49 |

Remarks

50 |

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".

54 |

If the script is exited, any currently-playing file that it started will stop.

55 |

Related

56 |

SoundBeep, Sound Functions, MsgBox, Threads

57 |

Examples

58 |
59 |

Plays a .wav file located in the Windows directory.

60 |
SoundPlay A_WinDir "\Media\ding.wav"
61 |
62 | 63 |
64 |

Generates a simple beep.

65 |
SoundPlay "*-1"
66 |
67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /docs/lib/SoundSetMute.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SoundSetMute - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

SoundSetMute

15 | 16 |

Changes a mute setting of a sound device.

17 | 18 |
SoundSetMute NewSetting , Component, Device
19 |

Parameters

20 |
21 | 22 |
NewSetting
23 |
24 |

Type: Integer

25 |

One of the following values:

26 |
    27 |
  • 1 or True turns on the setting
  • 28 |
  • 0 or False turns off the setting
  • 29 |
  • -1 toggles the setting (sets it to the opposite of its current state)
  • 30 |
31 |
32 | 33 |
Component
34 |
35 |

Type: String or Integer

36 |

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".

37 |

For further details, see Component (Sound Functions).

38 |
39 | 40 |
Device
41 |
42 |

Type: String or Integer

43 |

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)".

44 |

For further details, see Device (Sound Functions).

45 |
46 | 47 |
48 | 49 |

Error Handling

50 |

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 |

Remarks

53 |

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 |

Related

59 |

Sound Functions

60 | 61 |

Examples

62 |
63 |

Turns on the master mute.

64 |
SoundSetMute true
65 |
66 | 67 |
68 |

Turns off the master mute.

69 |
SoundSetMute false
70 |
71 | 72 |
73 |

Toggles the master mute (sets it to the opposite of its current state).

74 |
SoundSetMute -1
75 |
76 | 77 |
78 |

Mutes Line In.

79 |
SoundSetMute true, "Line In"
80 |
81 | 82 |
83 |

Mutes microphone recording.

84 |
SoundSetMute true,, "Microphone"
85 |
86 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /docs/lib/SoundSetVolume.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SoundSetVolume - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

SoundSetVolume

15 | 16 |

Changes a volume setting of a sound device.

17 | 18 |
SoundSetVolume NewSetting , Component, Device
19 |

Parameters

20 |
21 | 22 |
NewSetting
23 |
24 |

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 |
28 | 29 |
Component
30 |
31 |

Type: String or Integer

32 |

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".

33 |

For further details, see Component (Sound Functions).

34 |
35 | 36 |
Device
37 |
38 |

Type: String or Integer

39 |

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)".

40 |

For further details, see Device (Sound Functions).

41 |
42 | 43 |
44 | 45 |

Error Handling

46 |

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 |

Remarks

49 |

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 |

Related

58 |

Sound Functions

59 | 60 |

Examples

61 |
62 |

Sets the master volume to 50 percent. Quotation marks can be omitted.

63 |
SoundSetVolume "50"
64 |
SoundSetVolume 50
65 |
66 | 67 |
68 |

Increases the master volume by 10 percent. Quotation marks cannot be omitted.

69 |
SoundSetVolume "+10"
70 |
71 | 72 |
73 |

Decreases the master volume by 10 percent. Quotation marks can be omitted.

74 |
SoundSetVolume "-10"
75 |
SoundSetVolume -10
76 |
77 | 78 |
79 |

Increases microphone recording volume by 20 percent.

80 |
SoundSetVolume "+20", , "Microphone"
81 |
82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /docs/lib/SplitPath.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SplitPath - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

SplitPath

14 | 15 |

Separates a file name or URL into its name, directory, extension, and drive.

16 | 17 |
SplitPath Path , &OutFileName, &OutDir, &OutExtension, &OutNameNoExt, &OutDrive
18 |

Parameters

19 |
20 | 21 |
Path
22 |
23 |

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 |
27 | 28 |
&OutFileName
29 |
30 |

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 |
33 | 34 |
&OutDir
35 |
36 |

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 |
39 | 40 |
&OutExtension
41 |
42 |

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 |
45 | 46 |
&OutNameNoExt
47 |
48 |

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 |
51 | 52 |
&OutDrive
53 |
54 |

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 |
57 | 58 |
59 | 60 |

Remarks

61 |

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.

66 |

Related

67 |

A_LoopFileExt, StrSplit, InStr, SubStr, FileSelect, DirSelect

68 |

Examples

69 |
70 |

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 |
89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /docs/lib/StatusBarGetText.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | StatusbarGetText - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

StatusBarGetText

14 | 15 |

Retrieves the text from a standard status bar control.

16 | 17 |
Text := StatusBarGetText(Part#, WinTitle, WinText, ExcludeTitle, ExcludeText)
18 |

Parameters

19 |
20 | 21 |
Part#
22 |
23 |

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 |
26 | 27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 | 35 |
36 | 37 |

Return Value

38 |

Type: String

39 |

This function returns the text from a single part of the status bar control.

40 | 41 |

Error Handling

42 |

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 |

Remarks

46 |

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 |

Related

50 |

StatusBarWait, WinGetTitle, WinGetText, ControlGetText

51 |

Examples

52 |
53 |

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 |
58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /docs/lib/StatusBarWait.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | StatusBarWait - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

StatusBarWait

14 | 15 |

Waits until a window's status bar contains the specified string.

16 | 17 |
StatusBarWait BarText, Timeout, Part#, WinTitle, WinText, Interval, ExcludeTitle, ExcludeText
18 |

Parameters

19 |
20 | 21 |
BarText
22 |
23 |

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 |
27 | 28 |
Timeout
29 |
30 |

Type: Integer or Float

31 |

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 |
33 | 34 |
Part#
35 |
36 |

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 |
39 | 40 |
WinTitle, WinText, ExcludeTitle, ExcludeText
41 |
42 |

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 |
47 | 48 |
Interval
49 |
50 |

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 |
53 | 54 |
55 | 56 |

Return Value

57 |

Type: Integer (boolean)

58 |

This function returns 1 (true) if a match was found or 0 (false) if the function timed out.

59 | 60 |

Error Handling

61 |

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 |

Remarks

65 |

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 |

Related

71 |

StatusBarGetText, WinGetTitle, WinGetText, ControlGetText

72 |

Examples

73 |
74 |

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 |
86 | 87 |
88 |

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 |
96 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /docs/lib/StrCompare.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | StrCompare - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

StrCompare

15 |

Compares two strings alphabetically.

16 |
Result := StrCompare(String1, String2 , CaseSense)
17 | 18 |

Parameters

19 |
20 |
String1, String2
21 |
22 |

Type: String

23 |

The strings to be compared.

24 |
25 |
CaseSense
26 |
27 |

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.

33 |
34 |
35 | 36 |

Return Value

37 |

Type: Integer

38 |

To indicate the relationship between String1 and String2, this function returns one of the following:

39 |
    40 |
  • 0, if String1 is identical to String2
  • 41 |
  • a positive integer, if String1 is greater than String2
  • 42 |
  • a negative integer, if String1 is less than String2
  • 43 |
44 |

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) >= 0
47 | 48 |

Remarks

49 |

This function is commonly used for sort callbacks.

50 | 51 |

Related

52 |

Sort, VerCompare

53 | 54 |

Examples

55 |
56 |

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 -1
59 |
60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /docs/lib/StrGet.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | StrGet - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

StrGet

14 | 15 |

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 |

Parameters

20 |
21 | 22 |
Source
23 |
24 |

Type: Object or Integer

25 |

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 |
29 | 30 |
Length
31 |
32 |

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 |
37 | 38 |
Encoding
39 |
40 |

Type: String or Integer

41 |

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.

42 |
43 | 44 |
45 | 46 |

Return Value

47 |

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 |

Error Handling

51 |

A ValueError is thrown if invalid parameters are detected.

52 |

An OSError is thrown if the conversion could not be performed.

53 | 54 |

Remarks

55 |

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 |

Related

60 |

String Encoding, StrPut, Binary Compatibility, FileEncoding, DllCall, Buffer object, VarSetStrCapacity

61 | 62 |

Examples

63 |
64 |

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 |
71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /docs/lib/StrLen.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | StrLen - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

StrLen

14 |

Retrieves the count of how many characters are in a string.

15 |
Length := StrLen(String)
16 | 17 |

Parameters

18 |
19 |
String
20 |
21 |

Type: String

22 |

The string whose contents will be measured.

23 |
24 |
25 | 26 |

Return Value

27 |

Type: Integer

28 |

This function returns the length of the specified string.

29 | 30 |

Related

31 |

InStr, SubStr, Trim, StrLower, StrUpper, StrPut, StrGet, StrReplace, StrSplit

32 | 33 |

Examples

34 |
35 |

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: 43
38 |
39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /docs/lib/StrLower.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | StrLower / StrUpper / StrTitle - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

StrLower / StrUpper / StrTitle

15 | 16 |

Converts a string to lowercase, uppercase or title case.

17 | 18 |
NewString := StrLower(String)
19 | NewString := StrUpper(String)
20 | NewString := StrTitle(String)
21 |

Parameters

22 |
23 | 24 |
String
25 |
26 |

Type: String

27 |

The string to convert.

28 |
29 | 30 |
31 | 32 |

Return Value

33 |

Type: String

34 |

These functions return the newly converted version of the specified string.

35 | 36 |

Remarks

37 |

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 |

Related

52 |

InStr, SubStr, StrLen, StrReplace

53 |

Examples

54 |
55 |

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 |
59 | 60 |
61 |

Converts the string to uppercase and stores "THIS IS A TEST." in String2.

62 |
String2 := "This is a test."
63 | String2 := StrUpper(String2)
64 |
65 | 66 |
67 |

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 |
71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /docs/lib/StrPtr.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | StrPtr - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

StrPtr

15 |

Returns the current memory address of a string.

16 |
Address := StrPtr(Value)
17 | 18 |

Parameters

19 |
20 | 21 |
Value
22 |
23 |

Type: String

24 |
25 | 26 |
27 | 28 |

Return Value

29 |

Type: Integer

30 |

This function returns the current memory address of Value.

31 | 32 |

Remarks

33 |

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.

36 |

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).

39 |
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 |
    44 |
  • Concatenation.
  • 45 |
  • Built-in variables such as A_ScriptName.
  • 46 |
  • Functions which return strings.
  • 47 |
  • Accessing properties of an object, array elements or map elements.
  • 48 |
49 |

If not explicitly covered above, it is safe to assume the string is temporary.

50 | 51 |

Related

52 |

VarSetStrCapacity, DllCall, SendMessage, Buffer object, NumPut, NumGet

53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /docs/lib/StrPut.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | StrPut - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

StrPut

14 | 15 |

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 |

Parameters

23 |
24 | 25 |
String
26 |
27 |

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 |
31 | 32 |
Target
33 |
34 |

Type: Object or Integer

35 |

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 |
39 | 40 |
Length
41 |
42 |

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.

47 |

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 |
50 | 51 |
Encoding
52 |
53 |

Type: String or Integer

54 |

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.

55 |
56 | 57 |
58 | 59 |

Return Value

60 |

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.

62 |

In 2-parameter mode, this function returns the required buffer size in bytes, including space for the null-terminator.

63 | 64 |

Error Handling

65 |

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.

66 |

An OSError is thrown if the conversion could not be performed.

67 | 68 |

Remarks

69 |

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 |

Related

72 |

String Encoding, StrGet, Binary Compatibility, FileEncoding, DllCall, Buffer object, VarSetStrCapacity

73 | 74 |

Examples

75 |
76 |

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 |
83 |
84 |

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 |
95 | 96 | 97 | 98 | -------------------------------------------------------------------------------- /docs/lib/StrReplace.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | StrReplace - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

StrReplace

14 |

Replaces the specified substring with a new string.

15 |
ReplacedStr := StrReplace(Haystack, Needle , ReplaceText, CaseSense, &OutputVarCount, Limit)
16 | 17 |

Parameters

18 |
19 | 20 |
Haystack
21 |
22 |

Type: String

23 |

The string whose content is searched and replaced.

24 |
25 | 26 |
Needle
27 |
28 |

Type: String

29 |

The string to search for.

30 |
31 | 32 |
ReplaceText
33 |
34 |

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 |
37 | 38 |
CaseSense
39 |
40 |

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 |
46 | 47 |
&OutputVarCount
48 |
49 |

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 |
52 | 53 |
Limit
54 |
55 |

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 |
58 | 59 |
60 | 61 |

Return Value

62 |

Type: String

63 |

This function returns the replaced version of the specified string.

64 | 65 |

Remarks

66 |

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 |

Related

69 |

RegExReplace, InStr, SubStr, StrLen, StrLower, StrUpper

70 | 71 |

Examples

72 |
73 |

Removes all CR-LF pairs from the clipboard contents.

74 |
A_Clipboard := StrReplace(A_Clipboard, "`r`n")
75 |
76 | 77 |
78 |

Replaces all spaces with pluses.

79 |
NewStr := StrReplace(OldStr, A_Space, "+")
80 |
81 | 82 |
83 |

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 |
91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /docs/lib/StrSplit.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | StrSplit - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

StrSplit

14 |

Separates a string into an array of substrings using the specified delimiters.

15 |
Array := StrSplit(String , Delimiters, OmitChars, MaxParts)
16 | 17 |

Parameters

18 |
19 | 20 |
String
21 |
22 |

Type: String

23 |

A string to split.

24 |
25 | 26 |
Delimiters
27 |
28 |

Type: String or Array

29 |

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.

32 |
33 | 34 |
OmitChars
35 |
36 |

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.

38 |

If Delimiters is blank, OmitChars indicates which characters should be excluded from the array.

39 |
40 | 41 |
MaxParts
42 |
43 |

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 |
46 | 47 |
48 | 49 |

Return Value

50 |

Type: Array

51 |

This function returns an array containing the substrings of the specified string.

52 | 53 |

Remarks

54 |

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)

55 |

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_LoopField
61 | 62 |

Related

63 |

Parsing loop, Sort, SplitPath, InStr, SubStr, StrLen, StrLower, StrUpper, StrReplace

64 | 65 |

Examples

66 |
67 |

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 |
72 | 73 |
74 |

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 " color
78 |
79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /docs/lib/String.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | String - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

String

15 |

Converts a value to a string.

16 |
StrValue := String(Value)
17 | 18 |

Return Value

19 |

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.

23 | 24 |

Related

25 |

Type, Integer, Float, Values, Expressions, Is functions

26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /docs/lib/SubStr.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SubStr - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

SubStr

14 | 15 |

Retrieves one or more characters from the specified position in a string.

16 | 17 |
NewStr := SubStr(String, StartingPos , Length)
18 |

Parameters

19 |
20 | 21 |
String
22 |
23 |

Type: String

24 |

The string whose content is copied. This may contain binary zero.

25 |
26 | 27 |
StartingPos
28 |
29 |

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 |
33 | 34 |
Length
35 |
36 |

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 |
40 | 41 |
42 | 43 |

Return Value

44 |

Type: String

45 |

This function returns the requested substring of the specified string.

46 | 47 |

Related

48 |

RegExMatch

49 | 50 |

Examples

51 |
52 |

Retrieves a substring with a length of 3 characters at position 4.

53 |
MsgBox SubStr("123abc789", 4, 3) ; Returns abc
54 |
55 | 56 |
57 |

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 |
63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /docs/lib/Suspend.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Suspend - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Suspend

14 | 15 |

Disables or enables all or selected hotkeys and hotstrings.

16 | 17 |
Suspend NewState
18 |

Parameters

19 |
20 | 21 |
NewState
22 |
23 |

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.

26 |

0 or False: Re-enables the hotkeys and hotstrings that were disable above.

27 |

-1: Changes to the opposite of its previous state (On or Off).

28 |
29 | 30 |
31 | 32 |

Remarks

33 |

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 a green icon with a transparent H (or to a green icon with a transparent Pause symbol if the script is also paused). This icon change can be avoided by freezing the icon, which is achieved by using TraySetIcon(,, true).

39 |

The built-in variable A_IsSuspended contains 1 if the script is suspended and 0 otherwise.

40 | 41 |

Related

42 |

#SuspendExempt, Hotkeys, Hotstrings, #HotIf, Pause, ExitApp

43 | 44 |

Examples

45 |
46 |

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 False
50 |
51 | 52 |
53 |

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 |
59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /docs/lib/Switch.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Switch - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Switch

14 | 15 |

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 |

Parameters

28 |
29 | 30 |
SwitchValue
31 |
32 |

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 |
35 | 36 |
CaseSense
37 |
38 |

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 |
44 |
CaseValueN
45 |
46 |

The value to check or compare depending on whether SwitchValue is present.

47 |
48 | 49 |
50 | 51 |

Remarks

52 |

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.

53 |

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 |

Related

61 |

If, Else, Blocks

62 | 63 |

Examples

64 |
65 |

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 |
73 | 74 |
75 |

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 |
84 | 85 |
86 |

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 |
114 | 115 | 116 | 117 | -------------------------------------------------------------------------------- /docs/lib/SysGet.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SysGet - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

SysGet

14 | 15 |

Retrieves dimensions of system objects, and other system properties.

16 | 17 |
Value := SysGet(Property)
18 |

Parameters

19 |
20 | 21 |
Property
22 |
23 |

Type: Integer

24 |

Specify one of the numbers from the tables below to retrieve the corresponding value.

25 |
26 | 27 |
28 | 29 |

Return Value

30 |

Type: Integer

31 |

This function returns the value of the specified system property.

32 | 33 |

Commonly Used

34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 |
NumberDescription
80SM_CMONITORS: Number of display monitors on the desktop (not including "non-display pseudo-monitors").
43SM_CMOUSEBUTTONS: Number of buttons on mouse (0 if no mouse is installed).
16, 17SM_CXFULLSCREEN, SM_CYFULLSCREEN: Width and height of the client area for a full-screen window on the primary display monitor, in pixels.
61, 62SM_CXMAXIMIZED, SM_CYMAXIMIZED: Default dimensions, in pixels, of a maximized top-level window on the primary display monitor.
59, 60SM_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.
28, 29SM_CXMIN, SM_CYMIN: Minimum width and height of a window, in pixels.
57, 58SM_CXMINIMIZED, SM_CYMINIMIZED: Dimensions of a minimized window, in pixels.
34, 35SM_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.
0, 1SM_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.
78, 79SM_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.
19SM_MOUSEPRESENT: Nonzero if a mouse is installed; zero otherwise.
75SM_MOUSEWHEELPRESENT: Nonzero if a mouse with a wheel is installed; zero otherwise.
63SM_NETWORK: Least significant bit is set if a network is present; otherwise, it is cleared. The other bits are reserved for future use.
8193SM_REMOTECONTROL: This system metric is used in a Terminal Services environment. Its value is nonzero if the current session is remotely controlled; zero otherwise.
4096SM_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.
70SM_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.
8192SM_SHUTTINGDOWN: Nonzero if the current session is shutting down; zero otherwise. Windows 2000: The retrieved value is always 0.
23SM_SWAPBUTTON: Nonzero if the meanings of the left and right mouse buttons are swapped; zero otherwise.
76, 77SM_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.
116 | 117 |

Not Commonly Used

118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 |
NumberDescription
56SM_ARRANGE: Flags specifying how the system arranged minimized windows. See Microsoft Docs for more information.
67

SM_CLEANBOOT: Specifies how the system was started:

130 |
    131 |
  • 0 = Normal boot
  • 132 |
  • 1 = Fail-safe boot
  • 133 |
  • 2 = Fail-safe with network boot
  • 134 |
135 |
5, 6SM_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.
13, 14SM_CXCURSOR, SM_CYCURSOR: Width and height of a cursor, in pixels. The system cannot create cursors of other sizes.
36, 37SM_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.)
68, 69SM_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.
45, 46SM_CXEDGE, SM_CYEDGE: Dimensions of a 3-D border, in pixels. These are the 3-D counterparts of SM_CXBORDER and SM_CYBORDER.
7, 8SM_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.
83, 84SM_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.
21, 3SM_CXHSCROLL, SM_CYHSCROLL: Width of the arrow bitmap on a horizontal scroll bar, in pixels; and height of a horizontal scroll bar, in pixels.
10SM_CXHTHUMB: Width of the thumb box in a horizontal scroll bar, in pixels.
11, 12SM_CXICON, SM_CYICON: Default width and height of an icon, in pixels.
38, 39SM_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.
71, 72SM_CXMENUCHECK, SM_CYMENUCHECK: Dimensions of the default menu check-mark bitmap, in pixels.
54, 55SM_CXMENUSIZE, SM_CYMENUSIZE: Dimensions of menu bar buttons, such as the child window close button used in the multiple document interface, in pixels.
47, 48SM_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.
30, 31SM_CXSIZE, SM_CYSIZE: Width and height of a button in a window's caption or title bar, in pixels.
32, 33SM_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.
49, 50SM_CXSMICON, SM_CYSMICON: Recommended dimensions of a small icon, in pixels. Small icons typically appear in window captions and in small icon view.
52, 53SM_CXSMSIZE SM_CYSMSIZE: Dimensions of small caption buttons, in pixels.
2, 20SM_CXVSCROLL, SM_CYVSCROLL: Width of a vertical scroll bar, in pixels; and height of the arrow bitmap on a vertical scroll bar, in pixels.
4SM_CYCAPTION: Height of a caption area, in pixels.
18SM_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.
15SM_CYMENU: Height of a single-line menu bar, in pixels.
51SM_CYSMCAPTION: Height of a small caption, in pixels.
9SM_CYVTHUMB: Height of the thumb box in a vertical scroll bar, in pixels.
42SM_DBCSENABLED: Nonzero if User32.dll supports DBCS; zero otherwise.
22SM_DEBUG: Nonzero if the debug version of User.exe is installed; zero otherwise.
82

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.

40SM_MENUDROPALIGNMENT: Nonzero if drop-down menus are right-aligned with the corresponding menu-bar item; zero if the menus are left-aligned.
74SM_MIDEASTENABLED: Nonzero if the system is enabled for Hebrew and Arabic languages, zero if not.
41SM_PENWINDOWS: Nonzero if the Microsoft Windows for Pen computing extensions are installed; zero otherwise.
44SM_SECURE: Nonzero if security is present; zero otherwise.
81SM_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.
267 |

Remarks

268 |

SysGet simply calls the GetSystemMetrics function, which may support more system properties than are documented here.

269 | 270 |

Related

271 |

DllCall, Win functions, Monitor functions

272 | 273 |

Examples

274 |
275 |

Retrieves the number of mouse buttons and stores it in MouseButtonCount.

276 |
MouseButtonCount := SysGet(43)
277 |
278 | 279 |
280 |

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 |
284 | 285 | 286 | 287 | -------------------------------------------------------------------------------- /docs/lib/SysGetIPAddresses.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | SysGetIPAddresses - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

SysGetIPAddresses

15 | 16 |

Returns an array of the system's IPv4 addresses.

17 | 18 |
Addresses := SysGetIPAddresses()
19 | 20 |

Parameters

21 |

This function has no parameters.

22 | 23 |

Return Value

24 |

Type: Array

25 |

This function returns an array, where each element is an IPv4 address string such as "192.168.0.1".

26 | 27 |

Remarks

28 |

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.ResponseText
34 | 35 |

Related

36 |

A_ComputerName

37 | 38 |

Examples

39 |
40 |

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 msg
46 |
47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /docs/lib/Thread.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Thread - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Thread

14 | 15 |

Sets the priority or interruptibility of threads. It can also temporarily disable all timers.

16 |
Thread SubFunction , Value1, Value2
17 |

The SubFunction, Value1, and Value2 parameters are dependent upon each other and their usage is described below.

18 | 19 |

Sub-functions

20 |

For SubFunction, specify one of the following:

21 |
    22 |
  • NoTimers: Prevents interruptions from any timers.
  • 23 |
  • Priority: Changes the priority level of the current thread.
  • 24 |
  • Interrupt: Changes the duration of interruptibility for newly launched threads.
  • 25 |
26 | 27 |

NoTimers

28 |

Prevents interruptions from any timers.

29 |
Thread "NoTimers" , False
30 |

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).

31 |

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.

34 | 35 |

Priority

36 |

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 |

Interrupt

44 |

Changes the duration of interruptibility for newly launched threads.

45 |
Thread "Interrupt" , Duration, LineCount
46 |

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 |

Remarks

56 |

Due to its greater flexibility and its ability to buffer events, the function Critical is generally more useful than Thread "Interrupt" and Thread "Priority".

57 |

Related

58 |

Critical, Threads, Hotkey, Menu object, SetTimer, Process functions

59 |

Examples

60 |
61 |

Makes the priority of the current thread slightly above average.

62 |
Thread "Priority", 1
63 |
64 | 65 |
66 |

Makes each newly launched thread immediately interruptible.

67 |
Thread "Interrupt", 0
68 |
69 | 70 |
71 |

Makes each thread interruptible after 50 ms or 2000 lines, whichever comes first.

72 |
Thread "Interrupt", 50, 2000
73 |
74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /docs/lib/Throw.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Throw - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Throw

14 | 15 |

Signals the occurrence of an error. This signal can be caught by a Try-Catch statement.

16 | 17 |
Throw Value
18 |

Parameters

19 |
20 | 21 |
Value
22 |
23 |

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.

27 |
28 | 29 |
30 | 31 |

Remarks

32 |

The space or tab after throw is optional if the expression is enclosed in parentheses, as in throw(Error()).

33 |

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 |
    35 |
  • Any active OnError callbacks are called. Each callback may inspect Value and either suppress or allow further callbacks and default handling.
  • 36 |
  • By default, an error message is displayed based on what was thrown. If Value is an Object and owns a value property named Message, its value is used as the message. If Value is a non-numeric string, it is used as the message. In any other case, a default message is used. If Value is numeric, it is shown below the default message.
  • 37 |
  • The thread exits. Note that this does not necessarily occur for continuable errors, but throw is never continuable.
  • 38 |
39 | 40 |

Related

41 |

Error Object, Try, Catch, Finally, OnError

42 | 43 |

Examples

44 |

See Try.

45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/lib/ToolTip.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ToolTip - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

ToolTip

14 | 15 |

Shows an always-on-top window anywhere on the screen.

16 | 17 |
ToolTip Text, X, Y, WhichToolTip
18 |

Parameters

19 |
20 | 21 |
Text
22 |
23 |

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".

25 |

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 |
27 | 28 |
X, Y
29 |
30 |

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).

32 |
33 | 34 |
WhichToolTip
35 |
36 |

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 |
39 | 40 |
41 | 42 |

Return Value

43 |

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 |

Remarks

48 |

A tooltip usually looks like this: ToolTip

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 |
    52 |
  • The script terminates.
  • 53 |
  • The ToolTip function is executed again with a blank Text parameter.
  • 54 |
  • The user clicks on the tooltip (this behavior may vary depending on operating system version).
  • 55 |
56 |

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 |

Related

58 |

CoordMode, TrayTip, GUI, MsgBox, InputBox, FileSelect, DirSelect

59 |

Examples

60 |
61 |

Shows a multiline tooltip at a specific position in the active window.

62 |
ToolTip "Multiline`nTooltip", 100, 150
63 |
64 | 65 |
66 |

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(), -5000
69 |
70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /docs/lib/TraySetIcon.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | TraySetIcon - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

TraySetIcon

15 | 16 |

Changes the script's tray icon (which is also used by GUI and dialog windows).

17 | 18 |
TraySetIcon FileName, IconNumber, Freeze
19 |

Parameters

20 |
21 | 22 |
FileName
23 |
24 |

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.

26 |

For a list of supported formats, see the Picture control.

27 |
28 | 29 |
IconNumber
30 |
31 |

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.

33 |
34 | 35 |
Freeze
36 |
37 |

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 |
42 | 43 |
44 | 45 |

Remarks

46 |

To freeze (or unfreeze) the current icon, use the function as follows: TraySetIcon(,, true).

47 |

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.

48 |

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.

50 |

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 |

Related

54 |

#NoTrayIcon, TrayTip, Menu object

55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /docs/lib/TrayTip.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | TrayTip - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 18 | 19 | 20 | 21 |

TrayTip

22 | 23 |

Shows a balloon message window or, on Windows 10 and later, a toast notification near the tray icon.

24 | 25 |
TrayTip Text, Title, Options
26 |

Parameters

27 |
28 | 29 |
Text
30 |
31 |

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.

34 |

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 |
36 | 37 |
Title
38 |
39 |

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 |
42 | 43 |
Options
44 |
45 |

Type: String or Integer

46 |

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 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 |
FunctionDecHexString
No icon00x0N/A
Info icon10x1Iconi
Warning icon20x2Icon!
Error icon30x3Iconx
Tray icon40x4N/A
Do not play the notification sound.160x10Mute
Use the large version of the icon.320x20N/A
97 |

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 |
100 | 101 |
102 | 103 |

Hiding the Traytip

104 |

To hide the traytip, omit all parameters (or at least the Text and Title parameters). For example:

105 |
TrayTip
106 |

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 |

Remarks

125 |

On Windows 10, a traytip window usually looks like this:

126 | TrayTip 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:

129 |
HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced >> EnableBalloonTips
130 |

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".

131 | 132 |

Related

133 |

ToolTip, SetTimer, Menu object, MsgBox, InputBox, FileSelect, DirSelect

134 | 135 |

Examples

136 |
137 |

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 |
140 | 141 |
142 |

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(), -5000
145 |

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 |
154 | 155 |
156 |

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 |
165 | 166 |
167 |

Shows a message box whenever a traytip is left-clicked, timed out, closed, shown, queued, or disappeared. Press F1 to test this example. For details, see Shell_NotifyIcon (Microsoft Docs).

168 |
OnMessage 0x404, AHK_NOTIFYICON
169 | 
170 | F1::TrayTip("foo", "bar")
171 | 
172 | AHK_NOTIFYICON(wParam, lParam, msg, hwnd)
173 | {
174 |     if (hwnd != A_ScriptHwnd)
175 |         return
176 |     if (lParam = 1029) ; NIN_BALLOONUSERCLICK
177 |         MsgBox "Traytip was left-clicked."
178 |     if (lParam = 1028) ; NIN_BALLOONTIMEOUT
179 |         MsgBox "Traytip timed out or was closed or right-clicked."
180 |     if (lParam = 1026) ; NIN_BALLOONSHOW
181 |         MsgBox "Traytip was shown or queued."
182 |     if (lParam = 1027) ; NIN_BALLOONHIDE
183 |         MsgBox "Traytip disappeared, but not due to timeout or user interaction."
184 | }
185 |
186 | 187 | 188 | 189 | -------------------------------------------------------------------------------- /docs/lib/TreeView.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | TreeView (GUI) - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

TreeView

14 | 15 |

Table of Contents

16 |
    17 |
  • Introduction and Simple Example
  • 18 |
  • Options and Styles for the Options Parameter
  • 19 |
  • Built-in Methods for TreeViews
  • 20 |
  • Events
  • 21 |
  • Remarks
  • 22 |
  • Examples
  • 23 |
24 |

Introduction and Simple Example

25 |

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 | TreeView 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 |

Options and Styles for the Options Parameter

44 |

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").

45 |

Buttons: Specify -Buttons (minus Buttons) to avoid displaying a plus or minus button to the left of each item that has children.

46 |

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.

47 |

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).

49 |

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.

58 |

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:

59 |
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.

67 |

WantF2: Specify -WantF2 (minus WantF2) to prevent F2 from editing the currently selected item. This setting is ignored unless -ReadOnly is also in effect.

68 |

(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 |

Built-in Methods for TreeViews

70 |

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 |
    73 |
  • Add: Adds a new item to the TreeView.
  • 74 |
  • Modify: Modifies the attributes and/or name of an item.
  • 75 |
  • Delete: Deletes the specified item or all items.
  • 76 |
77 |

Retrieval methods:

78 |
    79 |
  • GetSelection: Returns the selected item's ID number.
  • 80 |
  • GetCount: Returns the total number of items in the control.
  • 81 |
  • GetParent: Returns the ID number of the specified item's parent.
  • 82 |
  • GetChild: Returns the ID number of the specified item's first/top child.
  • 83 |
  • GetPrev: Returns the ID number of the sibling above the specified item.
  • 84 |
  • GetNext: Returns the ID number of the next item below the specified item.
  • 85 |
  • GetText: Retrieves the text/name of the specified item.
  • 86 |
  • Get: Returns the ID number of the specified item if it has the specified attribute.
  • 87 |
88 |

Other methods:

89 |
    90 |
  • SetImageList: Sets or replaces an ImageList for displaying icons.
  • 91 |
92 | 93 |
94 |

Add

95 |

Adds a new item to the TreeView.

96 |
ItemID := TV.Add(Name, ParentItemID, Options)
97 |

Parameters

98 |
99 |
Name
100 |
101 |

Type: String

102 |

The displayed text of the item, which can be text or numeric (including numeric expression results).

103 |
104 |
ParentItemID
105 |
106 |

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 |
109 |
Options
110 |
111 |

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.

114 |

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).

115 |

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.

116 |

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.

120 |

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 |
123 |
124 |

Return Value

125 |

Type: Integer

126 |

On success, this method returns the unique ID number of the newly added item. On failure, it returns 0.

127 |

Remarks

128 |

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.

129 |
130 | 131 |
132 |

Modify

133 |

Modifies the attributes and/or name of an item.

134 |
ItemID := TV.Modify(ItemID , Options, NewName)
135 |

Parameters

136 |
137 |
ItemID
138 |
139 |

Type: Integer

140 |

The ID number of the item to modify.

141 |
142 |
Options
143 |
144 |

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 |
147 |
NewName
148 |
149 |

Type: String

150 |

If omitted, the current name is left unchanged. Otherwise, specify the new name of the item.

151 |
152 |
153 |

Return Value

154 |

Type: Integer

155 |

This method returns the item's own ID.

156 |
157 | 158 |
159 |

Delete

160 |

Deletes the specified item or all items.

161 |
TV.Delete(ItemID)
162 |

Parameters

163 |
164 |
ItemID
165 |
166 |

Type: Integer

167 |

If omitted, all items in the TreeView are deleted. Otherwise, specify the ID number of the item to delete.

168 |
169 |
170 |
171 | 172 |
173 |

GetSelection

174 |

Returns the selected item's ID number.

175 |
ItemID := TV.GetSelection()
176 |

Return Value

177 |

Type: Integer

178 |

This method returns the selected item's ID number.

179 |
180 | 181 |
182 |

GetCount

183 |

Returns the total number of items in the control.

184 |
Count := TV.GetCount()
185 |

Return Value

186 |

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 |
189 | 190 |
191 |

GetParent

192 |

Returns the ID number of the specified item's parent.

193 |
ParentItemID := TV.GetParent(ItemID)
194 |

Parameters

195 |
196 |
ItemID
197 |
198 |

Type: Integer

199 |

The ID number of the item to check.

200 |
201 |
202 |

Return Value

203 |

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 |
206 | 207 |
208 |

GetChild

209 |

Returns the ID number of the specified item's first/top child.

210 |
ChildItemID := TV.GetChild(ItemID)
211 |

Parameters

212 |
213 |
ItemID
214 |
215 |

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 |
218 |
219 |

Return Value

220 |

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 |
223 | 224 |
225 |

GetPrev

226 |

Returns the ID number of the sibling above the specified item.

227 |
PrevItemID := TV.GetPrev(ItemID)
228 |
229 |
ItemID
230 |
231 |

Type: Integer

232 |

The ID number of the item to check.

233 |
234 |
235 |

Return Value

236 |

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 |
239 | 240 |
241 |

GetNext

242 |

Returns the ID number of the next item below the specified item.

243 |
NextItemID := TV.GetNext(ItemID, ItemType)
244 |

Parameters

245 |
246 |
ItemID
247 |
248 |

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 |
251 |
ItemType
252 |
253 |

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 |
258 |
259 |

Return Value

260 |

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 |

Remarks

263 |

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 |
274 | 275 |
276 |

GetText

277 |

Retrieves the text/name of the specified item.

278 |
Text := TV.GetText(ItemID)
279 |

Parameters

280 |
281 |
ItemID
282 |
283 |

Type: Integer

284 |

The ID number of the item whose text to be retrieved.

285 |
286 |
287 |

Return Value

288 |

Type: String

289 |

This method returns the retrieved text. Only up to 8191 characters are retrieved.

290 |
291 | 292 |
293 |

Get

294 |

Returns the ID number of the specified item if it has the specified attribute.

295 |
ItemID := TV.Get(ItemID, Attribute)
296 |

Parameters

297 |
298 |
ItemID
299 |
300 |

Type: Integer

301 |

The ID number of the item to check.

302 |
303 |
Attribute
304 |
305 |

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 |
311 |
312 |

Return Value

313 |

Type: Integer

314 |

If the specified item has the specified attribute, its own ID is returned. Otherwise, 0 is returned.

315 |

Remarks

316 |

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").

317 |
318 | 319 |
320 |

SetImageList

321 |

Sets or replaces an ImageList for displaying icons.

322 |
PrevImageListID := TV.SetImageList(ImageListID , IconType)
323 |

Parameters

324 |
325 |
ImageListID
326 |
327 |

Type: Integer

328 |

The ID number returned from a previous call to IL_Create.

329 |
330 |
IconType
331 |
332 |

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 |
335 |
336 |

Return Value

337 |

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 |
340 | 341 |

Events

342 |

The following events can be detected by calling OnEvent to register a callback function or method:

343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 |
EventRaised when...
ClickThe control is clicked.
DoubleClickThe control is double-clicked.
ContextMenuThe user right-clicks the control or presses Menu or Shift+F10 while the control has the keyboard focus.
FocusThe control gains the keyboard focus.
LoseFocusThe control loses the keyboard focus.
ItemCheckAn item is checked or unchecked.
ItemEditAn item's label is edited by the user.
ItemExpandAn item is expanded or collapsed.
ItemSelectAn item is selected.
355 |

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 |

Remarks

358 |

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 |

Related

375 |

ListView, Other Control Types, Gui(), ContextMenu event, Gui object, GuiControl object, TreeView styles table

376 | 377 |

Examples

378 | 379 |
380 |

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 |
465 | 466 | 467 | -------------------------------------------------------------------------------- /docs/lib/Trim.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Trim / LTrim / RTrim - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Trim / LTrim / RTrim

14 | 15 |

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 |

Parameters

21 |
22 | 23 |
String
24 |
25 |

Type: String

26 |

Any string value or variable. Numbers are not supported.

27 |
28 | 29 |
OmitChars
30 |
31 |

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 |
34 | 35 |
36 | 37 |

Return Value

38 |

Type: String

39 |

These functions return the trimmed version of the specified string.

40 | 41 |

Examples

42 |
43 |

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 |
53 | 54 |
55 |

Trims all zeros from the left side of a string.

56 |
MsgBox LTrim("00000123", "0")
57 |
58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /docs/lib/Try.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Try - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Try

14 | 15 |

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 |

Remarks

23 |

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.

25 |

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 |
    27 |
  • If there is a Catch statement which matches the class of the thrown value, execution is transferred into it.
  • 28 |
  • If there is no matching Catch statement but there is a Finally statement, it is executed, but once it finishes the value is automatically thrown again.
  • 29 |
  • If there is no matching Catch statement or Finally statement, the value is automatically thrown again (unless there is no Catch or Finally at all, as noted above).
  • 30 |
31 |

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 |

Related

44 |

Throw, Catch, Else, Finally, Blocks, OnError

45 | 46 |

Examples

47 |
48 |

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 |
72 | 73 |
74 |

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 |
94 | 95 |
96 |

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 |
115 | 116 |
117 |

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 |
139 | 140 | 141 | 142 | -------------------------------------------------------------------------------- /docs/lib/Type.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Type - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Type

15 |

Returns the class name of a value.

16 |
ClassName := Type(Value)
17 | 18 |

Return Value

19 |

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 |

Remarks

57 |

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.

58 |

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.

61 | 62 |

Related

63 |

Values, Expressions, Is functions, Integer, Float, String

64 | 65 |

Examples

66 |
67 |

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 |
75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /docs/lib/Until.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Until - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Until

14 | 15 |

Applies a condition to the continuation of a Loop or For-loop.

16 | 17 |
Loop {
18 |     ...
19 | } Until Expression
20 |

Parameters

21 |
22 | 23 |
Expression
24 |

Any valid expression.

25 | 26 |
27 | 28 |

Remarks

29 |

The space or tab after Until is optional if the expression is enclosed in parentheses, as in until(expression).

30 |

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 > y
41 |

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 |

Related

50 |

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 | VarSetStrCapacity - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

VarSetStrCapacity

15 | 16 |

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 |

Parameters

20 |
21 | 22 |
&TargetVar
23 |
24 |

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.

26 |
27 | 28 |
RequestedCapacity
29 |
30 |

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.

35 |

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.

37 |

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 |
39 | 40 |
41 | 42 |

Return Value

43 |

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 |

Failure

47 |

An exception is thrown under any of the following conditions:

48 |
    49 |
  • TargetVar is not a valid variable reference. It is not possible to pass an object property or built-in variable by reference, and therefore not valid to pass one to this function.
  • 50 |
  • The requested capacity is too large to fit within any single contiguous memory block available to the script. In rare cases, this may be due to the system running out of memory.
  • 51 |
  • RequestedCapacity is less than -1 or greater than the capacity theoretically supported by the current platform.
  • 52 |
53 | 54 |

Remarks

55 |

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 := "".

57 | 58 |

Related

59 |

Buffer object, DllCall, NumPut, NumGet

60 |

Examples

61 |
62 |

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 |
71 | 72 |
73 |

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 |
111 | 112 | 113 | 114 | -------------------------------------------------------------------------------- /docs/lib/VerCompare.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | VerCompare - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

VerCompare

14 |

Compares two version strings.

15 |
Result := VerCompare(VersionA, VersionB)
16 | 17 |

Parameters

18 |
19 |
VersionA
20 |
21 |

Type: String

22 |

The first version string to be compared.

23 |
24 |
VersionB
25 |
26 |

Type: String

27 |

The second version string to be compared, optionally prefixed with one of the following operators: <, <=, >, >= or =.

28 |
29 |
30 | 31 |

Return Value

32 |

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 |
    36 |
  • 0 if VersionA is equal to VersionB
  • 37 |
  • a positive integer if VersionA is greater than VersionB
  • 38 |
  • a negative integer if VersionA is less than VersionB
  • 39 |
40 |

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) >= 0
43 | 44 |

Remarks

45 |

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 |

Related

51 |

#Requires, Sort, StrCompare

52 | 53 |

Examples

54 |
55 |

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 |
63 | 64 |
65 |

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 |
71 | 72 |
73 |

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 |
80 | 81 |
82 |

Demonstrates a range check.

83 |
84 | MsgBox VerCompare("2.0.1", ">=2.0") && VerCompare("2.0.1", "<2.1")  ; Returns 1
85 | 
86 |
87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /docs/lib/While.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | While Loop - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

While-loop

14 | 15 |

Performs one or more statements repeatedly until the specified expression evaluates to false.

16 | 17 |
While Expression
18 |

Parameters

19 |
20 | 21 |
Expression
22 |

Any valid expression. For example: while x < y.

23 | 24 |
25 | 26 |

Remarks

27 |

The space or tab after While is optional if the expression is enclosed in parentheses, as in While(expression).

28 |

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 {.

31 |

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 |

Related

37 |

Until, Break, Continue, Blocks, Loop, For-loop, Files-and-folders loop, Registry loop, File-reading loop, Parsing loop, If

38 | 39 |

Examples

40 |
41 |

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 |
56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /docs/lib/Win.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | List of Win Functions | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Win Functions

15 | 16 |

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 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 |
FunctionDescription
WinActivateActivates the specified window.
WinActivateBottomSame as WinActivate except that it activates the bottommost matching window rather than the topmost.
WinActiveChecks if the specified window exists and is currently active (foremost).
WinCloseCloses the specified window.
WinExistChecks if the specified window exists.
WinGetClassRetrieves the specified window's class name.
WinGetClientPosRetrieves the position and size of the specified window's client area.
WinGetControlsReturns an array of names (ClassNNs) for all controls in the specified window.
WinGetControlsHwndReturns an array of unique ID numbers (HWNDs) for all controls in the specified window.
WinGetCountReturns the number of existing windows that match the specified criteria.
WinGetIDReturns the unique ID number (HWND) of the specified window.
WinGetIDLastReturns the unique ID number (HWND) of the last/bottommost window if there is more than one match.
WinGetListReturns an array of unique ID numbers (HWNDs) for all existing windows that match the specified criteria.
WinGetMinMaxReturns a non-zero number if the specified window is maximized or minimized.
WinGetPIDReturns the Process ID number (PID) of the specified window.
WinGetPosRetrieves the position and size of the specified window.
WinGetProcessNameReturns the name of the process that owns the specified window.
WinGetProcessPathReturns the full path and name of the process that owns the specified window.
WinGetStyle
WinGetExStyle
Returns the style or extended style (respectively) of the specified window.
WinGetTextRetrieves the text from the specified window.
WinGetTitleRetrieves the title of the specified window.
WinGetTransColorReturns the color that is marked transparent in the specified window.
WinGetTransparentReturns the degree of transparency of the specified window.
WinHideHides the specified window.
WinKillForces the specified window to close.
WinMaximizeEnlarges the specified window to its maximum size.
WinMinimizeCollapses the specified window into a button on the task bar.
WinMinimizeAll
WinMinimizeAllUndo
Minimizes or unminimizes all windows.
WinMoveChanges the position and/or size of the specified window.
WinMoveBottomSends the specified window to the bottom of stack; that is, beneath all other windows.
WinMoveTopBrings the specified window to the top of the stack without explicitly activating it.
WinRedrawRedraws the specified window.
WinRestoreUnminimizes or unmaximizes the specified window if it is minimized or maximized.
WinSetAlwaysOnTopMakes the specified window stay on top of all other windows (except other always-on-top windows).
WinSetEnabledEnables or disables the specified window.
WinSetRegionChanges the shape of the specified window to be the specified rectangle, ellipse, or polygon.
WinSetStyle
WinSetExStyle
Changes the style or extended style of the specified window, respectively.
WinSetTitleChanges the title of the specified window.
WinSetTransColorMakes all pixels of the chosen color invisible inside the specified window.
WinSetTransparentMakes the specified window semi-transparent.
WinShowUnhides the specified window.
WinWaitWaits until the specified window exists.
WinWaitActive
WinWaitNotActive
Waits until the specified window is active or not active.
WinWaitCloseWaits until no matching windows can be found.
199 | 200 |

Remarks

201 |

To discover the unique ID number of the window that the mouse is currently hovering over, use MouseGetPos.

202 | 203 |

Related

204 |

SetWinDelay, Control functions, Gui object (for windows created by the script)

205 | 206 | 207 | 208 | -------------------------------------------------------------------------------- /docs/lib/WinActivate.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinActivate - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinActivate

14 | 15 |

Activates the specified window.

16 | 17 |
WinActivate WinTitle, WinText, ExcludeTitle, ExcludeText
18 |

Parameters

19 |
20 | 21 |
WinTitle, WinText, ExcludeTitle, ExcludeText
22 |
23 |

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 |
28 | 29 |
30 | 31 |

Error Handling

32 |

A TargetError is thrown if the window could not be found.

33 | 34 |

Remarks

35 |

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(...).

38 |

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.

39 |

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", 2
48 | 49 |

Related

50 |

WinActivateBottom, #WinActivateForce, SetTitleMatchMode, DetectHiddenWindows, Last Found Window, WinExist, WinActive, WinWaitActive, WinWait, WinWaitClose, WinClose, GroupActivate, Win functions

51 |

Examples

52 |
53 |

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 |
59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /docs/lib/WinActivateBottom.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinActivateBottom - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinActivateBottom

14 | 15 |

Same as WinActivate except that it activates the bottommost matching window rather than the topmost.

16 | 17 |
WinActivateBottom WinTitle, WinText, ExcludeTitle, ExcludeText
18 |

Parameters

19 |
20 | 21 |
WinTitle, WinText, ExcludeTitle, ExcludeText
22 |
23 |

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 |
28 | 29 |
30 | 31 |

Error Handling

32 |

A TargetError is thrown if the window could not be found.

33 | 34 |

Remarks

35 |

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 |

Related

44 |

WinActivate, #WinActivateForce, SetTitleMatchMode, DetectHiddenWindows, WinExist, WinActive, WinWaitActive, WinWait, WinWaitClose, GroupActivate

45 |

Examples

46 |
47 |

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 |
54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /docs/lib/WinActive.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinActive - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinActive

14 |

Checks if the specified window is active and returns its unique ID (HWND).

15 |
UniqueID := WinActive(WinTitle, WinText, ExcludeTitle, ExcludeText)
16 | 17 |

Parameters

18 |
19 | 20 |
WinTitle, WinText, ExcludeTitle, ExcludeText
21 |
22 |

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 |
27 | 28 |
29 | 30 |

Return Value

31 |

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.

34 | 35 |

Remarks

36 |

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").

38 |

SetWinDelay does not apply to this function.

39 | 40 |

Related

41 |

WinExist, SetTitleMatchMode, DetectHiddenWindows, Last Found Window, WinActivate, WinWaitActive, WinWait, WinWaitClose, #HotIf

42 | 43 |

Examples

44 |
45 |

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 |
49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /docs/lib/WinClose.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinClose - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinClose

14 | 15 |

Closes the specified window.

16 | 17 |
WinClose WinTitle, WinText, SecondsToWait, ExcludeTitle, ExcludeText
18 |

Parameters

19 |
20 | 21 |
WinTitle, WinText, ExcludeTitle, ExcludeText
22 |
23 |

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 |
28 | 29 |
SecondsToWait
30 |
31 |

Type: Integer or Float

32 |

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 |
34 | 35 |
36 | 37 |

Error Handling

38 |

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 |

Remarks

42 |

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_CLOSE
48 |

If a window does not close via WinClose, you can force it to close with WinKill.

49 | 50 |

Related

51 |

WinKill, WinWaitClose, ProcessClose, WinActivate, SetTitleMatchMode, DetectHiddenWindows, Last Found Window, WinExist, WinActive, WinWaitActive, WinWait, GroupActivate

52 |

Examples

53 |
54 |

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 |
60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /docs/lib/WinExist.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinExist - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinExist

14 |

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 |

Parameters

18 |
19 | 20 |
WinTitle, WinText, ExcludeTitle, ExcludeText
21 |
22 |

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 |
27 | 28 |
29 | 30 |

Return Value

31 |

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.

34 | 35 |

Remarks

36 |

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 |

Related

41 |

WinActive, SetTitleMatchMode, DetectHiddenWindows, Last Found Window, ProcessExist, WinActivate, WinWaitActive, WinWait, WinWaitClose, #HotIf

42 | 43 |

Examples

44 |
45 |

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 |
49 | 50 |
51 |

Retrieves and reports the unique ID (HWND) of the active window.

52 |
MsgBox "The active window's ID is " WinExist("A")
53 |
54 | 55 |
56 |

Returns if the calculator does not exist.

57 |
if not WinExist("Calculator")
58 |     return
59 |
60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /docs/lib/WinGetClass.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinGetClass - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinGetClass

14 | 15 |

Retrieves the specified window's class name.

16 | 17 |
ClassName := WinGetClass(WinTitle, WinText, ExcludeTitle, ExcludeText)
18 |

Parameters

19 |
20 | 21 |
WinTitle, WinText, ExcludeTitle, ExcludeText
22 |
23 |

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 |
28 | 29 |
30 | 31 |

Return Value

32 |

Type: String

33 |

This function returns the class name of the specified window.

34 | 35 |

Error Handling

36 |

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 |

Remarks

40 |

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 |

Related

44 |

WinGetTitle, Win functions

45 |

Examples

46 |
47 |

Retrieves and reports the class name of the active window.

48 |
MsgBox "The active window's class is " WinGetClass("A")
49 |
50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /docs/lib/WinGetClientPos.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinGetClientPos - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinGetClientPos

15 | 16 |

Retrieves the position and size of the specified window's client area.

17 | 18 |
WinGetClientPos &OutX, &OutY, &OutWidth, &OutHeight, WinTitle, WinText, ExcludeTitle, ExcludeText
19 |

Parameters

20 |
21 | 22 |
&OutX, &OutY
23 |
24 |

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 |
27 | 28 |
&OutWidth, &OutHeight
29 |
30 |

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 |
33 | 34 |
WinTitle, WinText, ExcludeTitle, ExcludeText
35 |
36 |

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 |
41 | 42 |
43 | 44 |

Error Handling

45 |

A TargetError is thrown if the window could not be found.

46 | 47 |

Remarks

48 |

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.

50 |

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 |

Related

55 |

WinGetPos, WinMove, ControlGetPos, WinGetTitle, WinGetText, ControlGetText

56 | 57 |

Examples

58 |
59 |

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" H
62 |
63 | 64 |
65 |

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 "," Y
68 |
69 | 70 |
71 |

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 |
78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /docs/lib/WinGetControls.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinGetControls - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinGetControls

15 | 16 |

Returns an array of names (ClassNNs) for all controls in the specified window.

17 | 18 |
ClassNNs := WinGetControls(WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
WinTitle, WinText, ExcludeTitle, ExcludeText
23 |
24 |

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 |
29 |
30 | 31 |

Return Value

32 |

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.

35 |

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 |

Error Handling

38 |

A TargetError is thrown if the window could not be found.

39 | 40 |

Remarks

41 |

The ID of the window or control under the mouse cursor can be retrieved with MouseGetPos.

42 | 43 |

Related

44 |

WinGetControlsHwnd, Win functions, Control functions

45 | 46 |

Examples

47 |
48 |

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 |
56 | 57 |
58 |

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 |
78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /docs/lib/WinGetControlsHwnd.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinGetControlsHwnd - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinGetControlsHwnd

15 | 16 |

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 |

Parameters

21 |
22 |
WinTitle, WinText, ExcludeTitle, ExcludeText
23 |
24 |

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 |
29 |
30 | 31 |

Return Value

32 |

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.

35 |

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 |

Error Handling

38 |

A TargetError is thrown if the window could not be found.

39 | 40 |

Remarks

41 |

The ID of the window or control under the mouse cursor can be retrieved with MouseGetPos.

42 | 43 |

Related

44 |

WinGetControls, Win functions, Control functions

45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/lib/WinGetCount.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinGetCount - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinGetCount

15 | 16 |

Returns the number of existing windows that match the specified criteria.

17 | 18 |
Count := WinGetCount(WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
WinTitle, WinText, ExcludeTitle, ExcludeText
23 |
24 |

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 |
29 |
30 | 31 |

Return Value

32 |

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 |

Remarks

36 |

The ID of the window under the mouse cursor can be retrieved with MouseGetPos.

37 | 38 |

Related

39 |

WinGetList, Win functions, Control functions

40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /docs/lib/WinGetID.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinGetID - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinGetID

15 | 16 |

Returns the unique ID number (HWND) of the specified window.

17 | 18 |
HWND := WinGetID(WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
WinTitle, WinText, ExcludeTitle, ExcludeText
23 |
24 |

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 |
29 |
30 | 31 |

Return Value

32 |

Type: Integer

33 |

This function returns the window handle (HWND) of the specified window.

34 | 35 |

Error Handling

36 |

A TargetError is thrown if the window could not be found.

37 | 38 |

Remarks

39 |

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 |

Related

44 |

WinGetIDLast, ControlGetHwnd, Hwnd property (Gui object), Win functions, Control functions

45 | 46 |

Examples

47 |
48 |

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_id
52 |
53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /docs/lib/WinGetIDLast.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinGetIDLast - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinGetIDLast

15 | 16 |

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 |

Parameters

21 |
22 |
WinTitle, WinText, ExcludeTitle, ExcludeText
23 |
24 |

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 |
29 |
30 | 31 |

Return Value

32 |

Type: Integer

33 |

This function returns the window handle (HWND) of the last/bottommost window if there is more than one match.

34 | 35 |

Error Handling

36 |

A TargetError is thrown if the window could not be found.

37 | 38 |

Remarks

39 |

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 |

Related

44 |

WinGetID, ControlGetHwnd, Hwnd property (Gui object), Win functions, Control functions

45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /docs/lib/WinGetList.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinGetList - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinGetList

15 | 16 |

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 |

Parameters

21 |
22 |
WinTitle, WinText, ExcludeTitle, ExcludeText
23 |
24 |

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 |
29 |
30 | 31 |

Return Value

32 |

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.

35 |

Windows are retrieved in order from topmost to bottommost (according to how they are stacked on the desktop).

36 | 37 |

Remarks

38 |

The ID of the window under the mouse cursor can be retrieved with MouseGetPos.

39 | 40 |

Related

41 |

WinGetCount, Win functions, Control functions

42 | 43 |

Examples

44 |
45 |

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 |
66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /docs/lib/WinGetMinMax.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinGetMinMax - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinGetMinMax

15 | 16 |

Returns a non-zero number if the specified window is maximized or minimized.

17 | 18 |
MinMax := WinGetMinMax(WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
WinTitle, WinText, ExcludeTitle, ExcludeText
23 |
24 |

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 |
29 |
30 | 31 |

Return Value

32 |

Type: Integer

33 |

This function returns a number indicating the current state of the specified window:

34 |
    35 |
  • -1: The window is minimized (WinRestore can unminimize it).
  • 36 |
  • 1: The window is maximized (WinRestore can unmaximize it).
  • 37 |
  • 0: The window is neither minimized nor maximized.
  • 38 |
39 | 40 |

Error Handling

41 |

A TargetError is thrown if the window could not be found.

42 | 43 |

Remarks

44 |

The ID of the window under the mouse cursor can be retrieved with MouseGetPos.

45 | 46 |

Related

47 |

WinMaximize, WinMinimize, Win functions, Control functions

48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /docs/lib/WinGetPID.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinGetPID - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinGetPID

15 | 16 |

Returns the Process ID number (PID) of the specified window.

17 | 18 |
PID := WinGetPID(WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
WinTitle, WinText, ExcludeTitle, ExcludeText
23 |
24 |

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 |
29 |
30 | 31 |

Return Value

32 |

Type: Integer

33 |

This function returns the Process ID (PID) of the specified window.

34 | 35 |

Error Handling

36 |

A TargetError is thrown if the window could not be found.

37 | 38 |

Remarks

39 |

The ID of the window under the mouse cursor can be retrieved with MouseGetPos.

40 | 41 |

Related

42 |

WinGetProcessName, WinGetProcessPath, Process functions, Win functions, Control functions

43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /docs/lib/WinGetPos.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinGetPos - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinGetPos

14 | 15 |

Retrieves the position and size of the specified window.

16 | 17 |
WinGetPos &OutX, &OutY, &OutWidth, &OutHeight, WinTitle, WinText, ExcludeTitle, ExcludeText
18 |

Parameters

19 |
20 | 21 |
&OutX, &OutY
22 |
23 |

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 |
26 | 27 |
&OutWidth, &OutHeight
28 |
29 |

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 |
32 | 33 |
WinTitle, WinText, ExcludeTitle, ExcludeText
34 |
35 |

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 |
40 | 41 |
42 | 43 |

Error Handling

44 |

A TargetError is thrown if the window could not be found.

45 | 46 |

Remarks

47 |

If WinTitle is "Program Manager", the function will retrieve the size of the desktop, which is usually the same as the current screen resolution.

48 |

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 |

Related

54 |

WinMove, WinGetClientPos, ControlGetPos, WinGetTitle, WinGetText, ControlGetText

55 |

Examples

56 |
57 |

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" H
60 |
61 | 62 |
63 |

Retrieves and reports the position of the active window.

64 |
WinGetPos &X, &Y,,, "A"
65 | MsgBox "The active window is at " X "," Y
66 |
67 | 68 |
69 |

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 |
76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /docs/lib/WinGetProcessName.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinGetProcessName - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinGetProcessName

15 | 16 |

Returns the name of the process that owns the specified window.

17 | 18 |
ProcessName := WinGetProcessName(WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
WinTitle, WinText, ExcludeTitle, ExcludeText
23 |
24 |

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 |
29 |
30 | 31 |

Return Value

32 |

Type: String

33 |

This function returns the name of the process that owns the specified window. For example: notepad.exe.

34 | 35 |

Error Handling

36 |

A TargetError is thrown if the window could not be found.

37 | 38 |

Remarks

39 |

The ID of the window under the mouse cursor can be retrieved with MouseGetPos.

40 | 41 |

Related

42 |

WinGetPID, WinGetProcessPath, Process functions, Win functions, Control functions

43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /docs/lib/WinGetProcessPath.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinGetProcessPath - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinGetProcessPath

15 | 16 |

Returns the full path and name of the process that owns the specified window.

17 | 18 |
ProcessPath := WinGetProcessPath(WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
WinTitle, WinText, ExcludeTitle, ExcludeText
23 |
24 |

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 |
29 |
30 | 31 |

Return Value

32 |

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 |

Error Handling

36 |

A TargetError is thrown if the window could not be found.

37 | 38 |

Remarks

39 |

The ID of the window under the mouse cursor can be retrieved with MouseGetPos.

40 | 41 |

Related

42 |

WinGetPID, WinGetProcessName, Process functions, Win functions, Control functions

43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /docs/lib/WinGetStyle.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinGetStyle / WinGetExStyle - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinGetStyle / WinGetExStyle

15 | 16 |

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 |

Parameters

22 |
23 |
WinTitle, WinText, ExcludeTitle, ExcludeText
24 |
25 |

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 |
30 |
31 | 32 |

Return Value

33 |

Type: Integer

34 |

These functions return the style or extended style (respectively) of the specified window.

35 | 36 |

Error Handling

37 |

A TargetError is thrown if the window could not be found.

38 | 39 |

Remarks

40 |

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 |

Related

44 |

WinSetStyle / WinSetExStyle, ControlGetStyle / ControlGetExStyle, styles table, Win functions, Control functions

45 | 46 |

Examples

47 |
48 |

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 |
53 | 54 |
55 |

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 |
60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /docs/lib/WinGetText.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinGetText - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinGetText

14 | 15 |

Retrieves the text from the specified window.

16 | 17 |
Text := WinGetText(WinTitle, WinText, ExcludeTitle, ExcludeText)
18 |

Parameters

19 |
20 | 21 |
WinTitle, WinText, ExcludeTitle, ExcludeText
22 |
23 |

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 |
28 | 29 |
30 | 31 |

Return Value

32 |

Type: String

33 |

This function returns the text of the specified window.

34 | 35 |

Error Handling

36 |

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 |

Remarks

40 |

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 := "".

44 |

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).

45 |

To retrieve an array of all controls in a window, use WinGetControls or WinGetControlsHwnd.

46 | 47 |

Related

48 |

ControlGetText, WinGetTitle, WinGetPos

49 |

Examples

50 |
51 |

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 |
56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /docs/lib/WinGetTitle.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinGetTitle - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinGetTitle

14 | 15 |

Retrieves the title of the specified window.

16 | 17 |
Title := WinGetTitle(WinTitle, WinText, ExcludeTitle, ExcludeText)
18 |

Parameters

19 |
20 | 21 |
WinTitle, WinText, ExcludeTitle, ExcludeText
22 |
23 |

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 |
28 | 29 |
30 | 31 |

Return Value

32 |

Type: String

33 |

This function returns the title of the specified window.

34 | 35 |

Error Handling

36 |

A TargetError is thrown if the window could not be found.

37 | 38 |

Remarks

39 |

To discover the name of the window that the mouse is currently hovering over, use MouseGetPos.

40 | 41 |

Related

42 |

WinSetTitle, WinGetClass, WinGetText, ControlGetText, WinGetPos, Win functions

43 |

Examples

44 |
45 |

Retrieves and reports the title of the active window.

46 |
MsgBox "The active window is '" WinGetTitle("A") "'."
47 |
48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /docs/lib/WinGetTransColor.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinGetTransColor - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinGetTransColor

15 | 16 |

Returns the color that is marked transparent in the specified window.

17 | 18 |
TransColor := WinGetTransColor(WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
WinTitle, WinText, ExcludeTitle, ExcludeText
23 |
24 |

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 |
29 |
30 | 31 |

Return Value

32 |

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 |
    36 |
  • The window has no transparency color.
  • 37 |
  • Under other conditions (caused by OS behavior) such as the window having been minimized, restored, and/or resized since it was made transparent.
  • 38 |
39 | 40 |

Error Handling

41 |

A TargetError is thrown if the window could not be found.

42 | 43 |

Remarks

44 |

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 |

Related

48 |

WinSetTransColor, WinGetTransparent, Win functions, Control functions

49 | 50 |

Examples

51 |
52 |

Retrieves the transparent color of a window under the mouse cursor.

53 |
MouseGetPos ,, &MouseWin
54 | TransColor := WinGetTransColor(MouseWin)
55 |
56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /docs/lib/WinGetTransparent.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinGetTransparent - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinGetTransparent

15 | 16 |

Returns the degree of transparency of the specified window.

17 | 18 |
TransDegree := WinGetTransparent(WinTitle, WinText, ExcludeTitle, ExcludeText)
19 | 20 |

Parameters

21 |
22 |
WinTitle, WinText, ExcludeTitle, ExcludeText
23 |
24 |

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 |
29 |
30 | 31 |

Return Value

32 |

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 |
    36 |
  • The window has no transparency level.
  • 37 |
  • Under other conditions (caused by OS behavior) such as the window having been minimized, restored, and/or resized since it was made transparent.
  • 38 |
39 | 40 |

Error Handling

41 |

A TargetError is thrown if the window could not be found.

42 | 43 |

Remarks

44 |

To set transparency, use WinSetTransparent.

45 |

The ID of the window under the mouse cursor can be retrieved with MouseGetPos.

46 | 47 |

Related

48 |

WinSetTransparent, WinGetTransColor, Win functions, Control functions

49 | 50 |

Examples

51 |
52 |

Retrieves the degree of transparency of the window under the mouse cursor.

53 |
MouseGetPos ,, &MouseWin
54 | TransDegree := WinGetTransparent(MouseWin)
55 |
56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /docs/lib/WinHide.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinHide - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinHide

14 | 15 |

Hides the specified window.

16 | 17 |
WinHide WinTitle, WinText, ExcludeTitle, ExcludeText
18 |

Parameters

19 |
20 | 21 |
WinTitle, WinText, ExcludeTitle, ExcludeText
22 |
23 |

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 |
28 | 29 |
30 | 31 |

Error Handling

32 |

A TargetError is thrown if the window could not be found, except if the group mode is used.

33 | 34 |

Remarks

35 |

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 |

Related

39 |

WinShow, SetTitleMatchMode, DetectHiddenWindows, Last Found Window, Win functions

40 |

Examples

41 |
42 |

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 |
50 |
51 |

Temporarily hides the taskbar.

52 |
WinHide "ahk_class Shell_TrayWnd"
53 | Sleep 1000
54 | WinShow "ahk_class Shell_TrayWnd"
55 |
56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /docs/lib/WinKill.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinKill - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinKill

14 | 15 |

Forces the specified window to close.

16 | 17 |
WinKill WinTitle, WinText, SecondsToWait, ExcludeTitle, ExcludeText
18 |

Parameters

19 |
20 | 21 |
WinTitle, WinText, ExcludeTitle, ExcludeText
22 |
23 |

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 |
28 | 29 |
SecondsToWait
30 |
31 |

Type: Integer or Float

32 |

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 |
34 | 35 |
36 | 37 |

Error Handling

38 |

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 |

Remarks

42 |

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 |

Related

48 |

WinClose, WinWaitClose, ProcessClose, WinActivate, SetTitleMatchMode, DetectHiddenWindows, Last Found Window, WinExist, WinActive, WinWaitActive, WinWait, GroupActivate

49 |

Examples

50 |
51 |

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 |
57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /docs/lib/WinMaximize.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinMaximize - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinMaximize

14 | 15 |

Enlarges the specified window to its maximum size.

16 | 17 |
WinMaximize WinTitle, WinText, ExcludeTitle, ExcludeText
18 |

Parameters

19 |
20 | 21 |
WinTitle, WinText, ExcludeTitle, ExcludeText
22 |
23 |

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 |
28 | 29 |
30 | 31 |

Error Handling

32 |

A TargetError is thrown if the window could not be found, except if the group mode is used.

33 | 34 |

Remarks

35 |

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_MAXIMIZE
38 |

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 |

Related

41 |

WinRestore, WinMinimize

42 |

Examples

43 |
44 |

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 |
49 | 50 |
51 |

Press a hotkey to maximize the active window.

52 |
^Up::WinMaximize "A"  ; Ctrl+Up
53 |
54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /docs/lib/WinMinimize.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinMinimize - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinMinimize

14 | 15 |

Collapses the specified window into a button on the task bar.

16 | 17 |
WinMinimize WinTitle, WinText, ExcludeTitle, ExcludeText
18 |

Parameters

19 |
20 | 21 |
WinTitle, WinText, ExcludeTitle, ExcludeText
22 |
23 |

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 |
28 | 29 |
30 | 31 |

Error Handling

32 |

A TargetError is thrown if the window could not be found, except if the group mode is used.

33 | 34 |

Remarks

35 |

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_MINIMIZE
39 |

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 |

Related

42 |

WinRestore, WinMaximize, WinMinimizeAll

43 |

Examples

44 |
45 |

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 |
50 | 51 |
52 |

Press a hotkey to minimize the active window.

53 |
^Down::WinMinimize "A"  ; Ctrl+Down
54 |
55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /docs/lib/WinMinimizeAll.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinMinimizeAll / WinMinimizeAllUndo - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinMinimizeAll / WinMinimizeAllUndo

14 | 15 |

Minimizes or unminimizes all windows.

16 | 17 |
WinMinimizeAll
18 | WinMinimizeAllUndo
19 |

On most systems, this is equivalent to Explorer's Win+M and Win+D hotkeys.

20 |

Related

21 |

WinMinimize, GroupAdd

22 |

Examples

23 |
24 |

Minimizes all windows for 1 second and unminimizes them.

25 |
WinMinimizeAll
26 | Sleep 1000
27 | WinMinimizeAllUndo
28 |
29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /docs/lib/WinMove.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinMove - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinMove

14 | 15 |

Changes the position and/or size of the specified window.

16 | 17 |
WinMove X, Y, Width, Height, WinTitle, WinText, ExcludeTitle, ExcludeText
18 |

Parameters

19 |
20 |
X, Y
21 |
22 |

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 |
25 | 26 |
Width, Height
27 |
28 |

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 |
31 | 32 |
WinTitle, WinText, ExcludeTitle, ExcludeText
33 |
34 |

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 |
39 |
40 | 41 |

Error Handling

42 |

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 |

Remarks

46 |

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 |

Related

54 |

ControlMove, WinGetPos, WinHide, WinMinimize, WinMaximize, Win functions

55 | 56 |

Examples

57 |
58 |

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 |
63 | 64 |
65 |

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 |
73 | 74 |
75 |

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 |
84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /docs/lib/WinMoveBottom.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinMoveBottom - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinMoveBottom

15 | 16 |

Sends the specified window to the bottom of stack; that is, beneath all other windows.

17 | 18 |
WinMoveBottom WinTitle, WinText, ExcludeTitle, ExcludeText
19 | 20 |

Parameters

21 |
22 |
WinTitle, WinText, ExcludeTitle, ExcludeText
23 |
24 |

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 |
29 |
30 | 31 |

Error Handling

32 |

A TargetError is thrown if the window could not be found.

33 |

An OSError may be thrown on failure.

34 | 35 |

Remarks

36 |

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 |

Related

40 |

WinMoveTop, WinSetAlwaysOnTop, Win functions, Control functions

41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /docs/lib/WinMoveTop.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinMoveTop - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinMoveTop

15 | 16 |

Brings the specified window to the top of the stack without explicitly activating it.

17 | 18 |
WinMoveTop WinTitle, WinText, ExcludeTitle, ExcludeText
19 | 20 |

Parameters

21 |
22 |
WinTitle, WinText, ExcludeTitle, ExcludeText
23 |
24 |

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 |
29 |
30 | 31 |

Error Handling

32 |

A TargetError is thrown if the window could not be found.

33 |

An OSError may be thrown on failure.

34 | 35 |

Remarks

36 |

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 |

Related

40 |

WinMoveBottom, WinSetAlwaysOnTop, Win functions, Control functions

41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /docs/lib/WinRedraw.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinRedraw - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinRedraw

15 | 16 |

Redraws the specified window.

17 | 18 |
WinRedraw WinTitle, WinText, ExcludeTitle, ExcludeText
19 | 20 |

Parameters

21 |
22 |
WinTitle, WinText, ExcludeTitle, ExcludeText
23 |
24 |

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 |
29 |
30 | 31 |

Error Handling

32 |

A TargetError is thrown if the window could not be found.

33 | 34 |

Remarks

35 |

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 |

Related

39 |

WinMoveBottom, WinSetAlwaysOnTop, Win functions, Control functions

40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /docs/lib/WinRestore.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinRestore - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinRestore

14 | 15 |

Unminimizes or unmaximizes the specified window if it is minimized or maximized.

16 | 17 |
WinRestore WinTitle, WinText, ExcludeTitle, ExcludeText
18 |

Parameters

19 |
20 | 21 |
WinTitle, WinText, ExcludeTitle, ExcludeText
22 |
23 |

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 |
28 | 29 |
30 | 31 |

Error Handling

32 |

A TargetError is thrown if the window could not be found, except if the group mode is used.

33 | 34 |

Remarks

35 |

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_RESTORE
37 |

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 |

Related

40 |

WinMinimize, WinMaximize

41 |

Examples

42 |
43 |

Unminimizes or unmaximizes Notepad if it is minimized or maximized.

44 |
WinRestore "Untitled - Notepad"
45 |
46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /docs/lib/WinSetAlwaysOnTop.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinSetAlwaysOnTop - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinSetAlwaysOnTop

15 | 16 |

Makes the specified window stay on top of all other windows (except other always-on-top windows).

17 | 18 |
WinSetAlwaysOnTop NewSetting, WinTitle, WinText, ExcludeTitle, ExcludeText
19 | 20 |

Parameters

21 |
22 |
NewSetting
23 |
24 |

Type: Integer

25 |

If omitted, it defaults to 1. Otherwise, specify one of the following values:

26 |
    27 |
  • 1 or True turns on the setting
  • 28 |
  • 0 or False turns off the setting
  • 29 |
  • -1 toggles the setting (sets it to the opposite of its current state)
  • 30 |
31 |
32 |
WinTitle, WinText, ExcludeTitle, ExcludeText
33 |
34 |

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 |
39 |
40 | 41 |

Error Handling

42 |

A TargetError is thrown if the window could not be found.

43 |

An OSError may be thrown on failure.

44 | 45 |

Remarks

46 |

The ID of the window under the mouse cursor can be retrieved with MouseGetPos.

47 | 48 |

Related

49 |

WinMoveTop, WinMoveBottom, Win functions, Control functions

50 | 51 |

Examples

52 |
53 |

Toggles the always-on-top status of the calculator.

54 |
WinSetAlwaysOnTop -1, "Calculator"
55 |
56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /docs/lib/WinSetEnabled.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinSetEnabled - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinSetEnabled

15 | 16 |

Enables or disables the specified window.

17 | 18 |
WinSetEnabled NewSetting , WinTitle, WinText, ExcludeTitle, ExcludeText
19 | 20 |

Parameters

21 |
22 |
NewSetting
23 |
24 |

Type: Integer

25 |

One of the following values:

26 |
    27 |
  • 1 or True turns on the setting
  • 28 |
  • 0 or False turns off the setting
  • 29 |
  • -1 toggles the setting (sets it to the opposite of its current state)
  • 30 |
31 |
32 |
WinTitle, WinText, ExcludeTitle, ExcludeText
33 |
34 |

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 |
39 |
40 | 41 |

Error Handling

42 |

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 |

Remarks

46 |

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 |

Related

51 |

ControlSetEnabled, Win functions, Control functions

52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /docs/lib/WinSetRegion.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinSetRegion - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinSetRegion

15 | 16 |

Changes the shape of the specified window to be the specified rectangle, ellipse, or polygon.

17 | 18 |
WinSetRegion Options, WinTitle, WinText, ExcludeTitle, ExcludeText
19 | 20 |

Parameters

21 |
22 |
Options
23 |
24 |

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.

27 |

Hn: Height of rectangle or ellipse. For example: h200.

28 |

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.

29 |

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.

31 |

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".

32 |

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 |
34 |
WinTitle, WinText, ExcludeTitle, ExcludeText
35 |
36 |

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 |
41 |
42 | 43 |

Error Handling

44 |

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 |

Remarks

49 |

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 |

Related

68 |

Win functions, Control functions

69 | 70 |

Examples

71 |
72 |

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 |
75 | 76 |
77 |

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 |
80 | 81 |
82 |

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 |
85 | 86 |
87 |

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 |
90 | 91 |
92 |

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 |
95 | 96 |
97 |

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 |
100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /docs/lib/WinSetStyle.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinSetStyle / WinSetExStyle - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinSetStyle / WinSetExStyle

15 | 16 |

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, ExcludeText
20 | 21 |

Parameters

22 |
23 |
Value
24 |
25 |

Type: Integer or String

26 |

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 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 |
OperationPrefixExampleFormula
Add+"+0x80"NewStyle := CurrentStyle | Value
Remove-"-0x80"NewStyle := CurrentStyle & ~Value
Toggle^"^0x80"NewStyle := CurrentStyle ^ Value
54 |

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.

56 |
57 |
WinTitle, WinText, ExcludeTitle, ExcludeText
58 |
59 |

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 |
64 |
65 | 66 |

Error Handling

67 |

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 |

Remarks

71 |

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 |

Related

76 |

WinGetStyle / WinGetExStyle, ControlSetStyle / ControlSetExStyle, styles table, Win functions, Control functions

77 | 78 |

Examples

79 |
80 |

Removes the active window's title bar (WS_CAPTION).

81 |
WinSetStyle "-0xC00000", "A"
82 |
83 | 84 |
85 |

Toggles the WS_EX_TOOLWINDOW attribute, which removes/adds Notepad from the alt-tab list.

86 |
WinSetExStyle "^0x80", "ahk_class Notepad"
87 |
88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /docs/lib/WinSetTitle.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinSetTitle - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinSetTitle

14 | 15 |

Changes the title of the specified window.

16 | 17 |
WinSetTitle NewTitle , WinTitle, WinText, ExcludeTitle, ExcludeText
18 |

Parameters

19 |
20 | 21 |
NewTitle
22 |
23 |

Type: String

24 |

The new title for the window. If this is the only parameter given, the Last Found Window will be used.

25 |
26 | 27 |
WinTitle, WinText, ExcludeTitle, ExcludeText
28 |
29 |

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 |
34 | 35 |
36 | 37 |

Error Handling

38 |

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 |

Remarks

42 |

A change to a window's title might be merely temporary if the application that owns the window frequently changes the title.

43 | 44 |

Related

45 |

WinMove, WinGetTitle, WinGetText, ControlGetText, WinGetPos, Win functions

46 |

Examples

47 |
48 |

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 |
51 | 52 |
53 |

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 |
58 | 59 |
60 |

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 |
65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /docs/lib/WinSetTransColor.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinSetTransColor - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinSetTransColor

15 | 16 |

Makes all pixels of the chosen color invisible inside the specified window.

17 | 18 |
WinSetTransColor Color , WinTitle, WinText, ExcludeTitle, ExcludeText
19 | 20 |

Parameters

21 |
22 |
Color
23 |
24 |

Type: String or Integer

25 |

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".

26 |

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.

27 |

"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).

28 |
29 |
WinTitle, WinText, ExcludeTitle, ExcludeText
30 |
31 |

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 |
36 |
37 | 38 |

Error Handling

39 |

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 |

Remarks

43 |

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 |

Related

49 |

WinSetTransparent, Win functions, Control functions

50 | 51 |

Examples

52 |
53 |

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 |
56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /docs/lib/WinSetTransparent.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinSetTransparent - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

WinSetTransparent

15 | 16 |

Makes the specified window semi-transparent.

17 | 18 |
WinSetTransparent N, WinTitle, WinText, ExcludeTitle, ExcludeText
19 | 20 |

Parameters

21 |
22 |
N
23 |
24 |

Type: Integer or String

25 |

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).

27 |
28 |
WinTitle, WinText, ExcludeTitle, ExcludeText
29 |
30 |

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 |
35 |
36 | 37 |

Error Handling

38 |

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 |

Remarks

42 |

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.

43 |

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 |

Related

47 |

WinSetTransColor, Win functions, Control functions

48 | 49 |

Examples

50 |
51 |

Makes Notepad a little bit transparent.

52 |
WinSetTransparent 200, "Untitled - Notepad"
53 |
54 | 55 |
56 |

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 |
60 | 61 |
62 |

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 |
72 | 73 |
74 |

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 |
98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /docs/lib/WinShow.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinShow - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinShow

14 | 15 |

Unhides the specified window.

16 | 17 |
WinShow WinTitle, WinText, ExcludeTitle, ExcludeText
18 |

Parameters

19 |
20 | 21 |
WinTitle, WinText, ExcludeTitle, ExcludeText
22 |
23 |

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 |
28 | 29 |
30 | 31 |

Error Handling

32 |

A TargetError is thrown if the window could not be found, except if the group mode is used.

33 | 34 |

Remarks

35 |

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 |

Related

38 |

WinHide, SetTitleMatchMode, DetectHiddenWindows, Last Found Window

39 |

Examples

40 |
41 |

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 |
49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /docs/lib/WinWait.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinWait - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinWait

14 | 15 |

Waits until the specified window exists.

16 | 17 |
HWND := WinWait(WinTitle, WinText, Timeout, ExcludeTitle, ExcludeText)
18 |

Parameters

19 |
20 | 21 |
WinTitle, WinText, ExcludeTitle, ExcludeText
22 |
23 |

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 |
28 | 29 |
Timeout
30 |
31 |

Type: Integer or Float

32 |

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 |
34 | 35 |
36 | 37 |

Return Value

38 |

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 |

Remarks

42 |

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 |

Related

50 |

WinWaitActive, WinWaitClose, WinExist, WinActive, ProcessWait, SetTitleMatchMode, DetectHiddenWindows

51 |

Examples

52 |
53 |

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 |
61 | 62 | 63 | -------------------------------------------------------------------------------- /docs/lib/WinWaitActive.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinWaitActive / WinWaitNotActive - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinWaitActive / WinWaitNotActive

14 | 15 |

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 |

Parameters

20 |
21 | 22 |
WinTitle, WinText, ExcludeTitle, ExcludeText
23 |
24 |

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 |
29 | 30 |
Timeout
31 |
32 |

Type: Integer or Float

33 |

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 |
35 | 36 |
37 | 38 |

Return Value

39 |

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 |

Remarks

44 |

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:

46 |
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 |

Related

52 |

WinWait, WinWaitClose, WinExist, WinActive, SetTitleMatchMode, DetectHiddenWindows

53 |

Examples

54 |
55 |

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 |
63 | 64 | 65 | -------------------------------------------------------------------------------- /docs/lib/WinWaitClose.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinWaitClose - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinWaitClose

14 | 15 |

Waits until no matching windows can be found.

16 | 17 |
Boolean := WinWaitClose(WinTitle, WinText, Timeout, ExcludeTitle, ExcludeText)
18 |

Parameters

19 |
20 | 21 |
WinTitle, WinText, ExcludeTitle, ExcludeText
22 |
23 |

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 |
28 | 29 |
Timeout
30 |
31 |

Type: Integer or Float

32 |

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 |
34 | 35 |
36 | 37 |

Return Value

38 |

Type: Integer (boolean)

39 |

This function returns 0 (false) if the function timed out or 1 (true) otherwise.

40 | 41 |

Remarks

42 |

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:

45 |
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 |

Related

59 |

WinClose, WinWait, WinWaitActive, WinExist, WinActive, ProcessWaitClose, SetTitleMatchMode, DetectHiddenWindows

60 |

Examples

61 |
62 |

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 |
68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /docs/lib/_ClipboardTimeout.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #ClipboardTimeout - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

#ClipboardTimeout

14 | 15 |

Changes how long the script keeps trying to access the clipboard when the first attempt fails.

16 | 17 |
#ClipboardTimeout Milliseconds
18 |

Parameters

19 |
20 | 21 |
Milliseconds
22 |
23 |

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 |
26 | 27 |
28 |

Remarks

29 |

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".

32 |

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 |

Related

36 |

A_Clipboard, Thread

37 |

Examples

38 |
39 |

Causes the script to wait 2 seconds instead of 1 second before giving up accessing the clipboard and displaying an error message.

40 |
#ClipboardTimeout 2000
41 |
42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /docs/lib/_DllLoad.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #DllLoad - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

#DllLoad

15 | 16 |

Loads a DLL or EXE file before the script starts executing.

17 | 18 |
#DllLoad FileOrDirName
19 |

Parameters

20 |
21 | 22 |
FileOrDirName
23 |
24 |

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 (`;).

26 |

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.

27 |

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 |
32 |
33 |

Remarks

34 |

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:

36 |
#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 |

Related

42 |

DllCall

43 |

Examples

44 |
45 |

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 |
48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /docs/lib/_ErrorStdOut.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #ErrorStdOut - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

#ErrorStdOut

14 | 15 |

Sends any syntax error that prevents a script from launching to the standard error stream (stderr) rather than displaying a dialog.

16 | 17 |
#ErrorStdOut Encoding
18 | 19 |

Parameters

20 |
21 |
Encoding
22 |
23 |

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.

25 |

Note: This parameter is not an expression, but can be enclosed in quote marks (either 'single' or "double").

26 |
27 |
28 | 29 |

Remarks

30 |

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 |clip
38 |

Note: 2>&1 causes stderr to be redirected to stdout, while 2>Filename redirects only stderr to a file.

39 |

Like other directives, #ErrorStdOut cannot be executed conditionally.

40 | 41 |

Instructions for specific editors

42 |

EditPlus:

43 |
    44 |
  1. From the menu bar, select Tools > Configure User Tools.
  2. 45 |
  3. Press button: Add Tool > Program
  4. 46 |
  5. Menu Text: Your choice
  6. 47 |
  7. Command: C:\Program Files\AutoHotkey\AutoHotkey.exe
  8. 48 |
  9. Argument: /ErrorStdOut "$(FilePath)"
  10. 49 |
  11. Initial directory: $(FileDir)
  12. 50 |
  13. Capture output: Yes
  14. 51 |
52 |

TextPad:

53 |
    54 |
  1. From the menu bar, select Configure > Preferences.
  2. 55 |
  3. Expand the Tools entry.
  4. 56 |
  5. Press the Add button and select "Program".
  6. 57 |
  7. Copy and paste (adjust to your path): C:\Windows\System32\cmd.exe -- then press OK.
  8. 58 |
  9. Triple-click the newly added item (cmd.exe) in the ListBox and rename it to your choice (e.g. Launch Script).
  10. 59 |
  11. Press Apply.
  12. 60 |
  13. Select the new item in the tree at the left and enter the following information:
  14. 61 |
  15. Command (should already be filled in): cmd.exe (or the full path to it)
  16. 62 |
  17. Parameters (adjust to your path, if necessary): /c ""C:\Program Files\AutoHotkey\AutoHotkey.exe" /ErrorStdOut "$File""
  18. 63 |
  19. Initial folder: $FileDir
  20. 64 |
  21. Check the following boxes: 1) Run minimized; 2) Capture output.
  22. 65 |
  23. Press OK. The newly added item should now exist in the Tools menu.
  24. 66 |
67 | 68 |

Related

69 |

FileAppend (because it can also send text to stderr or stdout)

70 |

Examples

71 |
72 |

Sends any syntax error that prevents the script from launching to stderr rather than displaying a dialog.

73 |
#ErrorStdOut
74 |
75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /docs/lib/_HotIf.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #HotIf - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |

#HotIf

16 | 17 |

Creates context-sensitive hotkeys and hotstrings. They perform a different action (or none at all) depending on any condition (an expression).

18 | 19 |
#HotIf Expression
20 |

Parameters

21 |
22 | 23 |
Expression
24 |
25 |

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 |
28 | 29 |
30 | 31 |

Basic Operation

32 |

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 " MyWindowTitle
37 |

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.

40 |

To turn off context sensitivity, specify #HotIf without any expression. For example:

41 |
#HotIf
42 |

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 | #HotIf
48 | 49 |

Variants (Duplicates)

50 |

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.

59 | 60 |

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 |

Expression Evaluation

71 |

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.

74 |

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 |
    77 |
  • Keyboard or mouse input is typically buffered (delayed) until expression evaluation completes or times out.
  • 78 |
  • Expression evaluation can only be performed by the script's main thread (at the OS level, not a quasi-thread), not directly by the keyboard/mouse hook. If the script is busy or unresponsive, such as if a FileCopy is in progress, expression evaluation is delayed and may time out.
  • 79 |
  • If the system-defined timeout is reached, the system may stop notifying the script of keyboard or mouse input (see #HotIfTimeout for details).
  • 80 |
  • Sending keystrokes or mouse clicks while the expression is being evaluated (such as from a function which it calls) may cause complications and should be avoided.
  • 81 |
82 |

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 |

Optimization

86 |

#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 |
    88 |
  • The expression must contain exactly one call to WinExist or WinActive.
  • 89 |
  • Each parameter must be a single quoted string, and no more than two parameters may be used.
  • 90 |
  • The result may be inverted with not or !, but no other operators may be used.
  • 91 |
  • Whitespace and parentheses are fully handled when the expression is pre-compiled and therefore do not affect this optimization.
  • 92 |
93 |

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 |
    106 |
  • Use HotIfWin...(MyTitleVar) to set the criteria and Hotkey(KeyName, Action) or Hotstring(String, Replacement) to create the hotkey or hotstring variant.
  • 107 |
  • Use a constant expression such as #HotIf WinActive("ahk_group MyGroup") and define the window group with GroupAdd "MyGroup", MyTitleVar elsewhere in the script.
  • 108 |
109 | 110 |

General Remarks

111 |

#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.

112 |

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 |

Related

119 |

#HotIfTimeout may be used to override the default timeout value.

120 |

Hotkey function, Hotkeys, Hotstring function, Hotstrings, Suspend, WinActive, WinExist, SetTitleMatchMode, DetectHiddenWindows

121 | 122 |

Examples

123 |
124 |

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 |
132 | 133 |
134 |

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 |
146 | 147 |
148 |

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 |
163 | 164 |
165 |

Context-insensitive Hotkey.

166 |
167 | #HotIf
168 | Esc::ExitApp
169 | 
170 |
171 | 172 |
173 |

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 |
189 | 190 | 191 | 192 | -------------------------------------------------------------------------------- /docs/lib/_HotIfTimeout.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #HotIfTimeout - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |

#HotIfTimeout

16 | 17 |

Sets the maximum time that may be spent evaluating a single #HotIf expression.

18 | 19 |
#HotIfTimeout Timeout
20 |

Parameters

21 |
22 | 23 |
Timeout
24 |
25 |

Type: Integer

26 |

The timeout value to apply globally, in milliseconds.

27 |
28 | 29 |
30 | 31 |

Remarks

32 |

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 |

Related

41 |

#HotIf

42 |

Examples

43 |
44 |

Sets the #HotIf timeout to 10 ms instead of 1000 ms.

45 |
#HotIfTimeout 10
46 |
47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /docs/lib/_Hotstring.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #Hotstring - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

#Hotstring

14 | 15 |

Changes hotstring options or ending characters.

16 | 17 |
#Hotstring NoMouse
18 | #Hotstring EndChars NewChars
19 | #Hotstring NewOptions
20 |

Parameters

21 |
22 | 23 |
NoMouse
24 |
25 |

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.

27 |
28 | 29 |
EndChars NewChars
30 |
31 |

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`t
34 |

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 |
38 | 39 |
NewOptions
40 |
41 |

Type: String

42 |

Specify new options as described in Hotstring Options. For example: #Hotstring r s k0 c0.

43 |

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 |
52 | 53 |
54 | 55 |

Remarks

56 |

Like other directives, #Hotstring cannot be executed conditionally.

57 | 58 |

Related

59 |

Hotstrings

60 |

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 | #Include / #IncludeAgain - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

#Include / #IncludeAgain

14 | 15 |

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 FileOrDirName
20 |

Parameters

21 |
22 | 23 |
FileOrDirName
24 |
25 |

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 (`;).

27 |

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.

28 |

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.

30 |

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 |
33 | 34 |
<LibName>
35 |
36 |

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.

38 |

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.

39 |
40 | 41 |
42 |

Remarks

43 |

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.

46 |

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 |

Related

53 |

Script Library Folders, Functions, FileInstall

54 |

Examples

55 |
56 |

Includes the contents of the specified file into the current script.

57 |
#Include "C:\My Documents\Scripts\Utility Subroutines.ahk"
58 |
59 | 60 |
61 |

Changes the working directory for subsequent #Includes and FileInstalls.

62 |
#Include "%A_ScriptDir%"
63 |
64 | 65 |
66 |

Same as above but for an explicitly named directory.

67 |
#Include "C:\My Scripts"
68 |
69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /docs/lib/_InputLevel.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #InputLevel - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

#InputLevel

14 |

Controls which artificial keyboard and mouse events are ignored by hotkeys and hotstrings.

15 |
#InputLevel Level
16 | 17 |

Parameters

18 |
19 | 20 |
Level
21 |
22 |

Type: Integer

23 |

If omitted, it defaults to 0. Otherwise, specify an integer between 0 and 100.

24 |
25 | 26 |
27 | 28 |

General Remarks

29 |

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"

33 |

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.

35 |

Like other directives, #InputLevel cannot be executed conditionally.

36 | 37 |

Related

38 |

SendLevel, Hotkeys, Hotstrings

39 | 40 |

Examples

41 |
42 |

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.

43 |
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 |
53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /docs/lib/_MaxThreads.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #MaxThreads - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

#MaxThreads

14 | 15 |

Sets the maximum number of simultaneous threads.

16 | 17 |
#MaxThreads Value
18 |

Parameters

19 |
20 | 21 |
Value
22 |
23 |

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 |
26 | 27 |
28 |

Remarks

29 |

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 |

Related

36 |

#MaxThreadsPerHotkey, Threads, A_MaxHotkeysPerInterval, ListHotkeys

37 |

Examples

38 |
39 |

Allows a maximum of 2 instead of 10 simultaneous threads.

40 |
#MaxThreads 2
41 |
42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /docs/lib/_MaxThreadsBuffer.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #MaxThreadsBuffer - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

#MaxThreadsBuffer

14 | 15 |

Causes some or all hotkeys to buffer rather than ignore keypresses when their #MaxThreadsPerHotkey limit has been reached.

16 | 17 |
#MaxThreadsBuffer Setting
18 |

Parameters

19 |
20 | 21 |
Setting
22 |
23 |

Type: String or Integer

24 |

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.

26 |

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 |
28 | 29 |
30 | 31 |

Remarks

32 |

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 |

Related

38 |

#MaxThreads, #MaxThreadsPerHotkey, Critical, Thread (function), Threads, Hotkey, A_MaxHotkeysPerInterval, ListHotkeys

39 |

Examples

40 |
41 |

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 |
48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /docs/lib/_MaxThreadsPerHotkey.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #MaxThreadsPerHotkey - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

#MaxThreadsPerHotkey

14 | 15 |

Sets the maximum number of simultaneous threads per hotkey or hotstring.

16 | 17 |
#MaxThreadsPerHotkey Value
18 |

Parameters

19 |
20 | 21 |
Value
22 |
23 |

Type: Integer

24 |

The maximum number of threads that can be launched for a given hotkey/hotstring subroutine (limit 255).

25 |
26 | 27 |
28 |

Remarks

29 |

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 |

Related

35 |

#MaxThreads, #MaxThreadsBuffer, Critical, Threads, Hotkey, A_MaxHotkeysPerInterval, ListHotkeys

36 |

Examples

37 |
38 |

Allows a maximum of 3 simultaneous threads instead of 1 per hotkey or hotstring.

39 |
#MaxThreadsPerHotkey 3
40 |
41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /docs/lib/_NoTrayIcon.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #NoTrayIcon - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

#NoTrayIcon

14 | 15 |

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.

20 |

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.

21 |

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 |

Related

25 |

Tray Icon, TraySetIcon, A_IconHidden, A_IconTip, ExitApp

26 |

Examples

27 |
28 |

Causes the script to launch without a tray icon.

29 |
#NoTrayIcon
30 |
31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /docs/lib/_Requires.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #Requires - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

#Requires

14 | 15 |

Displays an error and quits if a version requirement is not met.

16 | 17 |
#Requires Requirement
18 | 19 |

Parameters

20 |
21 |
Requirement
22 |
23 |

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 |
    27 |
  • An optional letter "v" followed by a version number. A_AhkVersion is required to be greater than or equal to this version, but less than the next major version.
  • 28 |
  • One of <, <=, >, >= 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.
  • 29 |
  • One of the following words to restrict the type of executable (EXE) which can run the script: "32-bit", "64-bit".
  • 30 |
31 |
32 |
33 | 34 |

Error Message

35 |

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 |

Remarks

42 |

As the launcher enables the use of v1 and v2 scripts on one system, it is recommended that you add at least #Requires AutoHotkey v1 for v1 scripts and #Requires AutoHotkey v2 for v2 scripts. This will ensure that the correct version is used to run the script.

43 |

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.

44 |

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.

45 |

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.

46 |

Version strings are compared as a series of dot-delimited components, optionally followed by a hyphen and pre-release identifier(s).

47 |
    48 |
  • Numeric components are compared numerically. For example, v1.01 = v1.1, but a20 > a112.
  • 49 |
  • Numeric components are always considered lower than non-numeric components in the same position.
  • 50 |
  • Any missing dot-delimited components are assumed to be zero. For example, v1.1.33-alpha is the same as v1.1.33.00-alpha.0.
  • 51 |
  • Non-numeric components are compared alphabetically, and are case-sensitive.
  • 52 |
  • Pre-release versions are considered lower than standard releases. For example, a script that #Requires AutoHotkey v2 will not run on v2.0-a112. To permit pre-release versions, include a hyphen suffix. For example: v2.0-.
  • 53 |
  • Any suffix beginning with "+" is ignored.
  • 54 |
55 |

A trailing "+" is sufficient to indicate to the reader that later versions are acceptable, but is not required.

56 |

Like other directives, #Requires cannot be executed conditionally.

57 | 58 |

Related

59 |

VerCompare, #ErrorStdOut

60 | 61 |

Examples

62 |
63 |

Causes the script to run only on v2.0, including alpha releases.

64 |
#Requires AutoHotkey v2.0-a
65 | MsgBox "This script will run only on v2.0, including alpha releases."
66 |
67 | 68 |
69 |

Causes the script to run only on v2.0, including pre-release versions.

70 |
#Requires AutoHotkey >=2.0- <2.1
71 |
72 | 73 |
74 |

Causes the script to run only with a 64-bit interpreter (EXE).

75 |
#Requires AutoHotkey 64-bit
76 |
77 | 78 |
79 |

Causes the script to run only with a 64-bit interpreter (EXE) version 2.0-rc.2 or later.

80 |
#Requires AutoHotkey v2.0-rc.2 64-bit
81 |
82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /docs/lib/_SingleInstance.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #SingleInstance - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

#SingleInstance

14 | 15 |

Determines whether a script is allowed to run again when it is already running.

16 | 17 |
#SingleInstance ForceIgnorePromptOff
18 |

Parameters

19 |
20 | 21 |
ForceIgnorePromptOff
22 |
23 |

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 |
30 | 31 |
32 |

Remarks

33 |

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 |

Limitations

38 |

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 |
    40 |
  • The title of its main window has been changed.
  • 41 |
  • It is running on a different version of AutoHotkey.
  • 42 |
  • Its main window is no longer top-level, such as if the script has used SetParent to change its parent to something other than NULL (0).
  • 43 |
44 |

At most one previous instance is detected and sent a message asking it to close. Therefore, the following additional limitations also apply:

45 |
    46 |
  • If there are multiple instances (such as if previous instances of the script used the #SingleInstance Off mode), the topmost matching instance is sent the message, and other instances are not considered.
  • 47 |
  • If the previous instance is running at a higher integrity level than the new instance (where running as administrator > running with UI access > normal), it cannot be closed due to security restrictions.
  • 48 |
49 |

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 |

Related

52 |

Reload

53 |

Examples

54 |
55 |

Skips the dialog box and replaces the old instance automatically.

56 |
#SingleInstance Force
57 |
58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /docs/lib/_SuspendExempt.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #SuspendExempt - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

#SuspendExempt

15 | 16 |

Exempts subsequent hotkeys and hotstrings from suspension.

17 | 18 |
#SuspendExempt Setting
19 |

Parameters

20 |
21 | 22 |
Setting
23 |
24 |

Type: String or Integer

25 |

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 |
29 | 30 |
31 |

Remarks

32 |

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 |

Related

38 |

Suspend, Hotkeys, Hotstrings

39 | 40 |

Examples

41 |
42 |

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 |
49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /docs/lib/_UseHook.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #UseHook - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

#UseHook

14 | 15 |

Forces the use of the hook to implement all or some keyboard hotkeys.

16 | 17 |
#UseHook Setting
18 |

Parameters

19 |
20 | 21 |
Setting
22 |
23 |

Type: String or Integer

24 |

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).

26 |

False or 0: Hotkeys will be implemented using the default method (RegisterHotkey() if possible; otherwise, the keyboard hook).

27 |
28 | 29 |
30 | 31 |

Remarks

32 |

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.

35 |

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 |

Related

40 |

InstallKeybdHook, InstallMouseHook, ListHotkeys, #InputLevel

41 |

Examples

42 |
43 |

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 |
50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /docs/lib/_Warn.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #Warn - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

#Warn

14 | 15 |

Enables or disables warnings for specific conditions which may indicate an error, such as a typo or missing "global" declaration.

16 | 17 |
#Warn WarningType, WarningMode
18 | 19 |

Parameters

20 |
21 | 22 |
WarningType
23 |
24 |

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 |
    29 |
  • As the target of a direct, non-dynamic assignment such as MyVar := "".
  • 30 |
  • Used with the reference operator (e.g. &MyVar).
  • 31 |
  • Passed directly to IsSet (e.g. IsSet(MyVar)).
  • 32 |
33 |

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.

34 |

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.

44 |

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.

45 |

All: Apply the given WarningMode to all supported warning types.

46 |
47 | 48 |
WarningMode
49 |
50 |

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 |
58 | 59 |
60 |

Remarks

61 |

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 |

Related

68 |

Local and Global Variables

69 |

Examples

70 |
71 |

Disables all warnings. Not recommended.

72 |
#Warn All, Off
73 |
74 | 75 |
76 |

Enables every type of warning and shows each warning in a message box.

77 |
#Warn
78 |
79 | 80 |
81 |

Sends a warning to OutputDebug for each undeclared local variable which has the same name as a global variable.

82 |
#Warn LocalSameAsGlobal, OutputDebug
83 |
84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /docs/lib/_WinActivateForce.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #WinActivateForce - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

#WinActivateForce

14 | 15 |

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 |

Remarks

22 |

Like other directives, #WinActivateForce cannot be executed conditionally.

23 | 24 |

Related

25 |

WinActivate, WinActivateBottom, GroupActivate

26 |

Examples

27 |
28 |

Enables the forceful method of activating a window.

29 |
#WinActivateForce
30 |
31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /docs/lib/index.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Alphabetical Function Index | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 13 | 14 | 15 | 16 |

Alphabetical Function Index

17 |

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 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 494 | 495 | 496 | 497 | 498 | 499 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 | 520 | 521 | 522 | 523 | 524 | 525 | 526 | 527 | 528 | 529 | 530 | 531 | 532 | 533 | 534 | 535 | 536 | 537 | 538 | 539 | 540 | 541 | 542 | 543 | 544 | 545 | 546 | 547 | 548 | 549 | 550 | 551 | 552 | 553 | 554 | 555 | 556 | 557 | 558 | 559 | 560 | 561 | 562 | 563 | 564 | 565 | 566 | 567 | 568 | 569 | 570 | 571 | 572 | 573 | 574 | 575 | 576 | 577 | 578 | 579 | 580 | 581 | 582 | 583 | 584 | 585 | 586 | 587 | 588 | 589 | 590 | 591 | 592 | 593 | 594 | 595 | 596 | 597 | 598 | 599 | 600 | 601 | 602 | 603 | 604 | 605 | 606 | 607 | 608 | 609 | 610 | 611 | 612 | 613 | 614 | 615 | 616 | 617 | 618 | 619 | 620 | 621 | 622 | 625 | 626 | 627 | 628 | 629 | 630 | 631 | 632 | 633 | 634 | 635 | 636 | 637 | 638 | 639 | 640 | 641 | 642 | 643 | 644 | 645 | 646 | 647 | 648 | 649 | 650 | 651 | 652 | 653 | 654 | 655 | 656 | 657 | 658 | 659 | 660 | 661 | 662 | 663 | 664 | 665 | 666 | 667 | 668 | 669 | 670 | 671 | 672 | 673 | 674 | 675 | 676 | 677 | 678 | 679 | 680 | 681 | 682 | 683 | 684 | 685 | 686 | 687 | 688 | 689 | 690 | 691 | 692 | 693 | 694 | 695 | 696 | 697 | 698 | 699 | 700 | 701 | 702 | 703 | 704 | 705 | 706 | 707 | 708 | 709 | 710 | 711 | 712 | 713 | 714 | 715 | 716 | 717 | 718 | 719 | 720 | 721 | 722 | 723 | 724 | 725 | 726 | 727 | 728 | 729 | 730 | 731 | 732 | 733 | 734 | 735 | 736 | 737 | 738 | 739 | 740 | 741 | 742 | 743 | 744 | 745 | 746 | 747 | 748 | 749 | 750 | 751 | 752 | 753 | 754 | 755 | 756 | 757 | 758 | 759 | 760 | 761 | 762 | 763 | 764 | 765 | 766 | 767 | 768 | 769 | 770 | 771 | 772 | 773 | 774 | 775 | 776 | 777 | 778 | 779 | 780 | 781 | 782 | 783 | 784 | 785 | 786 | 787 | 788 | 789 | 790 | 791 | 792 | 793 | 794 | 795 | 796 | 797 | 798 | 799 | 800 | 801 | 802 | 803 | 804 | 805 | 806 | 807 | 808 | 809 | 810 | 811 | 812 | 813 | 814 | 815 | 816 | 817 | 818 | 819 | 820 | 821 | 822 | 823 | 824 | 825 | 826 | 827 | 828 | 832 | 833 | 834 | 835 | 836 | 837 | 838 | 839 | 840 | 841 | 842 | 843 | 844 | 845 | 846 | 847 | 848 | 849 | 850 | 851 | 852 | 853 | 854 | 855 | 856 | 857 | 858 | 859 | 860 | 861 | 862 | 863 | 864 | 865 | 866 | 867 | 868 | 869 | 870 | 871 | 872 | 873 | 874 | 875 | 876 | 877 | 878 | 879 | 880 | 881 | 882 | 883 | 884 | 885 | 886 | 887 | 888 | 889 | 890 | 891 | 892 | 893 | 894 | 895 | 896 | 897 | 898 | 899 | 900 | 901 | 902 | 903 | 904 | 905 | 906 | 907 | 908 | 909 | 910 | 911 | 912 | 913 | 914 | 915 | 916 | 917 | 918 | 919 | 920 | 921 | 922 | 923 | 924 | 925 | 926 | 927 | 928 | 929 | 930 | 931 | 932 | 933 | 934 | 935 | 936 | 937 | 938 | 939 | 940 | 941 | 942 | 943 | 944 | 945 | 946 | 947 | 948 | 949 | 950 | 951 | 952 | 953 | 954 | 955 | 956 | 957 | 958 | 959 | 960 | 961 | 962 | 963 | 964 | 965 | 966 | 967 | 968 | 969 | 970 | 971 | 972 | 973 | 974 | 975 | 976 | 977 | 978 | 979 | 980 | 981 | 982 | 983 | 984 | 985 | 986 | 987 | 988 | 989 | 990 | 991 | 992 | 993 | 994 | 995 | 996 | 997 | 998 | 999 | 1000 | 1001 | 1002 | 1003 | 1004 | 1005 | 1006 | 1007 | 1008 | 1009 | 1010 | 1011 | 1012 | 1013 | 1014 | 1015 | 1016 | 1017 | 1018 | 1019 | 1020 | 1021 | 1022 | 1023 | 1024 | 1025 | 1026 | 1027 | 1028 | 1029 | 1030 | 1031 | 1032 | 1033 | 1034 | 1035 | 1036 | 1037 | 1038 | 1039 | 1040 | 1041 | 1042 | 1043 | 1044 | 1045 | 1046 | 1047 | 1048 | 1049 | 1050 | 1051 | 1052 | 1053 | 1054 | 1055 | 1056 | 1057 | 1058 | 1059 | 1060 | 1061 | 1062 | 1063 | 1064 | 1065 | 1066 | 1067 | 1068 | 1069 | 1070 | 1071 | 1072 | 1073 | 1074 | 1075 | 1076 | 1077 | 1078 | 1079 | 1080 | 1081 | 1082 | 1083 | 1084 | 1085 | 1086 | 1087 | 1088 | 1089 | 1090 | 1091 | 1092 | 1093 | 1094 | 1095 | 1096 | 1097 | 1098 | 1099 | 1100 | 1101 | 1102 | 1103 | 1104 | 1105 | 1106 | 1107 | 1108 | 1109 | 1110 | 1111 | 1112 | 1113 | 1114 | 1115 | 1116 | 1117 | 1118 | 1119 | 1120 | 1121 | 1122 | 1123 | 1124 | 1125 | 1126 | 1127 | 1128 | 1129 | 1130 | 1131 | 1132 | 1133 | 1134 | 1135 | 1136 | 1137 | 1138 | 1139 | 1140 | 1141 | 1142 | 1143 | 1144 | 1145 | 1146 | 1147 | 1148 | 1149 | 1150 | 1151 | 1152 | 1153 | 1154 | 1155 | 1156 | 1157 | 1158 | 1159 | 1160 | 1161 | 1162 | 1163 | 1164 | 1165 | 1166 | 1167 | 1168 | 1169 | 1170 | 1171 | 1172 | 1173 | 1174 | 1175 | 1176 | 1177 | 1178 | 1179 | 1180 | 1181 | 1182 | 1183 | 1184 | 1185 | 1186 | 1187 | 1188 | 1189 | 1190 | 1191 | 1192 | 1193 | 1194 | 1195 | 1196 | 1197 | 1198 | 1199 | 1200 | 1201 | 1202 | 1203 | 1204 | 1205 | 1206 | 1207 | 1208 | 1209 | 1210 | 1211 | 1212 | 1213 | 1214 | 1215 | 1216 | 1217 | 1218 | 1219 | 1220 | 1221 | 1222 | 1223 | 1224 | 1225 | 1226 | 1227 | 1228 | 1229 | 1230 | 1231 | 1232 | 1233 | 1234 | 1235 | 1236 | 1237 | 1238 | 1239 | 1240 | 1241 | 1242 | 1243 | 1244 | 1245 | 1246 | 1247 | 1248 | 1249 | 1250 | 1251 | 1252 | 1253 | 1254 | 1255 | 1256 | 1257 | 1258 | 1259 | 1260 | 1261 | 1262 | 1263 | 1264 | 1265 | 1266 | 1267 | 1268 | 1269 | 1270 | 1271 | 1272 | 1273 | 1274 | 1275 | 1276 | 1277 | 1278 | 1279 | 1280 | 1281 | 1282 | 1283 | 1284 | 1285 | 1286 | 1287 | 1288 | 1289 | 1290 | 1291 | 1292 | 1293 | 1294 | 1295 | 1296 | 1297 | 1298 | 1299 | 1300 | 1301 | 1302 | 1303 | 1304 | 1305 | 1306 | 1307 | 1308 | 1309 | 1310 | 1311 | 1312 | 1313 | 1314 | 1315 | 1316 | 1317 | 1318 | 1319 | 1320 | 1321 | 1322 | 1323 | 1324 | 1325 | 1326 | 1327 | 1328 | 1329 | 1330 | 1331 | 1332 | 1333 | 1334 | 1335 | 1336 | 1337 | 1338 | 1339 | 1340 | 1341 | 1342 | 1343 | 1344 | 1345 | 1346 | 1347 | 1348 | 1349 | 1350 | 1351 | 1352 | 1353 | 1354 | 1355 | 1356 | 1357 | 1358 | 1359 | 1360 | 1361 | 1362 | 1363 | 1364 | 1365 | 1366 | 1367 | 1368 | 1369 | 1370 | 1371 | 1372 | 1373 | 1374 | 1375 | 1376 | 1377 | 1378 | 1379 | 1380 | 1381 | 1382 | 1383 | 1384 | 1385 | 1386 | 1387 | 1388 | 1389 | 1390 | 1391 | 1392 | 1393 | 1394 | 1395 | 1396 | 1397 | 1398 | 1399 | 1400 | 1401 | 1402 | 1403 | 1404 | 1405 | 1406 | 1407 | 1408 | 1409 | 1410 | 1411 | 1412 | 1413 | 1414 | 1415 | 1416 | 1417 | 1418 | 1419 | 1420 | 1421 | 1422 | 1423 | 1424 | 1425 | 1426 | 1427 | 1428 | 1429 | 1430 | 1431 | 1432 | 1433 | 1434 | 1435 | 1436 | 1437 | 1438 | 1439 | 1440 | 1441 | 1442 | 1443 | 1444 | 1445 | 1446 | 1447 | 1448 | 1449 | 1450 | 1451 | 1452 | 1453 | 1454 | 1455 | 1456 | 1457 | 1458 | 1459 | 1460 | 1461 | 1462 | 1463 | 1464 | 1465 | 1466 | 1467 | 1468 | 1469 | 1470 | 1471 | 1472 | 1473 | 1474 | 1475 | 1476 | 1477 | 1478 | 1479 | 1480 | 1481 | 1482 |
NameDescription
{ ... } (Block)Blocks are one or more statements enclosed in braces. Typically used with function definitions and control flow statements.
{ ... } / ObjectCreates an Object from a list of property name and value pairs.
[ ... ] / ArrayCreates an Array from a sequence of parameter values.
AbsReturns the absolute value of the specified number.
ASinReturns the arcsine (the number whose sine is the specified number) in radians.
ACosReturns the arccosine (the number whose cosine is the specified number) in radians.
ATanReturns the arctangent (the number whose tangent is the specified number) in radians.
BlockInputDisables or enables the user's ability to interact with the computer via keyboard and mouse.
BreakExits (terminates) any type of loop statement.
BufferCreates a Buffer, which encapsulates a block of memory for use with other functions.
CallbackCreateCreates a machine-code address that when called, redirects the call to a function in the script.
CallbackFreeDeletes a callback and releases its reference to the function object.
CaretGetPosRetrieves the current position of the caret (text insertion point).
CatchSpecifies one or more statements to execute if a value or error is thrown during execution of a Try statement.
CeilReturns the specified number rounded up to the nearest integer (without any .00 suffix).
ChrReturns the string (usually a single character) corresponding to the character code indicated by the specified number.
ClickClicks a mouse button at the specified coordinates. It can also hold down a mouse button, turn the mouse wheel, or move the mouse.
ClipboardAllCreates an object containing everything on the clipboard (such as pictures and formatting).
ClipWaitWaits until the clipboard contains data.
ComCallCalls a native COM interface method by index.
ComObjActiveRetrieves a registered COM object.
ComObjArrayCreates a SafeArray for use with COM.
ComObjConnectConnects a COM object's event source to the script, enabling events to be handled.
ComObjectCreates a COM object.
ComObjFlagsRetrieves or changes flags which control a COM wrapper object's behaviour.
ComObjFromPtrWraps a raw IDispatch pointer (COM object) for use by the script.
ComObjGetReturns a reference to an object provided by a COM component.
ComObjQueryQueries a COM object for an interface or service.
ComObjTypeRetrieves type information from a COM object.
ComObjValueRetrieves the value or pointer stored in a COM wrapper object.
ComValueWraps a value, SafeArray or COM object for use by the script or for passing to a COM method.
ContinueSkips the rest of a loop statement's current iteration and begins a new one.
ControlAddItemAdds the specified string as a new entry at the bottom of a ListBox or ComboBox.
ControlChooseIndexSets the selection in a ListBox, ComboBox or Tab control to be the Nth item.
ControlChooseStringSets the selection in a ListBox or ComboBox to be the first entry whose leading part matches the specified string.
ControlClickSends a mouse button or mouse wheel event to a control.
ControlDeleteItemDeletes the specified entry number from a ListBox or ComboBox.
ControlFindItemReturns the entry number of a ListBox or ComboBox that is a complete match for the specified string.
ControlFocusSets input focus to a given control on a window.
ControlGetCheckedReturns a non-zero value if the checkbox or radio button is checked.
ControlGetChoiceReturns the name of the currently selected entry in a ListBox or ComboBox.
ControlGetClassNNReturns the ClassNN (class name and sequence number) of the specified control.
ControlGetEnabledReturns a non-zero value if the specified control is enabled.
ControlGetFocusRetrieves which control of the target window has keyboard focus, if any.
ControlGetHwndReturns the unique ID number of the specified control.
ControlGetIndexReturns the index of the currently selected entry or tab in a ListBox, ComboBox or Tab control.
ControlGetItemsReturns an array of items/rows from a ListBox, ComboBox, or DropDownList.
ControlGetPosRetrieves the position and size of a control.
ControlGetStyle
ControlGetExStyle
Returns an integer representing the style or extended style of the specified control.
ControlGetTextRetrieves text from a control.
ControlGetVisibleReturns a non-zero value if the specified control is visible.
ControlHideHides the specified control.
ControlHideDropDownHides the drop-down list of a ComboBox control.
ControlMoveMoves or resizes a control.
ControlSend
ControlSendText
Sends simulated keystrokes or text to a window or control.
ControlSetCheckedTurns on (checks) or turns off (unchecks) a checkbox or radio button.
ControlSetEnabledEnables or disables the specified control.
ControlSetStyle
ControlSetExStyle
Changes the style or extended style of the specified control, respectively.
ControlSetTextChanges the text of a control.
ControlShowShows the specified control if it was previously hidden.
ControlShowDropDownShows the drop-down list of a ComboBox control.
CoordModeSets coordinate mode for various built-in functions to be relative to either the active window or the screen.
CosReturns the trigonometric cosine of the specified number.
CriticalPrevents the current thread from being interrupted by other threads, or enables it to be interrupted.
DateAddAdds or subtracts time from a date-time value.
DateDiffCompares two date-time values and returns the difference.
DetectHiddenTextDetermines whether invisible text in a window is "seen" for the purpose of finding the window. This affects windowing functions such as WinExist and WinActivate.
DetectHiddenWindowsDetermines whether invisible windows are "seen" by the script.
DirCopyCopies a folder along with all its sub-folders and files (similar to xcopy) or the entire contents of an archive file such as ZIP.
DirCreateCreates a folder.
DirDeleteDeletes a folder.
DirExistChecks for the existence of a folder and returns its attributes.
DirMove Moves a folder along with all its sub-folders and files. It can also rename a folder.
DirSelect

Displays a standard dialog that allows the user to select a folder.

DllCallCalls a function inside a DLL, such as a standard Windows API function.
DownloadDownloads a file from the Internet.
DriveEjectEjects the tray of the specified CD/DVD drive, or ejects a removable drive.
DriveGetCapacityReturns the total capacity of the drive which contains the specified path, in megabytes.
DriveGetFileSystemReturns the type of the specified drive's file system.
DriveGetLabelReturns the volume label of the specified drive.
DriveGetListReturns a string of letters, one character for each drive letter in the system.
DriveGetSerialReturns the volume serial number of the specified drive.
DriveGetSpaceFreeReturns the free disk space of the drive which contains the specified path, in megabytes.
DriveGetStatusReturns the status of the drive which contains the specified path.
DriveGetStatusCDReturns the media status of the specified CD/DVD drive.
DriveGetTypeReturns the type of the drive which contains the specified path.
DriveLockPrevents the eject feature of the specified drive from working.
DriveRetractRetracts the tray of the specified CD/DVD drive.
DriveSetLabelChanges the volume label of the specified drive.
DriveUnlockRestores the eject feature of the specified drive.
EditOpens the current script for editing in the default editor.
EditGetCurrentColReturns the column number in an Edit control where the caret (text insertion point) resides.
EditGetCurrentLineReturns the line number in an Edit control where the caret (text insert point) resides.
EditGetLineReturns the text of the specified line in an Edit control.
EditGetLineCountReturns the number of lines in an Edit control.
EditGetSelectedTextReturns the selected text in an Edit control.
EditPastePastes the specified string at the caret (text insertion point) in an Edit control.
ElseSpecifies one or more statements to execute if the associated statement's body did not execute.
EnvGetRetrieves the value of the specified environment variable.
EnvSetWrites a value to the specified environment variable.
ExitExits the current thread.
ExitAppTerminates the script.
ExpReturns the result of raising e (which is approximately 2.71828182845905) to the Nth power.
FileAppendWrites text or binary data to the end of a file (first creating the file, if necessary).
FileCopyCopies one or more files.
FileCreateShortcutCreates a shortcut (.lnk) file.
FileDeleteDeletes one or more files permanently.
FileEncodingSets the default encoding for FileRead, Loop Read, FileAppend, and FileOpen.
FileExistChecks for the existence of a file or folder and returns its attributes.
FileInstallIncludes the specified file inside the compiled version of the script.
FileGetAttribReports whether a file or folder is read-only, hidden, etc.
FileGetShortcutRetrieves information about a shortcut (.lnk) file, such as its target file.
FileGetSizeRetrieves the size of a file.
FileGetTimeRetrieves the datetime stamp of a file or folder.
FileGetVersionRetrieves the version of a file.
FileMoveMoves or renames one or more files.
FileOpenOpens a file to read specific content from it and/or to write new content into it.
FileReadRetrieves the contents of a file.
FileRecycleSends a file or directory to the recycle bin if possible, or permanently deletes it.
FileRecycleEmptyEmpties the recycle bin.
FileSelectDisplays a standard dialog that allows the user to open or save file(s).
FileSetAttribChanges the attributes of one or more files or folders. Wildcards are supported.
FileSetTimeChanges the datetime stamp of one or more files or folders. Wildcards are supported.
FinallyEnsures that one or more statements are always executed after a Try statement finishes.
FloatConverts a numeric string or integer value to a floating-point number.
FloorReturns the specified number rounded down to the nearest integer (without any .00 suffix).
ForRepeats one or more statements once for each key-value pair in an object.
FormatFormats a variable number of input values according to a format string.
FormatTimeTransforms a YYYYMMDDHH24MISS timestamp into the specified date/time format.
GetKeyNameRetrieves the name/text of a key.
GetKeyVKRetrieves the virtual key code of a key.
GetKeySCRetrieves the scan code of a key.
GetKeyStateReturns 1 (true) or 0 (false) depending on whether the specified keyboard key or mouse/controller button is down or up. Also retrieves controller status.
GetMethodRetrieves the implementation function of a method.
GotoJumps to the specified label and continues execution.
GroupActivateActivates the next window in a window group that was defined with GroupAdd.
GroupAddAdds a window specification to a window group, creating the group if necessary.
GroupCloseCloses 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.
GroupDeactivateSimilar to GroupActivate except activates the next window not in the group.
Gui()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.
GuiCtrlFromHwndRetrieves the GuiControl object of a GUI control associated with the specified window handle.
GuiFromHwndRetrieves the Gui object of a GUI window associated with the specified window handle.
HasBaseReturns a non-zero number if the specified value is derived from the specified base object.
HasMethodReturns a non-zero number if the specified value has a method by the specified name.
HasPropReturns a non-zero number if the specified value has a property by the specified name.
HotIf / HotIfWin...Specifies the criteria for subsequently created or modified hotkey variants and hotstring variants.
HotkeyCreates, modifies, enables, or disables a hotkey while the script is running.
HotstringCreates, modifies, enables, or disables a hotstring while the script is running.
IfSpecifies one or more statements to execute if an expression evaluates to true.
IL_Create
623 | IL_Add
624 | IL_Destroy
The means by which icons are added to a ListView or TreeView control.
ImageSearchSearches a region of the screen for an image.
IniDeleteDeletes a value from a standard format .ini file.
IniReadReads a value, section or list of section names from a standard format .ini file.
IniWriteWrites a value or section to a standard format .ini file.
InputBoxDisplays an input box to ask the user to enter a string.
InputHookCreates an object which can be used to collect or intercept keyboard input.
InstallKeybdHookInstalls or uninstalls the keyboard hook.
InstallMouseHookInstalls or uninstalls the mouse hook.
InStrSearches for a given occurrence of a string, from the left or the right.
IntegerConverts a numeric string or floating-point value to an integer.
IsLabelReturns a non-zero number if the specified label exists in the current scope.
IsObjectReturns a non-zero number if the specified value is an object.
IsSet / IsSetRefReturns a non-zero number if the specified variable has been assigned a value.
KeyHistoryDisplays script info and a history of the most recent keystrokes and mouse clicks.
KeyWaitWaits for a key or mouse/controller button to be released or pressed down.
ListHotkeysDisplays 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.
ListLinesEnables or disables line logging or displays the script lines most recently executed.
ListVarsDisplays the script's variables: their names and current contents.
ListViewGetContentReturns a list of items/rows from a ListView.
LoadPictureLoads a picture from file and returns a bitmap or icon handle.
LogReturns the logarithm (base 10) of the specified number.
LnReturns the natural logarithm (base e) of the specified number.
Loop (normal)Performs one or more statements repeatedly: either the specified number of times or until Break is encountered.
Loop FilesRetrieves the specified files or folders, one at a time.
Loop ParseRetrieves substrings (fields) from a string, one at a time.
Loop ReadRetrieves the lines in a text file, one at a time.
Loop RegRetrieves the contents of the specified registry subkey, one item at a time.
MapCreates a Map from a list of key-value pairs.
MaxReturns the highest number from a set of numbers.
MenuBar()Creates a MenuBar object, which can be used to define a GUI menu bar.
Menu()Creates a Menu object, which can be used to create and display a menu.
MenuFromHandleRetrieves the Menu or MenuBar object corresponding to a Win32 menu handle.
MenuSelectInvokes a menu item from the menu bar of the specified window.
MinReturns the lowest number from a set of numbers.
ModModulo. Returns the remainder of a number (dividend) divided by another number (divisor).
MonitorGetChecks if the specified monitor exists and optionally retrieves its bounding coordinates.
MonitorGetCountReturns the total number of monitors.
MonitorGetNameReturns the operating system's name of the specified monitor.
MonitorGetPrimaryReturns the number of the primary monitor.
MonitorGetWorkAreaChecks if the specified monitor exists and optionally retrieves the bounding coordinates of its working area.
MouseClickClicks or holds down a mouse button, or turns the mouse wheel. Note: The Click function is generally more flexible and easier to use.
MouseClickDragClicks and holds the specified mouse button, moves the mouse to the destination coordinates, then releases the button.
MouseGetPosRetrieves the current position of the mouse cursor, and optionally which window and control it is hovering over.
MouseMoveMoves the mouse cursor.
MsgBoxDisplays the specified text in a small window containing one or more buttons (such as Yes and No).
NumberConverts a numeric string to a pure integer or floating-point number.
NumGetReturns the binary number stored at the specified address+offset.
NumPutStores one or more numbers in binary format at the specified address+offset.
ObjAddRef / ObjReleaseIncrements or decrements an object's reference count.
ObjBindMethodCreates a BoundFunc object which calls a method of a given object.
829 | ObjHasOwnProp
830 | ObjOwnProps
831 |
These functions are equivalent to built-in methods of the Object type. It is usually recommended to use the corresponding method instead.
ObjGetBaseRetrieves an object's base object.
ObjGetCapacityReturns the current capacity of the object's internal array of properties.
ObjOwnPropCountReturns the number of properties owned by an object.
ObjSetBaseSets an object's base object.
ObjSetCapacitySets the current capacity of the object's internal array of own properties.
OnClipboardChangeRegisters a function to be called automatically whenever the clipboard's content changes.
OnErrorRegisters a function to be called automatically whenever an unhandled error occurs.
OnExitRegisters a function to be called automatically whenever the script exits.
OnMessageRegisters a function to be called automatically whenever the script receives the specified message.
OrdReturns the ordinal value (numeric character code) of the first character in the specified string.
OutputDebugSends a string to the debugger (if any) for display.
PausePauses the script's current thread or sets the pause state of the underlying thread.
PersistentPrevents the script from exiting automatically when its last thread completes, allowing it to stay running in an idle state.
PixelGetColorRetrieves the color of the pixel at the specified X and Y coordinates.
PixelSearchSearches a region of the screen for a pixel of the specified color.
PostMessagePlaces a message in the message queue of a window or control.
ProcessCloseForces the first matching process to close.
ProcessExistChecks if the specified process exists.
ProcessGetNameReturns the name of the specified process.
ProcessGetParentReturns the process ID (PID) of the process which created the specified process.
ProcessGetPathReturns the path of the specified process.
ProcessSetPriorityChanges the priority level of the first matching process.
ProcessWaitWaits for the specified process to exist.
ProcessWaitCloseWaits for all matching processes to close.
RandomGenerates a pseudo-random number.
RegExMatchDetermines whether a string contains a pattern (regular expression).
RegExReplaceReplaces occurrences of a pattern (regular expression) inside a string.
RegCreateKeyCreates a registry key without writing a value.
RegDeleteDeletes a value from the registry.
RegDeleteKeyDeletes a subkey from the registry.
RegReadReads a value from the registry.
RegWriteWrites a value to the registry.
ReloadReplaces the currently running instance of the script with a new one.
ReturnReturns from a function to which execution had previously jumped via function-call, Hotkey activation, or other means.
RoundReturns the specified number rounded to N decimal places.
RunRuns an external program.
RunAsSpecifies a set of user credentials to use for all subsequent Run and RunWait functions.
RunWaitRuns an external program and waits until it finishes.
Send / SendText / SendInput / SendPlay / SendEventSends simulated keystrokes and mouse clicks to the active window.
SendLevelControls which artificial keyboard and mouse events are ignored by hotkeys and hotstrings.
SendMessageSends a message to a window or control and waits for acknowledgement.
SendModeMakes Send synonymous with SendEvent or SendPlay rather than the default (SendInput). Also makes Click and MouseMove/Click/Drag use the specified method.
SetCapsLockStateSets the state of CapsLock. Can also force the key to stay on or off.
SetControlDelaySets the delay that will occur after each control-modifying function.
SetDefaultMouseSpeedSets the mouse speed that will be used if unspecified in Click, MouseMove, MouseClick, and MouseClickDrag.
SetKeyDelaySets the delay that will occur after each keystroke sent by Send or ControlSend.
SetMouseDelaySets the delay that will occur after each mouse movement or click.
SetNumLockStateSets the state of NumLock. Can also force the key to stay on or off.
SetScrollLockStateSets the state of ScrollLock. Can also force the key to stay on or off.
SetRegViewSets 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.
SetStoreCapsLockModeWhether to restore the state of CapsLock after a Send.
SetTimerCauses a function to be called automatically and repeatedly at a specified time interval.
SetTitleMatchModeSets the matching behavior of the WinTitle parameter in built-in functions such as WinWait.
SetWinDelaySets the delay that will occur after each windowing function, such as WinActivate.
SetWorkingDirChanges the script's current working directory.
ShutdownShuts down, restarts, or logs off the system.
SinReturns the trigonometric sine of the specified number.
SleepWaits the specified amount of time before continuing.
SortArranges a variable's contents in alphabetical, numerical, or random order (optionally removing duplicates).
SoundBeepEmits a tone from the PC speaker.
SoundGetInterfaceRetrieves a native COM interface of a sound device or component.
SoundGetMuteRetrieves a mute setting of a sound device.
SoundGetNameRetrieves the name of a sound device or component.
SoundGetVolumeRetrieves a volume setting of a sound device.
SoundPlayPlays a sound, video, or other supported file type.
SoundSetMuteChanges a mute setting of a sound device.
SoundSetVolumeChanges a volume setting of a sound device.
SplitPathSeparates a file name or URL into its name, directory, extension, and drive.
SqrtReturns the square root of the specified number.
StatusBarGetTextRetrieves the text from a standard status bar control.
StatusBarWaitWaits until a window's status bar contains the specified string.
StrCompareCompares two strings alphabetically.
StrGetCopies a string from a memory address or buffer, optionally converting it from a given code page.
StringConverts a value to a string.
StrLenRetrieves the count of how many characters are in a string.
StrLowerConverts a string to lowercase.
StrPtrReturns the current memory address of a string.
StrPutCopies a string to a memory address or buffer, optionally converting it to a given code page.
StrReplaceReplaces the specified substring with a new string.
StrSplitSeparates a string into an array of substrings using the specified delimiters.
StrTitleConverts a string to title case.
StrUpperConverts a string to uppercase.
SubStrRetrieves one or more characters from the specified position in a string.
SuspendDisables or enables all or selected hotkeys and hotstrings.
SwitchCompares a value with multiple cases and executes the statements of the first match.
SysGetRetrieves dimensions of system objects, and other system properties.
SysGetIPAddressesReturns an array of the system's IPv4 addresses.
TanReturns the trigonometric tangent of the specified number.
ThreadSets the priority or interruptibility of threads. It can also temporarily disable all timers.
ThrowSignals the occurrence of an error. This signal can be caught by a Try-Catch statement.
ToolTipShows an always-on-top window anywhere on the screen.
TraySetIconChanges the script's tray icon (which is also used by GUI and dialog windows).
TrayTipShows a balloon message window or, on Windows 10 and later, a toast notification near the tray icon.
Trim / LTrim / RTrimTrims characters from the beginning and/or end of a string.
TryGuards one or more statements against runtime errors and values thrown by the Throw statement.
TypeReturns the class name of a value.
UntilApplies a condition to the continuation of a Loop or For-loop.
VarSetStrCapacityEnlarges 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.
VerCompareCompares two version strings.
While-loopPerforms one or more statements repeatedly until the specified expression evaluates to false.
WinActivateActivates the specified window.
WinActivateBottomSame as WinActivate except that it activates the bottommost matching window rather than the topmost.
WinActiveChecks if the specified window is active and returns its unique ID (HWND).
WinCloseCloses the specified window.
WinExistChecks if the specified window exists and returns the unique ID (HWND) of the first matching window.
WinGetClassRetrieves the specified window's class name.
WinGetClientPosRetrieves the position and size of the specified window's client area.
WinGetControlsReturns an array of names (ClassNNs) for all controls in the specified window.
WinGetControlsHwndReturns an array of unique ID numbers (HWNDs) for all controls in the specified window.
WinGetCountReturns the number of existing windows that match the specified criteria.
WinGetIDReturns the unique ID number (HWND) of the specified window.
WinGetIDLastReturns the unique ID number (HWND) of the last/bottommost window if there is more than one match.
WinGetListReturns an array of unique ID numbers (HWNDs) for all existing windows that match the specified criteria.
WinGetMinMaxReturns a non-zero number if the specified window is maximized or minimized.
WinGetPIDReturns the Process ID number (PID) of the specified window.
WinGetPosRetrieves the position and size of the specified window.
WinGetProcessNameReturns the name of the process that owns the specified window.
WinGetProcessPathReturns the full path and name of the process that owns the specified window.
WinGetStyle
WinGetExStyle
Returns the style or extended style (respectively) of the specified window.
WinGetTextRetrieves the text from the specified window.
WinGetTitleRetrieves the title of the specified window.
WinGetTransColorReturns the color that is marked transparent in the specified window.
WinGetTransparentReturns the degree of transparency of the specified window.
WinHideHides the specified window.
WinKillForces the specified window to close.
WinMaximizeEnlarges the specified window to its maximum size.
WinMinimizeCollapses the specified window into a button on the task bar.
WinMinimizeAll / WinMinimizeAllUndoMinimizes or unminimizes all windows.
WinMoveChanges the position and/or size of the specified window.
WinMoveBottomSends the specified window to the bottom of stack; that is, beneath all other windows.
WinMoveTopBrings the specified window to the top of the stack without explicitly activating it.
WinRedrawRedraws the specified window.
WinRestoreUnminimizes or unmaximizes the specified window if it is minimized or maximized.
WinSetAlwaysOnTopMakes the specified window stay on top of all other windows (except other always-on-top windows).
WinSetEnabledEnables or disables the specified window.
WinSetRegionChanges the shape of the specified window to be the specified rectangle, ellipse, or polygon.
WinSetStyle
WinSetExStyle
Changes the style or extended style of the specified window, respectively.
WinSetTitleChanges the title of the specified window.
WinSetTransColorMakes all pixels of the chosen color invisible inside the specified window.
WinSetTransparentMakes the specified window semi-transparent.
WinShowUnhides the specified window.
WinWaitWaits until the specified window exists.
WinWaitActive / WinWaitNotActiveWaits until the specified window is active or not active.
WinWaitCloseWaits until no matching windows can be found.
#ClipboardTimeoutChanges how long the script keeps trying to access the clipboard when the first attempt fails.
#DllLoadLoads a DLL or EXE file before the script starts executing.
#ErrorStdOutSends any syntax error that prevents a script from launching to the standard error stream (stderr) rather than displaying a dialog.
#HotstringChanges hotstring options or ending characters.
#HotIfCreates context-sensitive hotkeys and hotstrings. They perform a different action (or none at all) depending on any condition (an expression).
#HotIfTimeoutSets the maximum time that may be spent evaluating a single #HotIf expression.
#Include / #IncludeAgainCauses the script to behave as though the specified file's contents are present at this exact position.
#InputLevelControls which artificial keyboard and mouse events are ignored by hotkeys and hotstrings.
#MaxThreadsSets the maximum number of simultaneous threads.
#MaxThreadsBufferCauses some or all hotkeys to buffer rather than ignore keypresses when their #MaxThreadsPerHotkey limit has been reached.
#MaxThreadsPerHotkeySets the maximum number of simultaneous threads per hotkey or hotstring.
#NoTrayIconDisables the showing of a tray icon.
#RequiresDisplays an error and quits if a version requirement is not met.
#SingleInstanceDetermines whether a script is allowed to run again when it is already running.
#SuspendExemptExempts subsequent hotkeys and hotstrings from suspension.
#UseHookForces the use of the hook to implement all or some keyboard hotkeys.
#WarnEnables or disables warnings for specific conditions which may indicate an error, such as a typo or missing "global" declaration.
#WinActivateForceSkips the gentle method of activating a window and goes straight to the forceful method.
1483 | 1484 | 1485 | -------------------------------------------------------------------------------- /docs/license.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | License | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |

Software License

13 |

GNU GENERAL PUBLIC LICENSE

14 |

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 |

Preamble

23 |

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 |

TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

32 |

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 |
38 |
39 |
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
40 |
41 |
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
42 |
43 |
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
44 |
45 |

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 |
54 |
55 |
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
56 |
57 |
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
58 |
59 |
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
60 |
61 |

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 |

END OF TERMS AND CONDITIONS

78 | 79 | 80 | -------------------------------------------------------------------------------- /docs/misc/Acknowledgements.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Acknowledgements | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Acknowledgements

14 |

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 | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |

Script Compiler Directives

13 |

Table of Contents

14 |
    15 |
  • Introduction
  • 16 |
  • Directives that control the script behaviour:
  • 17 |
      18 |
    • IgnoreBegin
    • 19 |
    • IgnoreEnd
    • 20 |
    • IgnoreKeep
    • 21 |
    22 |
  • Directives that control executable metadata:
  • 23 |
      24 |
    • Introduction
    • 25 |
    • AddResource: Adds a resource to the .exe.
    • 26 |
    • Bin / Base: Specifies the base version of AutoHotkey to use.
    • 27 |
    • ConsoleApp: Sets Console mode.
    • 28 |
    • Cont: Specifies a directive continuation line.
    • 29 |
    • Debug: Shows directive debugging text.
    • 30 |
    • ExeName: Specifies the location and name for the .exe.
    • 31 |
    • Let: Sets a user variable.
    • 32 |
    • Nop: Does nothing.
    • 33 |
    • Obey: Obeys a command or expression.
    • 34 |
    • PostExec: Runs a program after compilation.
    • 35 |
    • ResourceID: Assigns a non-standard resource ID to the main script.
    • 36 |
    • SetMainIcon: Sets the main icon.
    • 37 |
    • SetProp: Sets an .exe property.
    • 38 |
    • Set: Sets a miscellaneous property.
    • 39 |
    • UpdateManifest: Changes the .exe's manifest.
    • 40 |
    • UseResourceLang: Changes the resource language.
    • 41 |
    42 |
43 |

Introduction

44 |

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 |
    46 |
  • Ability to change the version information (such as the name, description, version...).
  • 47 |
  • Ability to add resources to the compiled script.
  • 48 |
  • Ability to tweak several miscellaneous aspects of compilation.
  • 49 |
  • Ability to remove code sections from the compiled script and vice versa.
  • 50 |
51 |

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 ;).

52 | 53 |

Directives that control the script behaviour

54 |

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 |

Directives that control executable metadata

70 |

Introduction

71 |

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).

72 | 73 |

If required, directive parameters can reference the following list of standard built-in variables by enclosing the variable name with % signs:

74 |

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.

85 | 86 |

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.

89 | 90 |

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. ``.

91 | 92 | RegEx examples: 93 |
    94 |
  • 95 |
    %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)

    97 |
  • 98 |
  • 99 |

    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.)

    105 |
  • 106 |
107 |

Other examples: Other working examples which can be downloaded and examined, are available from here.

108 | 109 |

AddResource

110 |

Adds a resource to the compiled executable. (Also see UseResourceLang below)

111 |
;@Ahk2Exe-AddResource FileName , ResourceName
112 |
113 |
FileName
114 |
The filename of the resource to add. The file is assumed to be in (or relative to) the script's own directory if an absolute path isn't specified. The type of the resource (as an integer or string) can be explicitly specified by prepending an asterisk to it: *type Filename. If omitted, Ahk2Exe automatically detects the type according to the file extension.
115 |
ResourceName
116 |
(Optional) The name that the resource will have (can be a string or an integer). If omitted, it defaults to the name (with no path) of the file, in uppercase.
117 |
118 |

Here is a list of common standard resource types and the extensions that trigger them by default.

119 |
    120 |
  • 2 (RT_BITMAP): .bmp, .dib
  • 121 |
  • 4 (RT_MENU)
  • 122 |
  • 5 (RT_DIALOG)
  • 123 |
  • 6 (RT_STRING)
  • 124 |
  • 9 (RT_ACCELERATORS)
  • 125 |
  • 10 (RT_RCDATA): Every single other extension.
  • 126 |
  • 11 (RT_MESSAGETABLE)
  • 127 |
  • 12 (RT_GROUP_CURSOR): .cur (not yet supported)
  • 128 |
  • 14 (RT_GROUP_ICON): .ico
  • 129 |
  • 23 (RT_HTML): .htm, .html, .mht
  • 130 |
  • 24 (RT_MANIFEST): .manifest. If the name for the resource is not specified, it defaults to 1.
  • 131 |
132 |

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, MYRESOURCE
141 |

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 |

Bin / Base

144 |

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.)

145 | 146 |
;@Ahk2Exe-Bin  [Path\]Name , [Exe_path\][Name], Codepage ; Deprecated
147 | ;@Ahk2Exe-Base [Path\]Name , [Exe_path\][Name], Codepage
148 |
149 |
[Path\]Name
150 |
The *.bin or *.exe file to use. If no extension is supplied, .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.
151 |
[Exe_path\][Name]
152 |
(Optional) The file name to be given to the .exe. Any extension supplied will be replaced by .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.)
153 |
Codepage
154 |
(Optional) Overrides the default codepage 155 | used to process script files. (Scripts should begin with a Unicode byte-order-mark (BOM), rendering the use of this parameter unnecessary.)
156 |
157 | 158 |

ConsoleApp

159 |

Changes the executable subsystem to Console mode.

160 |
;@Ahk2Exe-ConsoleApp
161 | 162 |

Cont

163 |

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 |
166 |
Text
167 |
The text to be appended to the previous directive line, before that line is processed. The text starts after the single space following the Cont key-word.
168 |
169 | 170 |

Debug

171 |

Shows a message box with the supplied text, for debugging purposes.

172 |
;@Ahk2Exe-Debug Text
173 |
174 |
Text
175 |
The text to be shown. Include any special variables between % signs to see the (manipulated) contents.
176 |
177 | 178 |

ExeName

179 |

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 |
182 |
[Path\][Name]
183 |
The .exe file name. Any extension supplied will be replaced by .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.
184 |
185 | Example: 186 |
;@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 |

Let

191 |

Creates (or modifies) one or more user variables which can be accessed by %U_Name%, similar to the built-in variables (see above).

192 |
;@Ahk2Exe-Let Name = Value , Name = Value, ...
193 |
194 |
Name
195 |
The name of the variable (with or without the leading U_).
196 |
Value
197 |
The value to be used.
198 |
199 | 200 |

Nop

201 |

Does nothing.

202 |
;@Ahk2Exe-Nop Text
203 |
204 |
Text
205 |
(Optional) Any text, which is ignored.
206 |
207 | Example: 208 |
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 |

Obey

213 |

Obeys isolated AutoHotkey commands or expressions, with result in U_Name.

214 |
;@Ahk2Exe-Obey Name, CmdOrExp , Extra
215 |
216 |
Name
217 |
The name of the variable (with or without the leading U_) to receive the result.
218 |
CmdOrExp
219 |
220 |

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 T2
223 |

Expression format must start with =, e.g.

224 |
;@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% * 8
227 |

If needed, separate multiple commands and expressions with `n.

228 |
229 |
Extra
230 |
(Optional) A number (1-9) specifying the number of extra results to be returned. e.g. if extra = 2, results will be returned in U_name, U_name1, and U_name2. The values in the names must first be set by the expression or command.
231 |
232 | 233 |

PostExec

234 |

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, IgnoreErrors
236 |
237 |
Program [parameters]
238 |
The program to execute, plus parameters. To allow access to the processed .exe file, specify the special variable A_WorkFileName as a quoted parameter, such as "%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.)
239 |
When
240 |
241 |

(Optional) Leave blank to execute before any Compression is done. Otherwise set to a number to run after compression as follows:

242 |
    243 |
  • 0 - Only run when no compression is specified.
  • 244 |
  • 1 - Only run when MPRESS compression is specified.
  • 245 |
  • 2 - Only run when UPX compression is specified.
  • 246 |
247 |
248 |
WorkingDir
249 |
(Optional) The working directory for the program. Do not enclose the name in double quotes even if it contains spaces. If omitted, the directory of the compiler (Ahk2Exe) will be used.
250 |
Hidden
251 |
(Optional) If set to 1, the program will be launched hidden.
252 |
IgnoreErrors
253 |
(Optional) If set to 1, any errors that occur during the launching or running of the program will not be reported to the user.
254 |
255 |

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:

261 |
;@Ahk2Exe-PostExec "BinMod.exe" "%A_WorkFileName%"
262 | ;@Ahk2Exe-Cont  "11.UPX." "1.UPX!.", 2
263 |

(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,, 1
266 |

For UPX:

267 |
;@Ahk2Exe-PostExec "UPX.exe" "%A_WorkFileName%"
268 | ;@Ahk2Exe-Cont  -q --all-methods --compress-icons=0, 0,, 1
269 | 270 |

ResourceID

271 |

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 |
274 |
Name
275 |
The resource ID to use. Numeric resource IDs should consist of a hash sign (#) followed by a decimal number.
276 |
277 | 278 |

SetMainIcon

279 |

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.

280 |
;@Ahk2Exe-SetMainIcon IcoFile
281 |
282 |
IcoFile
283 |
(Optional) The icon file to use. If omitted, the default AutoHotkey icon is used.
284 |
285 | 286 |

SetProp

287 |

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 |
290 |
Prop
291 |
292 |

The name of the property to change. Must be one of those listed below.

293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 348 | 349 |
PropertyDescription
CompanyNameChanges the company name.
CopyrightChanges the legal copyright information.
DescriptionChanges the file description. On Windows 8 and above, this also changes the script's name in Task Manager under "Processes".
FileVersionChanges the file version, in both text and raw binary format. (See Version below, for more details.)
InternalNameChanges the internal name.
LanguageChanges the language code. Please note that hexadecimal numbers must have an 0x prefix.
LegalTrademarksChanges the legal trademarks information.
NameChanges the product name and the internal name.
OrigFilenameChanges the original filename information.
ProductNameChanges the product name.
ProductVersionChanges the product version, in both text and raw binary format. (See Version below, for more details.)
Version 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, 1.3-alpha would produce a binary version number of 1.3.0.0. If this property is not modified, it defaults to the AutoHotkey version used to compile the script.

347 |
350 |
351 |
Value
352 |
The value to set the property to.
353 |
354 | 355 |

Set

356 |

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 |
359 |
Prop
360 |
The name of the property to change.
361 |
Value
362 |
The value to set the property to.
363 |
364 | 365 |

UpdateManifest

366 |

Changes details in the .exe's manifest. This directive is for specialised use only.

367 |
;@Ahk2Exe-UpdateManifest RequireAdmin , Name, Version, UIAccess
368 |
369 |
RequireAdmin
370 |
Set to 1 to change the executable to require administrative privileges when run. Set to 2 to change the executable to request highest available privileges when run. Set to 0 to leave unchanged.
371 |
Name
372 |
(Optional) The name to be set in the manifest.
373 |
Version
374 |
(Optional) The version to be set in the manifest.
375 |
UIAccess
376 |
(Optional) Set to 1 to make UIAccess true in the manifest.
377 |
378 | 379 |

UseResourceLang

380 |

Changes the resource language used by AddResource. This directive is positional and affects all AddResource directives that follow it.

381 |
;@Ahk2Exe-UseResourceLang LangCode
382 |
383 |
LangCode
384 |
The language code. Please note that hexadecimal numbers must have an 0x prefix. The default resource language is US English (0x0409).
385 |
386 | 387 | 388 | 389 | -------------------------------------------------------------------------------- /docs/misc/CLSID-List.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | CLSID List (Windows Class Identifiers) | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 20 | 21 | 22 | 23 |

CLSID List (Windows Class Identifiers)

24 |

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:

27 |
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.

34 |

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 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 494 | 495 | 496 | 497 | 498 | 499 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 | 520 | 521 | 522 | 523 | 524 | 525 | 526 | 527 | 528 | 529 | 530 | 531 | 532 | 533 | 534 | 535 | 536 | 537 | 538 | 539 | 540 | 541 | 542 | 543 | 544 | 545 | 546 | 547 | 548 | 549 | 550 | 551 | 552 | 553 | 554 | 555 | 556 | 557 | 558 | 559 | 560 | 561 | 562 | 563 | 564 | 565 | 566 | 567 | 568 | 569 | 570 | 571 | 572 | 573 | 574 | 575 | 576 | 577 | 578 | 579 | 580 | 581 | 582 | 583 | 584 | 585 | 586 | 587 | 588 | 589 | 590 | 591 | 592 | 593 | 594 | 595 | 596 | 597 | 598 | 599 | 600 | 601 | 602 | 603 | 604 | 605 | 606 | 607 | 608 | 609 | 610 | 611 | 612 | 613 | 614 | 615 | 616 | 617 | 618 | 619 | 620 | 621 | 622 | 623 | 624 | 625 | 626 | 627 | 628 | 629 | 630 | 631 | 632 | 633 | 634 | 635 | 636 | 637 | 638 | 639 | 640 | 641 | 642 | 643 | 644 | 645 | 646 | 647 | 648 | 649 | 650 | 651 | 652 | 653 | 654 | 655 | 656 | 657 | 658 | 659 | 660 | 661 | 662 | 663 | 664 | 665 | 666 | 667 | 668 | 669 | 670 | 671 | 672 | 673 | 674 | 675 | 676 | 677 | 678 | 679 | 680 | 681 | 682 | 683 | 684 | 685 | 686 | 687 | 688 | 689 | 690 | 691 | 692 | 693 | 694 | 695 | 696 | 697 | 698 | 699 | 700 | 701 | 702 | 703 | 704 | 705 | 706 | 707 | 708 | 709 | 710 | 711 | 712 | 713 | 714 | 715 | 716 | 717 | 718 | 719 | 720 | 721 | 722 | 723 | 724 | 725 | 726 | 727 | 728 | 729 | 730 | 731 | 732 | 733 | 734 | 735 | 736 | 737 | 738 | 739 | 740 | 741 | 742 | 743 | 744 | 745 | 746 | 747 | 748 | 749 | 750 | 751 | 752 | 753 | 754 | 755 |
CLSIDLocationAvailability
::{00020D75-0000-0000-C000-000000000046}Inbox (Outlook)XP-11
::{00028B00-0000-0000-C000-000000000046}Microsoft NetworkXP
::{00C6D95F-329C-409A-81D7-C46C66EA7F33}Default Location7
::{0142E4D0-FB7A-11DC-BA4A-000FFE7AB428}Biometric Devices7
::{018D5C66-4533-4307-9B53-224DE2ED1FE6}OneDrive10-11
::{025A5937-A6BE-4686-A844-36FE4BEC8B6D}Power OptionsVista-11
::{031E4825-7B94-4DC3-B131-E946B44C8DD5}Libraries7-11
::{04731B67-D933-450A-90E6-4ACD2E9408FE}Desktop in FavoritesVista-11
::{05D7B0F4-2121-4EFF-BF6B-ED3F69B894D9}Notification Area Icons (append \SystemIcons for System Icons)7-10
::{088E3905-0323-4B02-9826-5D99428E115F}Downloads10-11
::{0907616E-F5E6-48D8-9D61-A91C3D28106D}Hyper-V Remote File Browsing10-11
::{0DB7E03F-FC29-4DC6-9020-FF41B59E513A}3D Objects10
::{0DF44EAA-FF21-4412-828E-260A8728E7F1}Taskbar SettingsXP-11
::{1206F5F1-0569-412C-8FEC-3204630DFB70}Credential Manager7-11
::{15EAE92E-F17A-4431-9F28-805E482DAFD4}Get ProgramsVista-11
::{17CD9488-1228-4B2F-88CE-4298E93E0966}Default Programs
Default Apps
Vista-11
::{1CF1260C-4DD0-4EBB-811F-33C572699FDE}Music7-11
::{1F3427C8-5C10-4210-AA03-2EE45287D668}User Pinned7-11
::{1F4DE370-D627-11D1-BA4F-00A0C91EEDBA}Network ComputersXP
::{1FA9085F-25A2-489B-85D4-86326EEDCD87}Manage Wireless NetworksVista-7
::{208D2C60-3AEA-1069-A2D7-08002B30309D}My Network PlacesXP-11
::{20D04FE0-3AEA-1069-A2D8-08002B30309D}My Computer
Computer
This PC
XP-11
::{21EC2020-3AEA-1069-A2DD-08002B30309D}Control Panel
All Control Panel Items
XP-11
::{2227A280-3AEA-1069-A2DE-08002B30309D}Printers and FaxesXP-11
::{22877A6D-37A1-461A-91B0-DBDA5AAEBC99}Recent Places
Recent Folders
Vista-11
::{241D7C96-F8BF-4F85-B01F-E2B043341A4B}RemoteApp and Desktop Connections7-11
::{24AD3AD4-A569-4530-98E1-AB02F9417AA8}Pictures10-11
::{2559A1F0-21D7-11D4-BDAF-00C04F60B9F0}SearchXP-10
::{2559A1F3-21D7-11D4-BDAF-00C04F60B9F0}RunXP-11
::{2559A1F5-21D7-11D4-BDAF-00C04F60B9F0}E-mailXP-11
::{2559A1F7-21D7-11D4-BDAF-00C04F60B9F0}Set Program Access and DefaultsXP-11
::{2559A1F8-21D7-11D4-BDAF-00C04F60B9F0}Search (Modern)8-11
::{26EE0668-A00A-44D7-9371-BEB064C98683}Control Panel (Category view)Vista-11
::{28803F59-3A75-4058-995F-4EE5503B023C}Bluetooth DevicesVista-11
::{289AF617-1CC3-42A6-926C-E6A863F0E3BA}Media Servers8-11
::{2965E715-EB66-4719-B53F-1672673BBEFA}Results FolderVista-11
::{2E9E59C0-B437-4981-A647-9C34B9B90891}Sync Setup FolderVista-11
::{3080F90D-D7AD-11D9-BD98-0000947B0257}Show DesktopVista-11
::{3080F90E-D7AD-11D9-BD98-0000947B0257}Window SwitcherVista-11
::{323CA680-C24D-4099-B94D-446DD2D7249E}Favorites7-11
::{35786D3C-B075-49B9-88DD-029876E11C01}Portable Devices7-11
::{36EEF7DB-88AD-4E81-AD49-0E313F0C35F8}Windows UpdateVista-8
::{374DE290-123F-4565-9164-39C4925E467B}Downloads8-11
::{37EFD44D-EF8D-41B1-940D-96973A50E9E0}Windows Sidebar Properties
Desktop Gadgets
Vista-8
::{38A98528-6CBF-4CA9-8DC0-B1E1D10F7B1B}Connected ToVista-8
::{3936E9E4-D92C-4EEE-A85A-BC16D5EA0819}Frequent Folders10-11
::{3ADD1653-EB32-4CB0-BBD7-DFA0ABB5ACCA}Pictures8-11
::{3DFDF296-DBEC-4FB4-81D1-6A3438BCF4DE}Music10-11
::{3F6BC534-DFA1-4AB4-AE54-EF25A74E0107}System RestoreVista-10
::{4026492F-2F69-46B8-B9BF-5654FC07E423}Windows FirewallVista-10
::{40419485-C444-4567-851A-2DD7BFA1684D}Phone and Modem7-11
::{4234D49B-0245-4DF3-B780-3893943456E1}Applications8-11
::{4336A54D-038B-4685-AB02-99BB52D3FB8B}Public FolderVista-11
::{437FF9C0-A07F-4FA0-AF80-84B6C6440A16}Command FolderVista-11
::{450D8FBA-AD25-11D0-98A8-0800361B1103}My DocumentsXP-11
::{48E7CAAB-B918-4E58-A94D-505519C795DC}Start Menu FolderXP-Vista
::{5224F545-A443-4859-BA23-7B5A95BDC8EF}People Near MeVista-7
::{5399E694-6CE5-4D6C-8FCE-1D8870FDCBA0}Control PanelVista-11
::{58E3C745-D971-4081-9034-86E34B30836A}Speech RecognitionVista-11
::{59031A47-3F72-44A7-89C5-5595FE6B30EE}User FolderVista-11
::{5EA4F148-308C-46D7-98A9-49041B1DD468}Mobility CenterVista-11
::{60632754-C523-4B62-B45C-4172DA012619}User AccountsVista-11
::{62D8ED13-C9D0-4CE8-A914-47DD628FB1B0}Region and Language7-11
::{645FF040-5081-101B-9F08-00AA002F954E}Recycle BinXP-11
::{67718415-C450-4F3C-BF8A-B487642DC39B}Windows FeaturesVista-10
::{679F85CB-0220-4080-B29B-5540CC05AAB6}Quick access10-11
::{67CA7650-96E6-4FDD-BB43-A8E774F73A57}HomeGroup7-11
::{6C8EEC18-8D75-41B2-A177-8831D59D2D50}Mouse Properties7-11
::{6DFD7C5C-2451-11D3-A299-00C04F8EF6AF}Folder OptionsXP-11
::{7007ACC7-3202-11D1-AAD2-00805FC1270E}Network ConnectionsXP-11
::{725BE8F7-668E-4C7B-8F90-46BDB0936430}Keyboard Properties7-11
::{74246BFC-4C96-11D0-ABEF-0020AF6B0B7A}Device ManagerVista-11
::{78CB147A-98EA-4AA6-B0DF-C8681F69341C}Windows CardspaceVista-7
::{78F3955E-3B90-4184-BD14-5397C15F1EFC}Performance Information and ToolsVista-7
::{7A9D77BD-5403-11D2-8785-2E0420524153}User Accounts (netplwiz)XP-11
::{7B81BE6A-CE2B-4676-A29E-EB907A5126C5}Programs and FeaturesVista-11
::{7BD29E00-76C1-11CF-9DD0-00A0C9034933}Temporary Internet FilesXP
::{7BE9D83C-A729-4D97-B5A7-1B7313C39E0A}Programs FolderXP-8
::{80F3F1D5-FECA-45F3-BC32-752C152E456E}Tablet PC Settings7-10
::{85BBD920-42A0-1069-A2E4-08002B30309D}BriefcaseXP
::{863AA9FD-42DF-457B-8E4D-0DE1B8015C60}Printers7-11
::{871C5380-42A0-1069-A2EA-08002B30309D}Internet ExplorerXP-10
::{87D66A43-7B11-4A28-9811-C86EE395ACF7}Indexing Options7-11
::{8E908FC9-BECC-40F6-915B-F4CA0E70D03D}Network and Sharing CenterVista-11
::{93412589-74D4-4E4E-AD0E-E0CB621440FD}Font Settings7-11
::{9343812E-1C37-4A49-A12E-4B2D810D956B}Search ResultsVista-10
::{96AE8D84-A250-4520-95A5-A47A7E3C548B}Parental Controls7-8
::{992CFFA0-F557-101A-88EC-00DD010CCC48}Network ConnectionsXP-11
::{9C60DE1E-E5FC-40F4-A487-460851A8D915}AutoPlayVista-11
::{9C73F5E5-7AE7-4E32-A8E8-8D23B85255BF}Sync CenterVista-11
::{9FE63AFD-59CF-4419-9775-ABCC3849F861}Recovery7-10
::{A0275511-0E86-4ECA-97C2-ECD8F1221D08}Infrared7-10
::{A0953C92-50DC-43BF-BE83-3742FED03C9C}Videos8-11
::{A304259D-52B8-4526-8B1A-A1D6CECC8243}iSCCI InitiatorVista-11
::{A3DD4F92-658A-410F-84FD-6FBBBEF2FFFE}Internet Options7-11
::{A6482830-08EB-41E2-84C1-73920C2BADB9}Removable Storage Devices8-11
::{A8A91A66-3A7D-4424-8D24-04E180695C7A}Devices and Printers7-11
::{A8CDFF1C-4878-43BE-B5FD-F8091C1C60D0}Documents8-11
::{AFDB1F70-2A4C-11D2-9039-00C04F8EEB3E}Offline Files FolderXP-10
::{B155BDF8-02F0-451E-9A26-AE317CFD7779}delegate folder that appears in ComputerVista-10
::{B2C761C6-29BC-4F19-9251-E6195265BAF1}Color ManagementVista-11
::{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}Desktop8-11
::{B4FB3F98-C1EA-428D-A78A-D1F5659CBA93}Other Users Folder
Media Streaming Options
7-11
::{B98A2BEA-7D42-4558-8BD1-832F41BAC6FD}Backup and RestoreVista-7
::{BB06C0E4-D293-4F75-8A90-CB05B6477EEE}SystemVista-11
::{BB64F8A7-BEE7-4E1A-AB8D-7D8273F7FDB6}Action Center
Security and Maintenance
(append \pageSettings for Problem Reporting Settings)
7-11
::{BD84B380-8CA2-1069-AB1D-08000948F534}FontsXP-11
::{BDEADF00-C265-11D0-BCED-00A0C90AB50F}Web FoldersXP
::{BE122A0E-4503-11DA-8BDE-F66BAD1E3F3A}Windows Anytime UpgradeVista-8
::{C555438B-3C23-4769-A71F-B6D3D9B6053A}Display (DPI)7-8
::{C58C4893-3BE0-4B45-ABB5-A63E4B8C8651}Troubleshooting7-10
::{CB1B7F8C-C50A-4176-B604-9E24DEE8D4D1}Welcome Center
Getting Started
Vista-7
::{D17D1D6D-CC3F-4815-8FE3-607E7D5D10B3}Text to Speech7-11
::{D20EA4E1-3957-11D2-A40B-0C5020524152}FontsXP-Vista
::{D20EA4E1-3957-11D2-A40B-0C5020524153}Administrative Tools
Windows Tools
XP-11
::{D3162B92-9365-467A-956B-92703ACA08AF}Documents10-11
::{D34A6CA6-62C2-4C34-8A7C-14709C1AD938}Common Places FS FolderVista-11
::{D4480A50-BA28-11D1-8E75-00C04FA31A86}Add Network PlaceXP-11
::{D450A8A1-9568-45C7-9C0E-B4F9FB4537BD}Installed UpdatesVista-11
::{D555645E-D4F8-4C29-A827-D93C859C4F2A}Ease of Access CenterVista-11
::{D6277990-4C6A-11CF-8D87-00AA0060F5BF}Scheduled TasksXP
::{D8559EB9-20C0-410E-BEDA-7ED416AECC2A}Windows DefenderVista-8
::{D9EF8727-CAC2-4E60-809E-86F80A666C91}BitLocker Drive EncryptionVista-10
::{E211B736-43FD-11D1-9EFB-0000F8757FCD}Scanners and CamerasXP
::{E2E7934B-DCE5-43C4-9576-7FE4F75E7480}Date and Time7-11
::{E44E5D18-0652-4508-A4E2-8A090067BCB0}Default Programs
Default Apps
Vista-11
::{E7DE9B1A-7533-4556-9484-B26FB486475E}Network MapVista-7
::{E95A4861-D57A-4BE1-AD0F-35267E261739}Windows SideShowVista-7
::{E9950154-C418-419E-A90A-20C5287AE24B}Location and Other Sensors
Location Settings
7-10
::{ECDB0924-4208-451E-8EE0-373C0956DE16}Work Folders8-10
::{ED228FDF-9EA8-4870-83B1-96B02CFE0D52}Games ExplorerVista-10
::{ED50FC29-B964-48A9-AFB3-15EBB9B97F36}printhood delegate folderVista-10
::{ED7BA470-8E54-465E-825C-99712043E01C}All Tasks (God Mode)Vista-11
::{ED834ED6-4B5A-4BFE-8F11-A626DCB6A921}PersonalizationVista-10
::{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}NetworkVista-11
::{F2DDFC82-8F12-4CDD-B7DC-D4FE1425AA4D}Sound7-11
::{F6B6E965-E9B2-444B-9286-10C9152EDBC5}File History8-10
::{F82DF8F7-8B9F-442E-A48C-818EA735FF9B}Pen and Touch7-10
::{F86FA3AB-70D2-4FC7-9C99-FCBF05467F3A}Videos10-11
::{F8C2AB3B-17BC-41DA-9758-339D7DBF2D88}Previous Versions Results Folder7-11
::{F942C606-0914-47AB-BE56-1321B8035096}Storage Spaces8-10
::{FF393560-C2A7-11CF-BFF4-444553540000}HistoryXP
756 | 757 | 758 | 759 | -------------------------------------------------------------------------------- /docs/misc/Colors.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | List of Color Names | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Color names and RGB values

15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 |
Color nameRGB value
Black000000
SilverC0C0C0
Gray808080
WhiteFFFFFF
Maroon800000
RedFF0000
Purple800080
FuchsiaFF00FF
Green008000
Lime00FF00
Olive808000
YellowFFFF00
Navy000080
Blue0000FF
Teal008080
Aqua00FFFF
102 | 103 | 104 | 105 | -------------------------------------------------------------------------------- /docs/misc/DPIScaling.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DPI Scaling | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

DPI Scaling

14 | 15 |

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 |

Gui DPI Scaling

20 |

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 |

OS DPI Scaling

23 |

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 |
    25 |
  • Systems with multiple monitors where not all monitors are set to the same scale.
  • 26 |
  • Whenever the display scale setting differs from what it was when the program started.
  • 27 |
28 |

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 |

Per-Monitor DPI Awareness

31 |

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 |

Workarounds

37 |

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 |

New Threads

43 |

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 |
    45 |
  • Under typical conditions, posted messages are handled directly from AutoHotkey's message loop, which means that whatever context was already in effect remains in effect. This includes most events which start new script threads, such as hotkeys, hotstrings and timers.
  • 46 |
  • Script threads corresponding to sent (not posted) messages are started from within the window procedure, which means that the context is always set based on the target window.
  • 47 |
  • Posted messages are typically dispatched to a window procedure if they are received during a modal message loop. Modal message loops are (for example) used by modal dialog boxes and menus, or while the user is moving a window or performing drag-drop.
  • 48 |
  • Non-GUI events are associated with the script's main window, and therefore receive the program-default DPI awareness context. This is usually as set in the program's manifest, but could be overridden by application compatibility settings.
  • 49 |
50 | 51 |

Mixed Settings

52 |

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 |

Compiled Scripts

74 |

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 |

Compatibility Settings

88 |

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.

89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /docs/misc/Editors.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Editors with AutoHotkey Support | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Editors with AutoHotkey Support

15 | 16 |

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 |
    18 |
  • Syntax highlighting, like what is used in this documentation. With syntax highlighting, words, symbols and segments of code are colour-coded to indicate their meaning. For instance, literal text, comments and variable names are displayed in different colours.
  • 19 |
  • Auto-complete, which typically offers a list of suggestions when you start typing the name of a known function or variable.
  • 20 |
  • Calltips may show you what the parameters are for a function while you are writing code to call the function.
  • 21 |
  • Interactive debugging, such as to step through the script line by line and inspect variables at each step, or to view and modify variables or objects, beyond what ListVars allows.
  • 22 |
23 |

Recommendations:

24 |
    25 |
  • SciTE4AutoHotkey is simple to install, relatively light-weight, and fully supports AutoHotkey v1 and v2 without further configuration.
  • 26 |
  • VS Code (plus extensions) provides an even higher level of support and a wider range of features, but can be heavy on resources.
  • 27 |
28 | 29 |

SciTE4AutoHotkey

30 |

SciTE4AutoHotkey is a custom version of the text editor known as SciTE. Its features include:

31 |
    32 |
  • Syntax highlighting
  • 33 |
  • Auto-complete
  • 34 |
  • Calltips
  • 35 |
  • Smart auto-indent
  • 36 |
  • Code folding
  • 37 |
  • Interactive debugging
  • 38 |
  • Running the script by pressing a hotkey
  • 39 |
  • Other tools for AutoHotkey scripting
  • 40 |
41 |

SciTE4AutoHotkey can be found here: https://www.autohotkey.com/scite4ahk/

42 | 43 |

Visual Studio Code (VS Code)

44 |

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 |
    47 |
  • Syntax highlighting
  • 48 |
  • Auto-complete
  • 49 |
  • Calltips
  • 50 |
  • Smart auto-indent
  • 51 |
  • Code folding
  • 52 |
  • Running the script by pressing a hotkey
  • 53 |
  • Real-time diagnostics (detecting common errors)
  • 54 |
  • Formatting/tidying code
  • 55 |
56 |

Additional notes:

57 |
    58 |
  • This extension only supports AutoHotkey v2, but can also detect v1 scripts and automatically switch over to a v1 extension if one is installed.
  • 59 |
  • This extension can also be used with other editors, such as vim, neovim and Sublime Text 4. For details, see Use in other editors. However, VS Code likely provides the best experience, with easiest setup.
  • 60 |
61 |

vscode-autohotkey-debug provides support for interactive debugging of v1 and v2 scripts.

62 | 63 |

Notepad++

64 |

Notepad++ can be configured to support the following features:

65 |
    66 |
  • Syntax highlighting
  • 67 |
  • Auto-complete
  • 68 |
  • Code folding
  • 69 |
  • Running the script by pressing a hotkey
  • 70 |
71 |

See Setup Notepad++ for AutoHotkey for instructions.

72 | 73 |

Notepad4

74 |

Notepad4 supports the following for AutoHotkey v2 by default:

75 |
    76 |
  • Syntax highlighting
  • 77 |
  • Auto-complete
  • 78 |
  • Auto-indent
  • 79 |
  • Code folding
  • 80 |
  • Running the script by pressing a hotkey
  • 81 |
82 |

It is available here: https://github.com/zufuliu/notepad4

83 | 84 |

Others editors

85 |

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 | Escape Sequences - Definition & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Escape Sequences

14 |

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.

15 |

In AutoHotkey the following escape sequences can be used:

16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 |
SequenceResult
``` (literal accent; i.e. two consecutive escape characters result in a single literal character)
`; 29 |

; (literal semicolon)

30 |

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 |
`:: (literal colon). This is necessary only in a hotstring's triggering abbreviation.
`{{ (keyboard key). This is only valid, and is required, when remapping a key to {.
`nnewline (linefeed/LF)
`rcarriage return (CR)
`bbackspace
`ttab (the more typical horizontal variety)
`sspace
`vvertical tab -- corresponds to Ascii value 11. It can also be manifest in some applications by typing Ctrl+K.
`aalert (bell) -- corresponds to Ascii value 7. It can also be manifest in some applications by typing Ctrl+G.
`fformfeed -- corresponds to Ascii value 12. It can also be manifest in some applications by typing Ctrl+L.
`" or `'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.'.
78 | 79 |

Examples

80 |
81 |

Reports a multi-line string. The lines are separated by a linefeed character.

82 |
MsgBox "Line 1`nLine 2"
83 |
84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /docs/misc/FontsStandard.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Standard Windows Fonts | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 18 | 26 | 36 | 37 | 38 | 39 |

Standard Windows Fonts

40 |

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 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 494 | 495 | 496 | 497 | 498 | 499 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 | 520 | 521 | 522 | 523 | 524 | 525 | 526 | 527 | 528 | 529 | 530 | 531 | 532 | 533 | 534 | 535 | 536 | 537 | 538 | 539 | 540 | 541 | 542 | 543 | 544 | 545 | 546 | 547 | 548 | 549 | 550 | 551 | 552 | 553 | 554 | 555 | 556 | 557 | 558 | 559 | 560 | 561 | 562 | 563 | 564 | 565 | 566 | 567 | 568 | 569 | 570 | 571 | 572 | 573 | 574 | 575 | 576 | 577 | 578 | 579 | 580 | 581 | 582 | 583 | 584 | 585 | 586 | 587 | 588 | 589 | 590 | 591 | 592 | 593 | 594 | 595 | 596 | 597 | 598 | 599 | 600 | 601 | 602 | 603 | 604 | 605 | 606 | 607 | 608 | 609 | 610 | 611 | 612 | 613 | 614 | 615 | 616 | 617 | 618 | 619 | 620 | 621 | 622 | 623 | 624 | 625 | 626 | 627 | 628 | 629 | 630 | 631 | 632 | 633 | 634 | 635 | 636 | 637 | 638 | 639 | 640 | 641 | 642 | 643 | 644 | 645 | 646 | 647 | 648 | 649 | 650 | 651 | 652 | 653 | 654 | 655 | 656 | 657 | 658 | 659 | 660 | 661 | 662 | 663 | 664 | 665 | 666 | 667 | 668 | 669 | 670 | 671 | 672 | 673 | 674 | 675 | 676 | 677 | 678 | 679 | 680 | 681 | 682 | 683 | 684 | 685 | 686 | 687 | 688 | 689 | 690 | 691 | 692 | 693 | 694 | 695 | 696 | 697 | 698 | 699 | 700 | 701 | 702 | 703 | 704 | 705 | 706 | 707 | 708 | 709 | 710 | 711 | 712 | 713 | 714 | 715 | 716 | 717 | 718 | 719 | 720 | 721 | 722 | 723 | 724 | 725 | 726 | 727 | 728 | 729 | 730 | 731 | 732 | 733 | 734 | 735 | 736 | 737 | 738 | 739 | 740 | 741 | 742 | 743 | 744 | 745 | 746 | 747 | 748 | 749 | 750 | 751 | 752 | 753 | 754 | 755 | 756 | 757 | 758 | 759 | 760 | 761 | 762 | 763 | 764 | 765 | 766 | 767 | 768 | 769 | 770 | 771 | 772 | 773 | 774 | 775 | 776 | 777 | 778 | 779 | 780 | 781 | 782 | 783 | 784 | 785 | 786 | 787 | 788 | 789 | 790 | 791 | 792 | 793 | 794 | 795 | 796 | 797 | 798 | 799 | 800 | 801 | 802 | 803 | 804 | 805 | 806 | 807 | 808 | 809 | 810 | 811 | 812 | 813 | 814 | 815 | 816 | 817 | 818 | 819 | 820 | 821 | 822 | 823 | 824 | 825 | 826 | 827 | 828 | 829 | 830 | 831 | 832 | 833 | 834 | 835 | 836 | 837 | 838 | 839 | 840 | 841 | 842 | 843 | 844 | 845 | 846 | 847 | 848 | 849 | 850 | 851 | 852 | 853 | 854 | 855 | 856 | 857 | 858 | 859 | 860 | 861 | 862 | 863 | 864 | 865 | 866 | 867 | 868 | 869 | 870 | 871 | 872 | 873 | 874 | 875 | 876 | 877 | 878 | 879 | 880 | 881 | 882 | 883 | 884 | 885 | 886 | 887 | 888 | 889 | 890 | 891 | 892 | 893 | 894 | 895 | 896 | 897 | 898 | 899 | 900 | 901 | 902 | 903 | 904 | 905 | 906 | 907 | 908 | 909 | 910 | 911 | 912 | 913 | 914 | 915 | 916 | 917 | 918 | 919 | 920 | 921 | 922 | 923 | 924 | 925 | 926 | 927 | 928 | 929 | 930 | 931 | 932 | 933 | 934 | 935 | 936 | 937 | 938 | 939 | 940 | 941 | 942 | 943 | 944 | 945 | 946 | 947 | 948 | 949 | 950 | 951 | 952 | 953 | 954 | 955 | 956 | 957 | 958 | 959 | 960 | 961 | 962 | 963 | 964 | 965 | 966 | 967 | 968 | 969 |
Font NameMainly Designed ForExists Since
AharoniHebrew2000
AldhabiArabic8
AndalusArabic2000
Angsana NewThaiXP
AngsanaUPCThaiXP
AparajitaIndic7
Arabic TypesettingArabicVista
ArialLatin, Greek, Cyrillic95
Arial BlackLatin, Greek, Cyrillic98
Arial NovaLatin, Greek, Cyrillic10
BahnschriftLatin10
BatangKorean2000
BatangCheKoreanVista
BIZ UDGothicJapanese10
BIZ UDMincho MediumJapanese10
BIZ UDPGothicJapanese10
Browallia NewThai2000
BrowalliaUPCThai2000
CalibriLatin, Greek, CyrillicVista
Calibri LightLatin, Greek, Cyrillic8
CambriaLatin, Greek, CyrillicVista
Cambria MathSymbolsVista
CandaraLatin, Greek, CyrillicVista
Cascadia CodeOther11
Cascadia MonoOther11
Comic Sans MSLatin, Greek, Cyrillic95
ConsolasLatin, Greek, CyrillicVista
ConstantiaLatin, Greek, CyrillicVista
CorbelLatin, Greek, CyrillicVista
Cordia NewThai2000
CordiaUPCThai2000
CourierLatin, Greek, Cyrillic95
Courier NewLatin, Greek, Cyrillic95
DaunPenhOtherVista
DavidHebrew2000
DengXianChinese10
DFKai-SBChinese2000
DilleniaUPCThai2000
DokChampaOtherVista
DotumKoreanVista
DotumCheKoreanVista
EbrimaAfrican7
Estrangelo EdessaOtherXP
EucrosiaUPCThai2000
EuphemiaOtherVista
FangSongChineseVista
FixedsysLatin95
Franklin Gothic MediumLatin, Greek, CyrillicXP
FrankRuehlHebrew2000
FreesiaUPCThai2000
GabriolaLatin, Greek, Cyrillic7
GadugiOther8
GautamiOtherXP
GeorgiaLatin, Greek, Cyrillic2000
Georgia ProLatin, Greek, Cyrillic10
Gill Sans NovaLatin, Greek, Cyrillic10
GishaHebrewVista
GulimKorean2000
GulimCheKoreanVista
GungsuhKoreanVista
GungsuhCheKoreanVista
HoloLens MDL2 AssetsSymbols10
ImpactLatin, Greek, Cyrillic98
Ink FreeOther10
IrisUPCThai2000
Iskoola PotaOtherVista
JasmineUPCThai2000
Javanese TextJavanese8.1
KaiTiChinese2000
KalingaOtherVista
KartikaOtherXP
Khmer UIOther7
KodchiangUPCThai2000
KokilaOther7
Lao UIOther7
LathaIndicXP
LeelawadeeThaiVista
Leelawadee UIThai8.1
Levenim MTHebrew98
LilyUPCThai2000
Lucida ConsoleLatin, Greek, Cyrillic98
Lucida SansLatin, Greek, Cyrillic98
Lucida Sans UnicodeLatin, Greek, Cyrillic98
Malgun GothicKoreanVista
MangalIndicXP
MarlettSymbols95
MeiryoJapaneseVista
Meiryo UIJapanese7
Microsoft HimalayaOtherVista
Microsoft JhengHeiChineseVista
Microsoft JhengHei UIChinese8
Microsoft New Tai LueOther7
Microsoft PhagsPaOther7
Microsoft Sans SerifLatin, Greek, Cyrillic2000
Microsoft Tai LeOther7
Microsoft UighurOtherVista
Microsoft YaHeiChineseVista
Microsoft YaHei UIChinese8
Microsoft Yi BaitiOtherVista
MingLiUChineseVista
MingLiU_HKSCSChineseVista
MingLiU_HKSCS-ExtBChineseVista
MingLiU-ExtBChineseVista
MiriamHebrew2000
Miriam FixedHebrew2000
ModernLatin95
Mongolian BaitiOtherVista
MoolBoranOtherVista
MS GothicJapanese2000
MS MinchoJapanese2000
MS PGothicJapaneseVista
MS PMinchoJapaneseVista
MS SerifLatin95
MS Sans SerifLatin95
MS UI GothicJapaneseVista
MV BoliOtherXP
Myanmar TextOther8
NarkisimHebrew2000
Neue Haas Grotesk Text ProLatin10
Nirmala UIIndic8
NSimSunChineseVista
NyalaAfricanVista
Palatino LinotypeLatin, Greek, Cyrillic2000
Plantagenet CherokeeOtherVista
PMingLiUChinese2000
PMingLiU-ExtBChineseVista
RaaviIndicXP
Rockwell NovaLatin, Greek, Cyrillic10
RodHebrew2000
RomanLatin98
Sakkal MajallaArabic7
Sanskrit TextOther10
ScriptLatin98
Segoe Fluent IconsSymbols11
Segoe MDL2 AssetsSymbols10
Segoe PrintLatin, Greek, CyrillicVista
Segoe ScriptLatin, Greek, CyrillicVista
Segoe UILatin, Greek, CyrillicVista
Segoe UI EmojiSymbols10
Segoe UI HistoricOther10
Segoe UI VariableOther11
Segoe UI SymbolSymbols7
Shonar BanglaIndic7
ShrutiIndicXP
SimHeiChinese2000
Simplified ArabicArabic2000
Simplified Arabic FixedArabic2000
SimSunChinese2000
SimSun-ExtBChineseVista
Sitka BannerLatin, Greek, Cyrillic8.1
Sitka DisplayLatin, Greek, Cyrillic8.1
Sitka HeadingLatin, Greek, Cyrillic8.1
Sitka SmallLatin, Greek, Cyrillic8.1
Sitka SubheadingLatin, Greek, Cyrillic8.1
Sitka TextLatin, Greek, Cyrillic8.1
Small FontsLatin95
SylfaenOtherXP
SymbolSymbols95
SystemLatin95
TahomaLatin, Greek, Cyrillic95
TerminalLatin95
Times New RomanLatin, Greek, Cyrillic95
Traditional ArabicArabic2000
Trebuchet MSLatin, Greek, Cyrillic2000
TungaIndicXP
UD Digi Kyokasho N-BJapanese10
UD Digi Kyokasho NK-BJapanese10
UD Digi Kyokasho NK-RJapanese10
UD Digi Kyokasho NP-BJapanese10
UD Digi Kyokasho NP-RJapanese10
UD Digi Kyokasho N-RJapanese10
Urdu TypesettingArabic8
UtsaahIndic7
VaniIndic7
VerdanaLatin, Greek, Cyrillic95
Verdana ProLatin, Greek, Cyrillic10
VijayaIndic7
VrindaIndicXP
WebdingsSymbols98
WingdingsSymbols95
Yu GothicJapanese8.1
Yu Gothic UIJapanese8.1
Yu MinchoJapanese8.1
970 | 971 | 972 | -------------------------------------------------------------------------------- /docs/misc/Functor.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Function Objects - Definition & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Function Objects

14 | 15 |

"Function object" usually means any of the following:

16 |
    17 |
  • A Func or Closure object, which represents an actual function; either built-in or defined by the script.
  • 18 |
  • A user-defined object which can be called like a function. This is sometimes also referred to as a "functor".
  • 19 |
  • Any other object which can be called like a function, such as a BoundFunc object or a JavaScript function object returned by a COM method.
  • 20 |
21 |

Function objects can be used with the following:

22 |
    23 |
  • CallbackCreate
  • 24 |
  • Gui events
  • 25 |
  • For ... in
  • 26 |
  • HotIf
  • 27 |
  • Hotkey
  • 28 |
  • Hotstring
  • 29 |
  • InputHook (OnEnd, OnChar, OnKeyDown, OnKeyUp)
  • 30 |
  • Menu.Add
  • 31 |
  • OnClipboardChange
  • 32 |
  • OnError
  • 33 |
  • OnExit
  • 34 |
  • OnMessage
  • 35 |
  • RegEx callouts
  • 36 |
  • SetTimer
  • 37 |
  • Sort
  • 38 |
39 |

To determine whether an object appears to be callable, use one of the following:

40 |
    41 |
  • 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.
  • 42 |
  • 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.
  • 43 |
44 | 45 |

User-Defined

46 | 47 |

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.

57 |

When the function object is assigned to a property, keep in mind that the method call syntax (target.func()) implicitly passes the target object as the first parameter. For YourClassName above, this would be the function object while a would be the target object. The expression used to retrieve the function object can be wrapped in parentheses to prevent this, as shown in the examples below.

58 |

Examples

59 |

The following example defines a function array which can be called; when called, it calls each element of the array in turn.

60 |
class FuncArrayType extends Array {
 61 |     Call(params*) {
 62 |         ; Call a list of functions.
 63 |         for fn in this
 64 |             fn(params*)
 65 |     }
 66 | }
 67 | 
 68 | ; Create an array of functions.
 69 | funcArray := FuncArrayType()
 70 | ; Add some functions to the array (can be done at any point).
 71 | funcArray.Push(One)
 72 | funcArray.Push(Two)
 73 | ; Create an object which uses the array as a method.
 74 | obj := {method: funcArray}
 75 | ; Call the method (and consequently both One and Two).
 76 | obj.method("2nd")
 77 | ; Call it as a function.
 78 | (obj.method)("1st", "2nd")
 79 | 
 80 | One(param1, param2) {
 81 |     ListVars
 82 |     MsgBox
 83 | }
 84 | Two(param1, param2) {
 85 |     ListVars
 86 |     MsgBox
 87 | }
88 | 89 |

BoundFunc Object

90 |

Acts like a function, but just passes predefined parameters to another function.

91 |

There are two ways that BoundFunc objects can be created:

92 |
    93 |
  • By calling the Func.Bind method, which binds parameter values to a function.
  • 94 |
  • By calling the ObjBindMethod function, which binds parameter values and a method name to a target object.
  • 95 |
96 |

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:

97 |
fn := RealFn.Bind(1)  ; Bind first parameter only
 98 | fn(2)      ; Shows "1, 2"
 99 | fn.Call(3) ; Shows "1, 3"
100 | 
101 | fn := RealFn.Bind( , 1)  ; Bind second parameter only
102 | fn(2, 0)   ; Shows "2, 1, 0"
103 | fn.Call(3) ; Shows "3, 1"
104 | fn(, 4)    ; Error: 'a' was omitted
105 | 
106 | RealFn(a, b, c?) {
107 |     MsgBox a ", " b (IsSet(c) ? ", " c : "")
108 | }
109 |

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:

110 |
Shell := ComObject("Shell.Application")
111 | RunBox := ObjBindMethod(Shell, "FileRun")
112 | ; Show the Run dialog.
113 | RunBox
114 |

For a more complex example, see SetTimer.

115 |

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:

116 |
Func_Bind(fn, bound_args*) {
117 |     return (args*) => (args.InsertAt(1, bound_args*), fn(args*))
118 | }
119 | 120 | 121 | 122 | -------------------------------------------------------------------------------- /docs/misc/ImageHandles.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Image Handles - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Image Handles

14 | 15 |

To use an icon or bitmap handle in place of an image filename, use the following syntax:

16 |
HBITMAP:BitmapHandle
17 | HICON:IconHandle
18 |

Replace BitmapHandle or IconHandle with the actual handle value. For example, "hicon:" handle, where handle is a variable containing an icon handle.

19 |

The following things support this syntax:

20 |
    21 |
  • Gui.AddPicture (and GuiControl.Value when setting a Picture control's content).
  • 22 |
  • IL_Add
  • 23 |
  • LoadPicture
  • 24 |
  • SB.SetIcon
  • 25 |
  • ImageSearch
  • 26 |
  • TraySetIcon or Menu.SetIcon
  • 27 |
28 |

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.

30 | 31 |

Examples

32 |
33 |

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 |
63 |

See also LoadPicture example #1.

64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /docs/misc/Labels.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Labels - Syntax & Usage | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Labels

14 | 15 |

Table of Contents

16 |
    17 |
  • Syntax and Usage
  • 18 |
  • Look-alikes
  • 19 |
  • Dynamic Labels
  • 20 |
  • Named Loops
  • 21 |
  • Related
  • 22 |
23 | 24 |

Syntax and Usage

25 |

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:

31 |
run_notepad_1:
32 | run_notepad_2:
33 |     Run "notepad"
34 |     return
35 |

Execution: Like directives, labels have no effect when reached during normal execution.

36 | 37 |

Look-alikes

38 |

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 |

Dynamic Labels

45 |

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 |

Named Loops

48 |

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 |

Related

51 |

Functions, IsLabel, Goto, Break, Continue

52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /docs/misc/Languages.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Language Codes | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Language Codes

14 | 15 |

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.

18 |
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 | Long Paths | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Long Paths

14 | 15 |

In general, programs are affected by two kinds of path length limitations:

16 |
    17 |
  1. Functions provided by the operating system generally limit paths to 259 characters, with some exceptions.
  2. 18 |
  3. Code for dealing with paths within the program may rely on the first limitation to simplify the code, effectively placing another 259 character limitation.
  4. 19 |
20 |

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.

21 |

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 |
    23 |
  • Long paths can be enabled for AutoHotkey and all other long-path-aware programs on Windows 10. Refer to the Microsoft documentation for details. In short, this enables most functions to transparently work with long paths, but requires Windows 10 version 1607 or later.
  • 24 |
  • In many cases, prefixing the path with \\?\ 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.
  • 25 |
26 | 27 |

Long Path Prefix

28 |

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.

29 |

In particular, normalization:

30 |
    31 |
  • Resolves relative paths such as dir\file.ext, \file.ext and C:file.ext (note the absence of a slash).
  • 32 |
  • Resolves relative components such as \.. and \..
  • 33 |
  • Canonicalizes component/directory separators, replacing / with \ and eliminating redundant separators.
  • 34 |
  • Trims certain characters, such as a single period at the end of a component (dir.\file) or trailing spaces and periods (dir\filename . .).
  • 35 |
36 |

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:\).

45 | 46 |

Known Limitations

47 |

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 |
    50 |
  • DllCall (for DllFile and Function)
  • 51 |
  • DirCopy
  • 52 |
  • DirDelete, unless Recurse is false
  • 53 |
  • DirMove, unless the R option is used
  • 54 |
  • FileCreateShortcut
  • 55 |
  • FileGetShortcut
  • 56 |
  • FileRecycle
  • 57 |
  • SoundPlay (for this, the limit is 127 characters)
  • 58 |
  • DriveSetLabel and DriveGet variants (except DriveGetType)
  • 59 |
  • Built-in variables which return special folder paths (for which long paths might be impossible anyway): A_AppData, A_Desktop, A_MyDocuments, A_ProgramFiles, A_Programs, A_StartMenu, A_Startup and Common variants, A_Temp and A_WinDir
  • 60 |
61 |

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.

62 |

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 |
    64 |
  • ahk_exe
  • 65 |
  • The default script's path, which is based on the current executable's path.
  • 66 |
  • Retrieval of the AutoHotkey installation directory, which is used by A_AhkPath in compiled scripts and may be used to launch Window Spy or the help file.
  • 67 |
  • WinGetProcessPath.
  • 68 |
  • WinGetProcessName (this theoretically isn't a problem since it is applied only to the name portion, and NTFS only supports names up to 255 chars).
  • 69 |
70 |

Long #Include paths shown in error messages may be truncated arbitrarily.

71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /docs/misc/Macros.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Creating a Keyboard Macro or Mouse Macro | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Creating a Keyboard Macro or Mouse Macro

15 | 16 |

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 | Overriding or Disabling External Hotkeys | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Overriding or Disabling External Hotkeys

14 | 15 |

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::return
23 |

Similarly, to disable both Win, use this:

24 |
LWin::return
25 | RWin::return
26 |

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 | Script Performance | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Script Performance

14 | 15 |

The following functions may affect performance depending on the nature of the script: SendMode, SetKeyDelay, SetMouseDelay, SetWinDelay, SetControlDelay, and SetDefaultMouseSpeed.

16 |

Built-in Performance Features

17 |

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 |
    20 |
  • Loops, blocks, IFs, ELSEs and other control flow statements are given the memory addresses of their related jump-points in the script.
  • 21 |
  • Each statement name is replaced by an address in a jump table.
  • 22 |
  • Each expression is tokenized and converted from infix to postfix.
  • 23 |
  • Each reference to a variable or function is resolved to a memory address, unless it is dynamic.
  • 24 |
  • Literal integers in expressions are replaced with binary integers.
  • 25 |
  • The destination of each Goto is resolved to a memory address unless it is a variable.
  • 26 |
27 |

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 | Regular Expressions (RegEx) - Quick Reference | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |

Regular Expressions (RegEx) - Quick Reference

13 | 14 |

Table of Contents

15 |
    16 |
  • Fundamentals
  • 17 |
  • Options (case-sensitive)
  • 18 |
  • Commonly Used Symbols and Syntax
  • 19 |
20 | 21 |

Fundamentals

22 |

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.

24 |

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 |

Options (case-sensitive)

27 |

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 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 |
OptionDescription
iCase-insensitive matching, which treats the letters A through Z as identical to their lowercase counterparts.
m

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.

sDotAll. 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.
xIgnores 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.
AForces 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 "^".
DForces 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.
JAllows 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.
UUngreedy. 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.
XPCRE_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).
SStudies 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).
CEnables the auto-callout mode. See Regular Expression Callouts for more info.
`a

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 |
`nCauses a solitary linefeed (`n) to be the only recognized newline marker (see above).
`rCauses a solitary carriage return (`r) to be the only recognized newline marker (see above).
97 |

Note: Spaces and tabs may optionally be used to separate each option from the next.

98 | 99 |

Commonly Used Symbols and Syntax

100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 126 | 127 | 128 | 129 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 175 | 176 | 177 | 178 | 180 | 181 | 182 | 183 | 185 | 186 | 187 | 188 | 190 | 191 |
ElementDescription
.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_.
*

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.

?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.
+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.
{min,max}

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.

[...]

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].

[^...]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.
\dMatches 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".
\sMatches any single whitespace character, mainly space, tab, and newline (`r and `n). Conversely, capital \S means "any non-whitespace character".
\wMatches any single "word" character, namely alphanumeric or underscore. This is equivalent to [a-zA-Z0-9_]. Conversely, capital \W means "any non-word character".
^
$

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.

\b\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.
|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.
(...)

Items enclosed in parentheses are most commonly used to:

169 |
    170 |
  • Determine the order of evaluation. For example, (Sun|Mon|Tues|Wednes|Thurs|Fri|Satur)day matches the name of any day.
  • 171 |
  • Apply *, ?, +, or {min,max} to a series of characters rather than just one. For example, (abc)+ matches one or more occurrences of the string "abc"; thus it matches abcabc123 but not ab123 or bc123.
  • 172 |
  • Capture a subpattern such as the dot-star in abc(.*)xyz. For example, RegExMatch stores the substring that matches each subpattern in its output array. Similarly, RegExReplace allows the substring that matches each subpattern to be reinserted into the result via backreferences like $1. To use the parentheses without the side-effect of capturing a subpattern, specify ?: as the first two characters inside the parentheses; for example: (?:.*)
  • 173 |
  • Change options on-the-fly. For example, (?im) turns on the case-insensitive and multiline options for the remainder of the pattern (or subpattern if it occurs inside a subpattern). Conversely, (?-im) would turn them both off. All options are supported except DPS`r`n`a.
  • 174 |
\t
\r
etc.

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 `r`n, `n and `r (however, \R inside a character class is merely the letter "R").

\p{xx}
\P{xx}
\X

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.

(*UCP)

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 |
192 |

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 | Regular Expression Callouts | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Regular Expression Callouts

14 | 15 |

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 |

Table of Contents

20 |
    21 |
  • Syntax
  • 22 |
  • RegEx Callout Functions
  • 23 |
  • EventInfo
  • 24 |
  • Auto-Callout
  • 25 |
  • Remarks
  • 26 |
27 | 28 |

Syntax

29 | 30 |

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.

31 |

A callout function must be provided by either formally defining it or assigning it to a variable within the scope of the function which called RegExMatch or RegExReplace (local or global). If Function is omitted, it defaults to pcre_callout. If no variable is found or its value is not a function object, an error is thrown.

32 | 33 |

RegEx Callout Functions

34 | 35 |
MyFunction(Match, CalloutNumber, FoundPos, Haystack, NeedleRegEx)
 36 | {
 37 |     ...
 38 | }
39 |

RegEx callout functions may define up to 5 parameters:

40 |
    41 |
  • Match: Receives a RegExMatchInfo object containing information about the match so far.
  • 42 |
  • CalloutNumber: Receives the Number of the RegEx callout.
  • 43 |
  • FoundPos: Receives the position of the current potential match.
  • 44 |
  • Haystack: Receives the Haystack passed to RegExMatch or RegExReplace.
  • 45 |
  • NeedleRegEx: Receives the NeedleRegEx passed to RegExMatch or RegExReplace.
  • 46 |
47 |

These names are suggestive only. Actual names may vary.

48 | 49 |

Warning: Changing the input parameters of RegExReplace or RegExMatch during a call is unsupported and may cause unpredictable behaviour.

50 | 51 |

Pattern-matching may proceed or fail depending on the return value of the RegEx callout function:

52 |
    53 |
  • If the function returns 0 or does not return a numeric value, matching proceeds as normal.
  • 54 |
  • If the function returns 1 or greater, matching fails at the current point, but the testing of other matching possibilities goes ahead.
  • 55 |
  • If the function returns -1, matching is abandoned.
  • 56 |
  • If the function returns a value less than -1, it is treated as a PCRE error code and matching is abandoned. This causes RegExMatch and RegExReplace to throw an exception; the Extra property of the exception object contains the error code.
  • 57 |
58 | 59 |

For example:

60 |
Haystack := "The quick brown fox jumps over the lazy dog."
 61 | RegExMatch(Haystack, "i)(The) (\w+)\b(?CCallout)")
 62 | Callout(m, *) {
 63 |     MsgBox "m[0]=" m[0] "`nm[1]=" m[1] "`nm[2]=" m[2]
 64 |     return 1
 65 | }
66 |

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.

67 |

If any of the input parameters to a RegEx function is modified during a callout, the behaviour is undefined.

68 | 69 |

EventInfo

70 | 71 |

Additional information is available by accessing the pcre_callout_block structure via A_EventInfo.

72 |
version           := NumGet(A_EventInfo,  0, "Int")
 73 | callout_number    := NumGet(A_EventInfo,  4, "Int")
 74 | offset_vector     := NumGet(A_EventInfo,  8, "Ptr")
 75 | subject           := NumGet(A_EventInfo,  8 + A_PtrSize, "Ptr")
 76 | subject_length    := NumGet(A_EventInfo,  8 + A_PtrSize*2, "Int")
 77 | start_match       := NumGet(A_EventInfo, 12 + A_PtrSize*2, "Int")
 78 | current_position  := NumGet(A_EventInfo, 16 + A_PtrSize*2, "Int")
 79 | capture_top       := NumGet(A_EventInfo, 20 + A_PtrSize*2, "Int")
 80 | capture_last      := NumGet(A_EventInfo, 24 + A_PtrSize*2, "Int")
 81 | pad := A_PtrSize=8 ? 4 : 0  ; Compensate for 64-bit data alignment.
 82 | callout_data      := NumGet(A_EventInfo, 28 + pad + A_PtrSize*2, "Ptr")
 83 | pattern_position  := NumGet(A_EventInfo, 28 + pad + A_PtrSize*3, "Int")
 84 | next_item_length  := NumGet(A_EventInfo, 32 + pad + A_PtrSize*3, "Int")
 85 | if (version >= 2)
 86 |     mark   := StrGet(NumGet(A_EventInfo, 36 + pad + A_PtrSize*3, "Int"), "UTF-8")
 87 | 
88 |

For more information, see pcre.txt, NumGet and A_PtrSize.

89 | 90 |

Auto-Callout

91 | 92 |

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:

93 |
; Call RegExMatch with auto-callout option C.
 94 | RegExMatch("xxxabc123xyz", "C)abc.*xyz")
 95 | 
 96 | ; Define the default RegEx callout function.
 97 | pcre_callout(Match, CalloutNumber, FoundPos, Haystack, NeedleRegEx)
 98 | {
 99 |     ; See pcre.txt for descriptions of these fields.
100 |     start_match       := NumGet(A_EventInfo, 12 + A_PtrSize*2, "Int")
101 |     current_position  := NumGet(A_EventInfo, 16 + A_PtrSize*2, "Int")
102 |     pad := A_PtrSize=8 ? 4 : 0
103 |     pattern_position  := NumGet(A_EventInfo, 28 + pad + A_PtrSize*3, "Int")
104 |     next_item_length  := NumGet(A_EventInfo, 32 + pad + A_PtrSize*3, "Int")
105 | 
106 |     ; Point out >>current match<<.
107 |     _HAYSTACK:=SubStr(Haystack, 1, start_match)
108 |         . ">>" SubStr(Haystack, start_match + 1, current_position - start_match)
109 |         . "<<" SubStr(Haystack, current_position + 1)
110 |     
111 |     ; Point out >>next item to be evaluated<<.
112 |     _NEEDLE:=  SubStr(NeedleRegEx, 1, pattern_position)
113 |         . ">>" SubStr(NeedleRegEx, pattern_position + 1, next_item_length)
114 |         . "<<" SubStr(NeedleRegEx, pattern_position + 1 + next_item_length)
115 |     
116 |     ListVars
117 |     ; Press Pause to continue.
118 |     Pause
119 | }
120 | 121 |

Remarks

122 | 123 |

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.

124 |

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.

125 | 126 | 127 | 128 | -------------------------------------------------------------------------------- /docs/misc/Remap.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Remapping Keys (Keyboard, Mouse and Controller) | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Remapping Keys (Keyboard, Mouse and Controller)

15 | 16 |

Table of Contents

17 |
    18 |
  • Introduction
  • 19 |
  • Remapping the Keyboard and Mouse
  • 20 |
  • Remarks
  • 21 |
  • Moving the Mouse Cursor via the Keyboard
  • 22 |
  • Remapping via the Registry's "Scancode Map"
  • 23 |
  • Related Topics
  • 24 |
25 | 26 |

Introduction

27 |

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 |

Remapping the Keyboard and Mouse

29 |

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:

30 |
a::b
31 |

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::a
34 |

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::B
36 |

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::b
39 | 40 |

Mouse Remapping

41 |

To remap the mouse instead of the keyboard, use the same approach. For example:

42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 |
ExampleDescription
MButton::ShiftMakes the middle button behave like Shift.
XButton1::LButtonMakes the fourth mouse button behave like the left mouse button.
RAlt::RButtonMakes the right Alt behave like the right mouse button.
60 | 61 |

Other Useful Remappings

62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 |
ExampleDescription
CapsLock::CtrlMakes 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.
XButton2::^LButtonMakes the fifth mouse button (XButton2) produce a control-click.
RAlt::AppsKeyMakes the right Alt become Menu (which is the key that opens the context menu).
RCtrl::RWinMakes the right Ctrl become the right Win.
Ctrl::AltMakes both Ctrl behave like Alt. However, see alt-tab issues.
^x::^cMakes Ctrl+X produce Ctrl+C. It also makes Ctrl+Alt+X produce Ctrl+Alt+C, etc.
RWin::ReturnDisables the right Win by having it simply return.
96 |

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 |

Remarks

99 |

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 |
    105 |
  • Holding down a modifier such as Ctrl or Shift while typing the origin key will put that modifier into effect for the destination key. For example, b::a would produce Ctrl+A if you press Ctrl+B.
  • 106 |
  • CapsLock generally affects remapped keys in the same way as normal keys.
  • 107 |
  • The destination key or button is held down for as long as you continue to hold down the origin key. However, some games do not support remapping; in such cases, the keyboard and mouse will behave as though not remapped.
  • 108 |
  • Remapped keys will auto-repeat while being held down (except keys remapped to become mouse buttons).
  • 109 |
110 |

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:

111 |
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.

123 |

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.

124 |

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:

125 |
*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 |
    138 |
  1. When the source key is the left Ctrl and the destination key is Alt, the line 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.
  2. 139 |
  3. When a keyboard key is being remapped to become a mouse button (e.g. 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 |
  4. 147 |
  5. When the source is a custom combination, the wildcard modifier (*) is omitted to allow the hotkeys to work.
  6. 148 |
  7. If any of the modifier symbols in !#^+ 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.
  8. 149 |
150 |

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.

151 |

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.

152 |
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.

155 |

In addition to the keys and mouse buttons on the Key List page, the source and destination keys may also be a virtual key (VKnn) or scan code (SCnnn) as described in the Special Keys section. For example, sc01e::vk42 is equivalent to a::b on most keyboard layouts.

156 |

To disable a key rather than remapping it, make it a hotkey that simply returns. For example, F1::return would disable F1.

157 |

The following keys are not supported by the built-in remapping method:

158 |
    159 |
  • The mouse wheel (WheelUp/Down/Left/Right).
  • 160 |
  • "Pause" as a destination key name (since it matches the name of a built-in function). Instead use vk13 or the corresponding scan code.
  • 161 |
  • Curly braces {} as destination keys. Instead use the VK/SC method; e.g. x::+sc01A and y::+sc01B.
  • 162 |
163 |

Moving the Mouse Cursor via the Keyboard

164 |

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 |

Remapping via the Registry's "Scancode Map"

184 |

Advantages:

185 |
    186 |
  • Registry remapping is generally more pure and effective than AutoHotkey's remapping. For example, it works in a broader variety of games, it has no known alt-tab issues, and it is capable of firing AutoHotkey's hook hotkeys (whereas AutoHotkey's remapping requires a workaround).
  • 187 |
  • If you choose to make the registry entries manually (explained below), absolutely no external software is needed to remap your keyboard. Even if you use KeyTweak to make the registry entries for you, KeyTweak does not need to stay running all the time (unlike AutoHotkey).
  • 188 |
189 |

Disadvantages:

190 |
    191 |
  • Registry remapping is relatively permanent: a reboot is required to undo the changes or put new ones into effect.
  • 192 |
  • Its effect is global: it cannot create remappings specific to a particular user, application, or locale.
  • 193 |
  • It cannot send keystrokes that are modified by Shift, Ctrl, Alt, or AltGr. For example, it cannot remap a lowercase character to an uppercase one.
  • 194 |
  • It supports only the keyboard (AutoHotkey has mouse remapping and some limited controller remapping).
  • 195 |
196 |

How to Apply Changes to the Registry: There are at least two methods to remap keys via the registry:

197 |
    198 |
  1. Use a program like KeyTweak (freeware) to visually remap your keys. It will change the registry for you.
  2. 199 |
  3. Remap keys manually by creating a .reg file (plain text) and loading it into the registry. This is demonstrated in the archived forums.
  4. 200 |
201 |

Related Topics

202 |
    203 |
  • List of keys, mouse buttons and controller controls
  • 204 |
  • GetKeyState
  • 205 |
  • Remapping a controller
  • 206 |
207 | 208 | 209 | -------------------------------------------------------------------------------- /docs/misc/RemapController.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Remapping a Controller to Keyboard or Mouse | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Remapping a Controller to Keyboard or Mouse

15 | 16 |

Table of Contents

17 |
    18 |
  • Important Notes
  • 19 |
  • Making a Controller Button Send Keystrokes or Mouse Clicks 20 |
      21 |
    • Different Approaches
    • 22 |
    • Auto-repeating a Keystroke
    • 23 |
    • Context-sensitive Controller Buttons
    • 24 |
    • Using a Controller as a Mouse
    • 25 |
  • 26 |
  • Making Other Controller Controls Send Keystrokes or Mouse Clicks 27 |
      28 |
    • Controller Axes
    • 29 |
    • Controller POV Hat
    • 30 |
    • Auto-repeating a Keystroke
    • 31 |
  • 32 |
  • Remarks
  • 33 |
  • Related Topics
  • 34 |
35 | 36 |

Important Notes

37 |
    38 |
  • 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.
  • 39 |
  • Although a controller button or axis can be remapped to become a key or mouse button, it cannot be remapped to some other controller button or axis. That would be possible only with the help of a controller emulator such as vJoy.
  • 40 |
  • AutoHotkey identifies each button on a controller with a unique number between 1 and 32. To determine these numbers, use the controller test script.
  • 41 |
  • For Xbox controller 2013 and newer (anything newer than the Xbox 360 controller), Joy1 to Joy32 hotkeys will only work if a window owned by the script is active, such as a message box, GUI, or the script's main window. This limitation also applies to GetKeyState for Joy1 to Joy32 and JoyX, JoyY, JoyZ, JoyR, JoyU, JoyPOV (and possibly JoyV), but not for JoyName, JoyButtons, JoyAxes and JoyInfo. To detect those controller inputs for other active windows, use the XInput.ahk library.
  • 42 |
43 | 44 |

Making a Controller Button Send Keystrokes or Mouse Clicks

45 | 46 |

Different Approaches

47 |

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 |

Method #1

50 |

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 |

Method #2

67 |

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 |

Method #3

76 |

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 |

Auto-repeating a Keystroke

94 |

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 |

Context-sensitive Controller Buttons

114 |

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 |

Using a Controller as a Mouse

117 |

The Controller-To-Mouse script converts a controller into a mouse by remapping its buttons and axis control.

118 | 119 |

Making Other Controller Controls Send Keystrokes or Mouse Clicks

120 |

To have a script respond to movement of a stick's axis or POV hat, use SetTimer and GetKeyState.

121 | 122 |

Controller Axes

123 |

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 |

Controller POV Hat

156 |

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 |

Auto-repeating a Keystroke

192 |

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 |

Remarks

201 |

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.

202 |

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 |

Related Topics

204 |
    205 |
  • Controller-To-Mouse script (using a controller as a mouse)
  • 206 |
  • List of controller buttons, axes, and controls
  • 207 |
  • GetKeyState
  • 208 |
  • Remapping the keyboard and mouse
  • 209 |
210 | 211 | 212 | 213 | -------------------------------------------------------------------------------- /docs/misc/SendMessage.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | PostMessage / SendMessage Tutorial | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

PostMessage / SendMessage Tutorial by Rajat

14 | 15 |

This page explains how to send messages to a window or its controls via PostMessage or SendMessage and will answer some questions like:

16 |
    17 |
  • "How do I press a button on a minimized window?"
  • 18 |
  • "How do I select a menu item when MenuSelect doesn't work with it?!"
  • 19 |
  • "This is a skinnable window.... how do I send a command that works every time?"
  • 20 |
  • "and what about hidden windows?!"
  • 21 |
22 |

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 |
    29 |
  1. Open Winspector Spy and a "New Message" window.
  2. 30 |
  3. Drag the crosshair from Winspector Spy's window to "New Message" window's titlebar (the portion not covered by Winspector Spy's overlay).
  4. 31 |
  5. Right click the selected window in the list on left and select 'Messages'.
  6. 32 |
  7. Right click the blank window and select 'Edit message filter'.
  8. 33 |
  9. Press the 'filter all' button and then dbl click 'wm_command' on the list on left. This way you will only monitor this message.
  10. 34 |
  11. Now go to the "New Message" window and select from its menu bar: Insert > Picture.
  12. 35 |
  13. Come back to Winspector Spy and press the traffic light button to pause monitoring.
  14. 36 |
  15. Expand the wm_command messages that've accumulated (forget others if any).
  16. 37 |
  17. What you want to look for (usually) is a code 0 message. sometimes there are wm_command messages saying 'win activated' or 'win destroyed' and other stuff.. not needed. You'll find that there's a message saying 'Control ID: 40239' ...that's it!
  18. 38 |
  19. Now put that in the above function and you've got it! It's the wParam value.
  20. 39 |
40 |

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 |
    75 |
  • The note above regarding OS being XP and msg values changing with different OSes is purely cautionary. if you've found a msg that works on your system (with a certain version of a software) then you can be sure it'll work on another system too with the same version of the software. In addition, most apps keep these msg values the same even on different versions of themselves (e.g. Windows Media Player and Winamp).
  • 76 |
  • If you've set the filter to show only wm_command in Winspector Spy and still you're getting a flood of messages then right click that message and select hide (msg name)... you don't want to have a look at a msg that appears without you interacting with the target software.
  • 77 |
  • The right pointing arrow in Winspector Spy shows the msg values and the blurred left pointing arrows show the returned value. A 0 (zero) value can by default safely be taken as 'no error'.
  • 78 |
  • For posting to hidden windows add this to script: DetectHiddenWindows True
  • 79 |
80 |

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 | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Windows Messages

14 | 15 |

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 |
    20 |
  • 0 through 0x03FF: Messages reserved for use by the system.
  • 21 |
  • 0x0400 (WM_USER) through 0x7FFF: Integer messages for use by private window classes.
  • 22 |
  • 0x8000 (WM_APP) through 0xBFFF: Messages available for use by applications. Messages in this range do not conflict with system messages.
  • 23 |
  • 0xC000 through 0xFFFF: String messages for use by applications. Messages in this range are defined at runtime via the system's function RegisterWindowMessage.
  • 24 |
  • Greater than 0xFFFF: Reserved by the system.
  • 25 |
26 |

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 := 0x8000
251 | 252 | 253 | -------------------------------------------------------------------------------- /docs/misc/Styles.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Window and Control Styles | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Window and Control Styles

14 |

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 |

Table of Contents

17 |
    18 |
  • Styles Common to Gui/Parent Windows and Most Control Types
  • 19 |
  • Text | Edit | UpDown | Picture
  • 20 |
  • Button | CheckBox | Radio | GroupBox
  • 21 |
  • DropDownList | ComboBox
  • 22 |
  • ListBox | ListView | TreeView
  • 23 |
  • DateTime | MonthCal
  • 24 |
  • Slider | Progress | Tab | StatusBar
  • 25 |
26 | 27 |

Common Styles

28 |

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 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 |
StyleHexDescription
WS_BORDER0x800000+/-Border. Creates a window that has a thin-line border.
WS_POPUP0x80000000Creates a pop-up window. This style cannot be used with the WS_CHILD style.
WS_CAPTION0xC00000+/-Caption. Creates a window that has a title bar. This style is a numerical combination of WS_BORDER and WS_DLGFRAME.
WS_CLIPSIBLINGS0x4000000Clips 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.
WS_DISABLED0x8000000+/-Disabled. Creates a window that is initially disabled.
WS_DLGFRAME0x400000Creates a window that has a border of a style typically used with dialog boxes.
WS_GROUP0x20000+/-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.
WS_HSCROLL0x100000Creates a window that has a horizontal scroll bar.
WS_MAXIMIZE0x1000000Creates a window that is initially maximized.
WS_MAXIMIZEBOX0x10000+/-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.
WS_MINIMIZE0x20000000Creates a window that is initially minimized.
WS_MINIMIZEBOX0x20000+/-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.
WS_OVERLAPPED0x0Creates an overlapped window. An overlapped window has a title bar and a border. Same as the WS_TILED style.
WS_OVERLAPPEDWINDOW0xCF0000Creates 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.
WS_POPUPWINDOW0x80880000Creates 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.
WS_SIZEBOX0x40000+/-Resize. Creates a window that has a sizing border. Same as the WS_THICKFRAME style.
WS_SYSMENU0x80000+/-SysMenu. Creates a window that has a window menu on its title bar. The WS_CAPTION style must also be specified.
WS_TABSTOP0x10000+/-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.
WS_THICKFRAME0x40000Creates a window that has a sizing border. Same as the WS_SIZEBOX style.
WS_VSCROLL0x200000Creates a window that has a vertical scroll bar.
WS_VISIBLE0x10000000Creates a window that is initially visible.
WS_CHILD0x40000000Creates a child window. A window with this style cannot have a menu bar. This style cannot be used with the WS_POPUP style.
146 | 147 |

Text Control Styles

148 |

These styles affect the Text control. It has neither default styles nor forced styles.

149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 |
StyleHexDescription
SS_BLACKFRAME0x7Specifies a box with a frame drawn in the same color as the window frames. This color is black in the default color scheme.
SS_BLACKRECT0x4Specifies a rectangle filled with the current window frame color. This color is black in the default color scheme.
SS_CENTER0x1+/-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.
SS_CENTERIMAGE0x200 174 |

If the control contains a single line of text, the text is centered vertically within the available height of the control.

175 |
SS_ETCHEDFRAME0x12Draws the frame of the static control using the EDGE_ETCHED edge style.
SS_ETCHEDHORZ0x10Draws the top and bottom edges of the static control using the EDGE_ETCHED edge style.
SS_ETCHEDVERT0x11Draws the left and right edges of the static control using the EDGE_ETCHED edge style.
SS_GRAYFRAME0x8Specifies a box with a frame drawn with the same color as the screen background (desktop). This color is gray in the default color scheme.
SS_GRAYRECT0x5Specifies a rectangle filled with the current screen background color. This color is gray in the default color scheme.
SS_LEFT0x0+/-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.
SS_LEFTNOWORDWRAP0xC+/-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.
SS_NOPREFIX0x80Prevents 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.
SS_NOTIFY0x100Sends the parent window the STN_CLICKED notification when the user clicks the control.
SS_RIGHT0x2+/-Right. Specifies a rectangle and right-aligns the specified text in the rectangle.
SS_SUNKEN0x1000Draws a half-sunken border around a static control.
SS_WHITEFRAME0x9Specifies a box with a frame drawn with the same color as the window background. This color is white in the default color scheme.
SS_WHITERECT0x6Specifies a rectangle filled with the current window background color. This color is white in the default color scheme.
243 | 244 |

Edit Control Styles

245 |

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 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 |
StyleHexDescription
ES_AUTOHSCROLL0x80+/-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.
ES_AUTOVSCROLL0x40Scrolls text up one page when the user presses Enter on the last line.
ES_CENTER0x1+/-Center. Centers text in a multiline edit control.
ES_LOWERCASE0x10+/-Lowercase. Converts all characters to lowercase as they are typed into the edit control.
ES_NOHIDESEL0x100Negates 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.
ES_NUMBER0x2000+/-Number. Prevents the user from typing anything other than digits in the control.
ES_OEMCONVERT0x400This style is most useful for edit controls that contain file names.
ES_MULTILINE0x4+/-Multi. Designates a multiline edit control. The default is a single-line edit control.
ES_PASSWORD0x20+/-Password. Displays a masking character in place of each character that is typed into the edit control, which conceals the text.
ES_READONLY0x800+/-ReadOnly. Prevents the user from typing or editing text in the edit control.
ES_RIGHT0x2+/-Right. Right-aligns text in a multiline edit control.
ES_UPPERCASE0x8+/-Uppercase. Converts all characters to uppercase as they are typed into the edit control.
ES_WANTRETURN0x1000+/-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.
320 | 321 |

UpDown Control Styles

322 |

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 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 |
StyleHexDescription
UDS_WRAP0x1Named 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.
UDS_SETBUDDYINT0x2Causes 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.
UDS_ALIGNRIGHT0x4Named option "Right" (default). Positions UpDown on the right side of its buddy control.
UDS_ALIGNLEFT0x8Named option "Left". Positions UpDown on the left side of its buddy control.
UDS_AUTOBUDDY0x10Automatically selects the previous control in the z-order as the UpDown control's buddy control.
UDS_ARROWKEYS0x20Allows the user to press ↑ or ↓ on the keyboard to increase or decrease the UpDown control's position.
UDS_HORZ0x40Named option "Horz". Causes the control's arrows to point left and right instead of up and down.
UDS_NOTHOUSANDS0x80Does not insert a thousands separator between every three decimal digits in the buddy control.
UDS_HOTTRACK0x100Causes 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.
375 | 376 |

Picture Control Styles

377 |

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 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 395 | 396 |
StyleHexDescription
SS_REALSIZECONTROL0x40Adjusts the bitmap to fit the size of the control.
SS_CENTERIMAGE0x200 393 |

Centers the bitmap in the control. If the bitmap is too large, it will be clipped.

394 |
397 | 398 |

Button, CheckBox, Radio, and GroupBox Control Styles

399 |

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 |
    403 |
  • Button: BS_PUSHBUTTON or BS_DEFPUSHBUTTON
  • 404 |
  • CheckBox: BS_AUTOCHECKBOX or BS_AUTO3STATE
  • 405 |
  • Radio: BS_AUTORADIOBUTTON
  • 406 |
  • GroupBox: BS_GROUPBOX
  • 407 |
408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 494 | 495 | 496 | 497 | 498 | 499 |
StyleHexDescription
BS_AUTO3STATE0x6Creates 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.
BS_AUTOCHECKBOX0x3Creates 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.
BS_AUTORADIOBUTTON0x9Creates 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.
BS_LEFT0x100+/-Left. Left-aligns the text.
BS_PUSHBUTTON0x0Creates a push button that posts a WM_COMMAND message to the owner window when the user selects the button.
BS_PUSHLIKE0x1000Makes 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.
BS_RIGHT0x200+/-Right. Right-aligns the text.
BS_RIGHTBUTTON0x20+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.
BS_BOTTOM0x800Places the text at the bottom of the control's available height.
BS_CENTER0x300+/-Center. Centers the text horizontally within the control's available width.
BS_DEFPUSHBUTTON0x1+/-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.
BS_MULTILINE0x2000+/-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.
BS_NOTIFY0x4000Enables 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.
BS_TOP0x400Places text at the top of the control's available height.
BS_VCENTER0xC00Vertically centers text in the control's available height.
BS_FLAT0x8000Specifies that the button is two-dimensional; it does not use the default shading to create a 3-D effect.
BS_GROUPBOX0x7Creates a rectangle in which other controls can be grouped. Any text associated with this style is displayed in the rectangle's upper left corner.
500 | 501 |

DropDownList and ComboBox Control Styles

502 |

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 |
    506 |
  • DropDownList: CBS_DROPDOWNLIST
  • 507 |
  • ComboBox: Either CBS_DROPDOWN or CBS_SIMPLE
  • 508 |
509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 | 520 | 521 | 522 | 523 | 524 | 525 | 526 | 527 | 528 | 529 | 530 | 531 | 532 | 533 | 534 | 535 | 536 | 537 | 538 | 539 | 540 | 541 | 542 | 543 | 544 | 545 | 546 | 547 | 548 | 549 | 550 | 551 | 552 | 553 | 554 | 555 | 556 | 557 | 558 | 559 | 560 | 561 | 562 | 563 | 564 | 565 |
StyleHexDescription
CBS_AUTOHSCROLL0x40+/-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.
CBS_DISABLENOSCROLL0x800Shows 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.
CBS_DROPDOWN0x2Similar to CBS_SIMPLE, except that the list box is not displayed unless the user selects an icon next to the edit control.
CBS_DROPDOWNLIST0x3Similar to CBS_DROPDOWN, except that the edit control is replaced by a static text item that displays the current selection in the list box.
CBS_LOWERCASE0x4000+/-Lowercase. Converts to lowercase any uppercase characters that are typed into the edit control of a combo box.
CBS_NOINTEGRALHEIGHT0x400Specifies 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.
CBS_OEMCONVERT0x80Converts 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.
CBS_SIMPLE0x1+/-Simple (ComboBox only). Displays the drop-down list at all times. The current selection in the list is displayed in the edit control.
CBS_SORT0x100+/-Sort. Sorts the items in the drop-list alphabetically.
CBS_UPPERCASE0x2000+/-Uppercase. Converts to uppercase any lowercase characters that are typed into the edit control of a ComboBox.
566 | 567 |

ListBox Control Styles

568 |

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 | 570 | 571 | 572 | 573 | 574 | 575 | 576 | 577 | 578 | 579 | 580 | 581 | 582 | 583 | 584 | 585 | 586 | 587 | 588 | 589 | 590 | 591 | 592 | 593 | 594 | 595 | 596 | 597 | 598 | 599 | 600 | 601 | 602 | 603 | 604 | 605 | 606 | 607 | 608 | 609 | 610 | 611 | 612 | 613 | 614 | 615 |
StyleHexDescription
LBS_DISABLENOSCROLL0x1000Shows 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.
LBS_NOINTEGRALHEIGHT0x100Specifies that the list box will be exactly the size specified by the application when it created the list box.
LBS_EXTENDEDSEL0x800+/-Multi. Allows multiple selections via control-click and shift-click.
LBS_MULTIPLESEL0x8A 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.
LBS_NOSEL0x4000+/-ReadOnly. Specifies that the user can view list box strings but cannot select them.
LBS_NOTIFY0x1Causes 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).
LBS_SORT0x2+/-Sort. Sorts the items in the list box alphabetically.
LBS_USETABSTOPS0x80Enables 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.
616 | 617 |

ListView Control Styles

618 |

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 | 620 | 621 | 622 | 623 | 624 | 625 | 626 | 627 | 628 | 629 | 630 | 631 | 632 | 633 | 634 | 635 | 636 | 637 | 638 | 639 | 640 | 641 | 642 | 643 | 644 | 645 | 646 | 647 | 648 | 649 | 650 | 651 | 652 | 653 | 654 | 655 | 656 | 657 | 658 | 659 | 660 | 661 | 662 | 663 | 664 | 665 | 666 | 667 | 668 | 669 | 670 | 671 | 672 | 673 | 674 | 675 | 676 | 677 | 678 | 679 | 680 | 681 | 682 | 683 | 684 | 685 | 686 | 687 | 688 | 689 | 690 | 691 | 692 | 693 | 694 | 695 | 696 | 697 | 698 | 699 | 700 | 701 | 702 | 703 | 704 | 705 | 706 | 707 | 708 | 709 | 710 | 711 | 712 | 713 | 714 | 715 | 716 | 717 | 718 | 719 | 720 |
StyleHexDescription
LVS_ALIGNLEFT0x800Items are left-aligned in icon and small icon view.
LVS_ALIGNTOP0x0Items are aligned with the top of the list-view control in icon and small icon view. This is the default.
LVS_AUTOARRANGE0x100Icons are automatically kept arranged in icon and small icon view.
LVS_EDITLABELS0x200+/-ReadOnly. Specifying -ReadOnly (or +0x200) allows the user to edit the first field of each row in place.
LVS_ICON0x0+Icon. Specifies large-icon view.
LVS_LIST0x3+List. Specifies list view.
LVS_NOCOLUMNHEADER0x4000+/-Hdr. Avoids displaying column headers in report view.
LVS_NOLABELWRAP0x80Item text is displayed on a single line in icon view. By default, item text may wrap in icon view.
LVS_NOSCROLL0x2000Scrolling is disabled. All items must be within the client area. This style is not compatible with the LVS_LIST or LVS_REPORT styles.
LVS_NOSORTHEADER0x8000+/-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.
LVS_OWNERDATA0x1000This style specifies a virtual list-view control (not directly supported by AutoHotkey).
LVS_OWNERDRAWFIXED0x400The owner window can paint items in report view in response to WM_DRAWITEM messages (not directly supported by AutoHotkey).
LVS_REPORT0x1+Report. Specifies report view.
LVS_SHAREIMAGELISTS0x40The 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.
LVS_SHOWSELALWAYS0x8The selection, if any, is always shown, even if the control does not have keyboard focus.
LVS_SINGLESEL0x4+/-Multi. Only one item at a time can be selected. By default, multiple items can be selected.
LVS_SMALLICON0x2+IconSmall. Specifies small-icon view.
LVS_SORTASCENDING0x10+/-Sort. Rows are sorted in ascending order based on the contents of the first field.
LVS_SORTDESCENDING0x20+/-SortDesc. Same as above but in descending order.
721 |

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 | 723 | 724 | 725 | 726 | 727 | 728 | 729 | 730 | 731 | 732 | 733 | 734 | 735 | 736 | 740 | 741 | 742 | 743 | 744 | 747 | 748 | 749 | 750 | 751 | 752 | 753 | 754 | 755 | 756 | 757 | 758 | 759 | 760 | 761 | 762 | 763 | 764 | 765 | 766 | 767 | 768 | 769 | 770 | 771 | 772 | 773 | 774 | 775 | 776 | 777 | 778 | 779 | 780 | 781 | 782 | 783 | 784 | 785 | 786 | 787 | 788 | 789 | 790 | 791 | 792 | 793 | 794 | 795 | 796 | 797 | 798 | 799 | 800 | 801 | 802 | 803 | 804 | 805 | 806 | 807 | 808 | 809 | 810 | 811 | 812 | 813 | 814 | 815 | 816 | 817 | 818 | 819 | 820 | 821 | 822 | 823 |
Extended StyleHexDescription
LVS_EX_BORDERSELECTLV0x8000When 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).
LVS_EX_CHECKBOXESLV0x4 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 |
LVS_EX_DOUBLEBUFFERLV0x10000 745 |

Paints via double-buffering, which reduces flicker. This extended style also enables alpha-blended marquee selection on systems where it is supported.

746 |
LVS_EX_FLATSBLV0x100Enables flat scroll bars in the list view.
LVS_EX_FULLROWSELECTLV0x20When a row is selected, all its fields are highlighted. This style is available only in conjunction with the LVS_REPORT style.
LVS_EX_GRIDLINESLV0x1+/-Grid. Displays gridlines around rows and columns. This style is available only in conjunction with the LVS_REPORT style.
LVS_EX_HEADERDRAGDROPLV0x10Enables 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.
LVS_EX_INFOTIPLV0x400When a list-view control uses this style, the LVN_GETINFOTIP notification message is sent to the parent window before displaying an item's ToolTip.
LVS_EX_LABELTIPLV0x4000If 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.
LVS_EX_MULTIWORKAREASLV0x2000If 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.
LVS_EX_ONECLICKACTIVATELV0x40The 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.
LVS_EX_REGIONALLV0x200Sets 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.
LVS_EX_SIMPLESELECTLV0x100000In 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.
LVS_EX_SUBITEMIMAGESLV0x2Allows images to be displayed for fields beyond the first. This style is available only in conjunction with the LVS_REPORT style.
LVS_EX_TRACKSELECTLV0x8Enables 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.
LVS_EX_TWOCLICKACTIVATELV0x80The 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.
LVS_EX_UNDERLINECOLDLV0x1000Causes those non-hot items that may be activated to be displayed with underlined text. This style requires that LVS_EX_TWOCLICKACTIVATE be set also.
LVS_EX_UNDERLINEHOTLV0x800Causes 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.
824 | 825 |

TreeView Control Styles

826 |

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 | 828 | 829 | 830 | 831 | 832 | 833 | 834 | 835 | 836 | 837 | 838 | 839 | 840 | 841 | 842 | 843 | 844 | 845 | 846 | 847 | 848 | 849 | 850 | 851 | 852 | 853 | 854 | 855 | 856 | 857 | 858 | 859 | 860 | 861 | 862 | 863 | 864 | 865 | 866 | 867 | 868 | 869 | 870 | 871 | 872 | 873 | 874 | 875 | 876 | 877 | 878 | 879 | 880 | 881 | 882 | 883 | 884 | 885 | 886 | 887 | 888 | 889 | 890 | 891 | 892 | 893 | 894 | 895 | 896 | 897 | 898 | 899 | 900 | 901 | 902 | 903 | 904 | 905 | 906 | 907 | 908 | 909 | 910 | 911 | 912 | 913 |
StyleHexDescription
TVS_CHECKBOXES0x100+/-Checked. Displays a checkbox next to each item.
TVS_DISABLEDRAGDROP0x10Prevents the tree-view control from sending TVN_BEGINDRAG notification messages.
TVS_EDITLABELS0x8+/-ReadOnly. Allows the user to edit the names of tree-view items.
TVS_FULLROWSELECT0x1000Enables 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.
TVS_HASBUTTONS0x1+/-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.
TVS_HASLINES0x2+/-Lines. Uses lines to show the hierarchy of items.
TVS_INFOTIP0x800Obtains ToolTip information by sending the TVN_GETINFOTIP notification.
TVS_LINESATROOT0x4+/-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.
TVS_NOHSCROLL0x8000+/-HScroll. Disables horizontal scrolling in the control. The control will not display any horizontal scroll bars.
TVS_NONEVENHEIGHT0x4000Sets 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.
TVS_NOSCROLL0x2000Disables both horizontal and vertical scrolling in the control. The control will not display any scroll bars.
TVS_NOTOOLTIPS0x80Disables tooltips.
TVS_RTLREADING0x40Causes text to be displayed from right-to-left (RTL). Usually, windows display text left-to-right (LTR).
TVS_SHOWSELALWAYS0x20Causes a selected item to remain selected when the tree-view control loses focus.
TVS_SINGLEEXPAND0x400Causes 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.
TVS_TRACKSELECT0x200Enables hot tracking of the mouse in a tree-view control.
914 | 915 |

DateTime Control Styles

916 |

These styles affect the DateTime control. By default, it uses DTS_SHORTDATECENTURYFORMAT and WS_TABSTOP. It has no forced styles.

917 | 918 | 919 | 920 | 921 | 922 | 923 | 924 | 925 | 926 | 927 | 928 | 929 | 930 | 931 | 932 | 933 | 934 | 935 | 936 | 937 | 938 | 939 | 940 | 941 | 942 | 943 | 944 | 945 | 946 | 947 | 948 | 949 | 950 | 951 | 952 | 953 | 954 | 955 | 956 | 957 | 958 | 959 | 960 | 961 | 962 | 963 |
StyleHexDescription
DTS_UPDOWN0x1Provides 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.
DTS_SHOWNONE0x2Displays 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).
DTS_SHORTDATEFORMAT0x0Displays 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.
DTS_LONGDATEFORMAT0x4Format option "LongDate". Displays the date in long format. In some locales, it looks like Wednesday, June 01, 2005.
DTS_SHORTDATECENTURYFORMAT0xCFormat 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.
DTS_TIMEFORMAT0x9Format option "Time". Displays only the time, which in some locales looks like 5:31:42 PM.
DTS_APPCANPARSE0x10Not 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.
DTS_RIGHTALIGN0x20+/-Right. The calendar will drop down on the right side of the control instead of the left.
964 | 965 |

MonthCal Control Styles

966 |

These styles affect the MonthCal control. By default, it uses WS_TABSTOP. It has no forced styles.

967 | 968 | 969 | 970 | 971 | 972 | 973 | 974 | 975 | 976 | 977 | 978 | 979 | 980 | 981 | 985 | 986 | 987 | 988 | 989 | 990 | 991 | 992 | 993 | 994 | 995 | 996 | 997 | 998 | 999 | 1000 | 1001 |
StyleHexDescription
MCS_DAYSTATE0x1Makes the control send MCN_GETDAYSTATE notifications to request information about which days should be displayed in bold. [Not yet supported]
MCS_MULTISELECT0x2 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 |
MCS_WEEKNUMBERS0x4Displays 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.
MCS_NOTODAYCIRCLE0x8Prevents the circling of today's date within the control.
MCS_NOTODAY0x10Prevents the display of today's date at the bottom of the control.
1002 | 1003 |

Slider Control Styles

1004 |

These styles affect the Slider control. By default, it uses WS_TABSTOP. It has no forced styles.

1005 | 1006 | 1007 | 1008 | 1009 | 1010 | 1011 | 1012 | 1013 | 1014 | 1015 | 1016 | 1017 | 1018 | 1019 | 1020 | 1021 | 1022 | 1023 | 1024 | 1025 | 1026 | 1027 | 1028 | 1029 | 1030 | 1031 | 1032 | 1033 | 1034 | 1035 | 1036 | 1037 | 1038 | 1039 | 1045 | 1046 | 1047 | 1048 | 1049 | 1050 | 1051 | 1052 | 1053 | 1054 | 1055 | 1056 | 1057 | 1058 | 1059 | 1060 | 1061 | 1062 | 1063 | 1064 | 1065 | 1066 | 1067 | 1068 | 1069 | 1070 | 1071 | 1072 | 1073 | 1074 | 1075 | 1076 |
StyleHexDescription
TBS_VERT0x2+/-Vertical. The control is oriented vertically.
TBS_LEFT0x4+/-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.
TBS_TOP0x4same as TBS_LEFT.
TBS_BOTH0x8+/-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.
TBS_AUTOTICKS0x1The control has a tick mark for each increment in its range of values. Use +/-TickInterval to have more flexibility.
TBS_ENABLESELRANGE0x20 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 GuiObj.Opt("-Theme")).

1041 |

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", WinTitle
1044 |
TBS_FIXEDLENGTH0x40+/-Thick. Allows the thumb's size to be changed.
TBS_NOTHUMB0x80The control does not display the moveable bar.
TBS_NOTICKS0x10+/-NoTicks. The control does not display any tick marks.
TBS_TOOLTIPS0x100+/-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.
TBS_REVERSED0x200Unfortunately, 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.
TBS_DOWNISLEFT0x400Unfortunately, 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.
1077 | 1078 |

Progress Control Styles

1079 |

These styles affect the Progress control. It has neither default styles nor forced styles.

1080 | 1081 | 1082 | 1083 | 1084 | 1085 | 1086 | 1087 | 1088 | 1089 | 1090 | 1091 | 1092 | 1093 | 1094 | 1095 | 1096 | 1097 | 1098 | 1099 | 1103 | 1104 |
StyleHexDescription
PBS_SMOOTH0x1+/-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.
PBS_VERTICAL0x4+/-Vertical. The progress bar displays progress status vertically, from bottom to top.
PBS_MARQUEE0x8 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 |
1105 | 1106 |

Tab Control Styles

1107 |

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 | 1109 | 1110 | 1111 | 1112 | 1113 | 1114 | 1115 | 1116 | 1117 | 1118 | 1119 | 1120 | 1121 | 1122 | 1123 | 1124 | 1125 | 1126 | 1127 | 1128 | 1129 | 1130 | 1131 | 1132 | 1133 | 1134 | 1135 | 1136 | 1137 | 1138 | 1139 | 1140 | 1141 | 1142 | 1143 | 1144 | 1145 | 1146 | 1147 | 1151 | 1152 | 1153 | 1154 | 1155 | 1156 | 1157 | 1158 | 1159 | 1160 | 1164 | 1165 | 1166 | 1167 | 1168 | 1169 | 1170 | 1171 | 1172 | 1173 | 1174 | 1175 | 1176 | 1177 | 1178 | 1179 | 1180 | 1181 | 1182 | 1183 | 1187 | 1188 | 1189 | 1190 | 1191 | 1192 | 1193 | 1194 | 1195 | 1196 | 1197 | 1198 | 1199 | 1200 | 1201 | 1202 | 1203 | 1204 | 1205 | 1206 | 1207 | 1208 | 1209 | 1210 | 1211 | 1212 | 1213 | 1214 | 1215 | 1216 | 1217 | 1218 |
StyleHexDescription
TCS_SCROLLOPPOSITE0x1Unneeded tabs scroll to the opposite side of the control when a tab is selected.
TCS_BOTTOM0x2+/-Bottom. Tabs appear at the bottom of the control instead of the top.
TCS_RIGHT0x2Tabs appear vertically on the right side of controls that use the TCS_VERTICAL style.
TCS_MULTISELECT0x4Multiple tabs can be selected by holding down Ctrl when clicking. This style must be used with the TCS_BUTTONS style.
TCS_FLATBUTTONS0x8Selected 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.
TCS_FORCEICONLEFT0x10Icons are aligned with the left edge of each fixed-width tab. This style can only be used with the TCS_FIXEDWIDTH style.
TCS_FORCELABELLEFT0x20 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 |
TCS_HOTTRACK0x40Items under the pointer are automatically highlighted.
TCS_VERTICAL0x80 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 |
TCS_BUTTONS0x100+/-Buttons. Tabs appear as buttons, and no border is drawn around the display area.
TCS_SINGLELINE0x0+/-Wrap. Only one row of tabs is displayed. The user can scroll to see more tabs, if necessary. This style is the default.
TCS_MULTILINE0x200+/-Wrap. Multiple rows of tabs are displayed, if necessary, so all tabs are visible at once.
TCS_RIGHTJUSTIFY0x0 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 |
TCS_FIXEDWIDTH0x400All tabs are the same width. This style cannot be combined with the TCS_RIGHTJUSTIFY style.
TCS_RAGGEDRIGHT0x800Rows of tabs will not be stretched to fill the entire width of the control. This style is the default.
TCS_FOCUSONBUTTONDOWN0x1000The tab control receives the input focus when clicked.
TCS_OWNERDRAWFIXED0x2000The parent window is responsible for drawing tabs.
TCS_TOOLTIPS0x4000The tab control has a tooltip control associated with it.
TCS_FOCUSNEVER0x8000The tab control does not receive the input focus when clicked.
1219 | 1220 |

StatusBar Control Styles

1221 |

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 | 1223 | 1224 | 1225 | 1226 | 1227 | 1228 | 1229 | 1230 | 1231 | 1237 | 1238 | 1239 | 1240 | 1241 | 1242 | 1243 |
StyleHexDescription
SBARS_TOOLTIPS0x800 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 |
SBARS_SIZEGRIP0x100Includes 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.
1244 | 1245 | 1246 | -------------------------------------------------------------------------------- /docs/misc/Threads.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Threads - Behaviour & Priority | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Threads

14 | 15 |

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 |

Thread Priority

24 |

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 |
    27 |
  • A timed subroutine is given a specific priority via SetTimer.
  • 28 |
  • A hotkey is given a specific priority via the Hotkey function.
  • 29 |
  • A hotstring is given a specific priority when it is defined, or via the #Hotstring directive.
  • 30 |
  • A custom menu item is given a specific priority via the Menu.Add method.
  • 31 |
  • The current thread sets its own priority via the Thread function.
  • 32 |
33 |

The OnExit callback function (if any) will always run when called for, regardless of the current thread's priority.

34 | 35 |

Thread Interruptibility

36 |

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 |
    38 |
  • The thread has been marked as critical. Critical may have been called by the thread itself or by the auto-execute thread.
  • 39 |
  • The thread has not been running long enough to meet the conditions for becoming interruptible, as set by Thread Interrupt.
  • 40 |
  • One of the script's menus is being displayed (such as the tray icon menu or a menu bar).
  • 41 |
  • A delay is being performed by Send (most often due to SetKeyDelay), WinActivate, or a Clipboard operation.
  • 42 |
  • An OnExit thread is executing.
  • 43 |
  • A warning dialog is being displayed due to the A_MaxHotkeysPerInterval limit being reached, or due to a problem activating the keyboard or mouse hook (very rare).
  • 44 |
45 |

Behavior of Uninterruptible Threads

46 |

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 |
    49 |
  • An OnExit callback.
  • 50 |
  • Any OnMessage function that monitors a message which is not buffered.
  • 51 |
  • Any callback indirectly triggered by the thread itself (e.g. via SendMessage or DllCall).
  • 52 |
53 |

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 | WinTitle & Last Found Window | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

WinTitle Parameter & Last Found Window

14 |

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 |

Table of Contents

17 |
    18 |
  • Window Title & Matching Behaviour
  • 19 |
  • A (Active Window)
  • 20 |
  • ahk_ Criteria 21 |
      22 |
    • ahk_class (Window Class)
    • 23 |
    • ahk_id (Unique ID / HWND)
    • 24 |
    • ahk_pid (Process ID)
    • 25 |
    • ahk_exe (Process Name/Path)
    • 26 |
    • ahk_group (Window Group)
    • 27 |
    28 |
  • 29 |
  • Multiple Criteria
  • 30 |
  • Last Found Window
  • 31 |
32 | 33 | 34 |

Window Title & Matching Behaviour

35 |

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 |

A (Active Window)

45 |

Use the letter A for WinTitle and omit the other three window parameters (WinText, ExcludeTitle and ExcludeText), to operate on the active window.

46 |

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+Up
50 | 51 |

ahk_ Criteria

52 |

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.

53 |

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.

54 | 55 |

ahk_class (Window Class)

56 |

Use ahk_class ClassName in WinTitle to identify a window by its window class.

57 |

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 |

ahk_id (Unique ID / HWND)

65 |

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.

67 |

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.

68 |

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.

69 |

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.

70 |

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 |

ahk_pid (Process ID)

86 |

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.

87 |

The following example activates a window by a process ID stored in VarContainingPID:

88 |
WinActivate "ahk_pid " VarContainingPID
89 | 90 |

ahk_exe (Process Name/Path)

91 |

Use ahk_exe ProcessNameOrPath in WinTitle to identify a window belonging to any process with the given name or path.

92 |

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.

93 |

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 |

ahk_group (Window Group)

99 |

Use ahk_group GroupName in WinTitle to identify a window or windows matching the rules contained by a previously defined window group.

100 |

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 |

Multiple Criteria

110 |

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 |

Last Found Window

123 | 124 |

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 | Automating Winamp | AutoHotkey v2 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

Automating Winamp

14 | 15 |

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 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 |
Key to sendEffect
cPause/UnPause
xPlay/Restart/UnPause
vStop
+vStop with Fadeout
^vStop after the current track
bNext Track
zPrevious Track
{left}Rewind 5 seconds
{right}Fast-forward 5 seconds
{up}Turn Volume Up
{down}Turn Volume Down
75 |

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
`n (i.e.
followed 8 | ; by a linefeed). 9 | 10 | ; In addition of the functionality above, Flags can be zero or a 11 | ; combination (sum) of the following values. If omitted, it defaults to 1. 12 | 13 | ; - 1: Converts certain characters to named expressions. e.g. € is 14 | ; converted to € 15 | ; - 2: Converts certain characters to numbered expressions. e.g. € is 16 | ; converted to € 17 | 18 | ; Only non-ASCII characters are affected. If Flags is the number 3, 19 | ; numbered expressions are used only where a named expression is not 20 | ; available. The following characters are always converted: <>"& and `n 21 | ; (line feed). 22 | 23 | EncodeHTML(String, Flags := 1) 24 | { 25 | static TRANS_HTML_NAMED := 1 26 | static TRANS_HTML_NUMBERED := 2 27 | static ansi := ["euro", "#129", "sbquo", "fnof", "bdquo", "hellip", "dagger", "Dagger", "circ", "permil", "Scaron", "lsaquo", "OElig", "#141", "#381", "#143", "#144", "lsquo", "rsquo", "ldquo", "rdquo", "bull", "ndash", "mdash", "tilde", "trade", "scaron", "rsaquo", "oelig", "#157", "#382", "Yuml", "nbsp", "iexcl", "cent", "pound", "curren", "yen", "brvbar", "sect", "uml", "copy", "ordf", "laquo", "not", "shy", "reg", "macr", "deg", "plusmn", "sup2", "sup3", "acute", "micro", "para", "middot", "cedil", "sup1", "ordm", "raquo", "frac14", "frac12", "frac34", "iquest", "Agrave", "Aacute", "Acirc", "Atilde", "Auml", "Aring", "AElig", "Ccedil", "Egrave", "Eacute", "Ecirc", "Euml", "Igrave", "Iacute", "Icirc", "Iuml", "ETH", "Ntilde", "Ograve", "Oacute", "Ocirc", "Otilde", "Ouml", "times", "Oslash", "Ugrave", "Uacute", "Ucirc", "Uuml", "Yacute", "THORN", "szlig", "agrave", "aacute", "acirc", "atilde", "auml", "aring", "aelig", "ccedil", "egrave", "eacute", "ecirc", "euml", "igrave", "iacute", "icirc", "iuml", "eth", "ntilde", "ograve", "oacute", "ocirc", "otilde", "ouml", "divide", "oslash", "ugrave", "uacute", "ucirc", "uuml", "yacute", "thorn", "yuml"] 28 | static unicode := {0x20AC:1, 0x201A:3, 0x0192:4, 0x201E:5, 0x2026:6, 0x2020:7, 0x2021:8, 0x02C6:9, 0x2030:10, 0x0160:11, 0x2039:12, 0x0152:13, 0x2018:18, 0x2019:19, 0x201C:20, 0x201D:21, 0x2022:22, 0x2013:23, 0x2014:24, 0x02DC:25, 0x2122:26, 0x0161:27, 0x203A:28, 0x0153:29, 0x0178:32} 29 | 30 | out := "" 31 | for i, char in StrSplit(String) 32 | { 33 | code := Ord(char) 34 | switch code 35 | { 36 | case 10: out .= "
`n" 37 | case 34: out .= """ 38 | case 38: out .= "&" 39 | case 60: out .= "<" 40 | case 62: out .= ">" 41 | default: 42 | if (code >= 160 && code <= 255) 43 | { 44 | if (Flags & TRANS_HTML_NAMED) 45 | out .= "&" ansi[code-127] ";" 46 | else if (Flags & TRANS_HTML_NUMBERED) 47 | out .= "&#" code ";" 48 | else 49 | out .= char 50 | } 51 | else if (code > 255) 52 | { 53 | if (Flags & TRANS_HTML_NAMED && unicode.HasOwnProp(code)) 54 | out .= "&" ansi[unicode.%code%] ";" 55 | else if (Flags & TRANS_HTML_NUMBERED) 56 | out .= "&#" code ";" 57 | else 58 | out .= char 59 | } 60 | else 61 | { 62 | if (code >= 128 && code <= 159) 63 | out .= "&" ansi[code-127] ";" 64 | else 65 | out .= char 66 | } 67 | } 68 | } 69 | return out 70 | } -------------------------------------------------------------------------------- /docs/scripts/FavoriteFolders.ahk: -------------------------------------------------------------------------------- 1 | ; Easy Access to Favorite Folders (based on the v1 script by Savage) 2 | ; https://www.autohotkey.com 3 | ; When you click the middle mouse button while certain types of 4 | ; windows are active, this script displays a menu of your favorite 5 | ; folders. Upon selecting a favorite, the script will instantly 6 | ; switch to that folder within the active window. The following 7 | ; window types are supported: 1) Standard file-open or file-save 8 | ; dialogs; 2) Explorer windows; 3) Console (command prompt) windows. 9 | ; The menu can also be optionally shown for unsupported window 10 | ; types, in which case the chosen favorite will be opened as a new 11 | ; Explorer window. 12 | 13 | ; CONFIG: CHOOSE YOUR HOTKEY 14 | ; If your mouse has more than 3 buttons, you could try using 15 | ; XButton1 (the 4th) or XButton2 (the 5th) instead of MButton. 16 | ; You could also use a modified mouse button (such as ^MButton) or 17 | ; a keyboard hotkey. In the case of MButton, the tilde (~) prefix 18 | ; is used so that MButton's normal functionality is not lost when 19 | ; you click in other window types, such as a browser. The presence 20 | ; of a tilde tells the script to avoid showing the menu for 21 | ; unsupported window types. In other words, if there is no tilde, 22 | ; the hotkey will always display the menu; and upon selecting a 23 | ; favorite while an unsupported window type is active, a new 24 | ; Explorer window will be opened to display the contents of that 25 | ; folder. 26 | g_Hotkey := "~MButton" 27 | 28 | ; CONFIG: CHOOSE YOUR FAVORITES 29 | ; Update the special commented section below to list your favorite 30 | ; folders. Specify the name of the menu item first, followed by a 31 | ; semicolon, followed by the name of the actual path of the favorite. 32 | ; Use a blank line to create a separator line. 33 | 34 | /* 35 | ITEMS IN FAVORITES MENU <-- Do not change this string. 36 | Desktop ; %USERPROFILE%\Desktop 37 | Favorites ; %USERPROFILE%\Favorites 38 | Documents ; %USERPROFILE%\Documents 39 | 40 | Program Files; %PROGRAMFILES% 41 | */ 42 | 43 | 44 | ; END OF CONFIGURATION SECTION 45 | ; Do not make changes below this point unless you want to change 46 | ; the basic functionality of the script. 47 | 48 | #SingleInstance ; Needed since the hotkey is dynamically created. 49 | 50 | g_AlwaysShowMenu := true 51 | g_Paths := [] 52 | g_Menu := Menu() 53 | g_window_id := 0 54 | g_class := "" 55 | 56 | Hotkey g_Hotkey, DisplayMenu 57 | if SubStr(g_Hotkey, 1, 1) = "~" ; Show menu only for certain window types. 58 | g_AlwaysShowMenu := false 59 | 60 | if A_IsCompiled ; Read the menu items from an external file. 61 | FavoritesFile := A_ScriptDir "\Favorites.ini" 62 | else ; Read the menu items directly from this script file. 63 | FavoritesFile := A_ScriptFullPath 64 | 65 | ;----Read the configuration file. 66 | AtStartingPos := false 67 | FileExt := "" 68 | Loop Read, FavoritesFile 69 | { 70 | if FileExt != "Exe" 71 | { 72 | ; Since the menu items are being read directly from this 73 | ; script, skip over all lines until the starting line is 74 | ; arrived at. 75 | if !AtStartingPos 76 | { 77 | if InStr(A_LoopReadLine, "ITEMS IN FAVORITES MENU") 78 | AtStartingPos := true 79 | continue ; Start a new loop iteration. 80 | } 81 | ; Otherwise, the closing comment symbol marks the end of the list. 82 | if A_LoopReadLine = "*/" 83 | break ; terminate the loop 84 | } 85 | if !A_LoopReadLine ; Blank indicates a separator line. 86 | { 87 | ; Menu separator lines must also be pushed to the array 88 | ; to be compatible with ItemPos: 89 | g_Paths.Push("") 90 | g_Menu.Add() 91 | } 92 | else 93 | { 94 | line := StrSplit(A_LoopReadLine, ";", "`s`t") 95 | ; Resolve any references to variables within either field, and 96 | ; create a new array element containing the path of this favorite: 97 | g_Paths.Push(line[2]) 98 | g_Menu.Add(line[1], OpenFavorite) 99 | } 100 | } 101 | 102 | 103 | ;----Open the selected favorite 104 | OpenFavorite(ItemName, ItemPos, *) 105 | { 106 | control_id := 0 107 | ; Fetch the array element that corresponds to the selected menu item: 108 | path := g_Paths[ItemPos] 109 | if path = "" 110 | return 111 | if g_class = "#32770" ; It's a dialog. 112 | { 113 | ; Activate the window so that if the user is middle-clicking 114 | ; outside the dialog, subsequent clicks will also work: 115 | WinActivate g_window_id 116 | ; Retrieve the unique ID number of the Edit1 control: 117 | control_id := ControlGetHwnd("Edit1", g_window_id) 118 | ; Retrieve any filename that might already be in the field so 119 | ; that it can be restored after the switch to the new folder: 120 | text := ControlGetText(control_id) 121 | ControlSetText path, control_id 122 | ControlFocus control_id 123 | ControlSend "{Enter}", control_id 124 | Sleep 100 ; It needs extra time on some dialogs or in some cases. 125 | ControlSetText text, control_id 126 | return 127 | } 128 | else if g_class = "CabinetWClass" ; In Explorer, switch folders. 129 | { 130 | if VerCompare(A_OSVersion, "10.0.22000") >= 0 ; Windows 11 and later 131 | { 132 | try GetActiveExplorerTab().Navigate(ExpandEnvVars(path)) 133 | } 134 | else 135 | { 136 | ControlClick "ToolbarWindow323", g_window_id,,,, "NA x1 y1" 137 | ; Wait until the Edit1 control exists: 138 | while not control_id 139 | try control_id := ControlGetHwnd("Edit1", g_window_id) 140 | ControlFocus control_id 141 | ControlSetText path, control_id 142 | ; Tekl reported the following: "If I want to change to Folder L:\folder 143 | ; then the addressbar shows http://www.L:\folder.com. To solve this, 144 | ; I added a {right} before {Enter}": 145 | ControlSend "{Right}{Enter}", control_id 146 | } 147 | return 148 | } 149 | else if g_class ~= "ConsoleWindowClass|CASCADIA_HOSTING_WINDOW_CLASS" ; In a console window, CD to that directory 150 | { 151 | WinActivate g_window_id ; Because sometimes the mclick deactivates it. 152 | SetKeyDelay 0 ; This will be in effect only for the duration of this thread. 153 | if InStr(path, ":") ; It contains a drive letter 154 | { 155 | path_drive := SubStr(path, 1, 1) 156 | Send path_drive ":{enter}" 157 | } 158 | Send "cd " path "{Enter}" 159 | return 160 | } 161 | ; Since the above didn't return, one of the following is true: 162 | ; 1) It's an unsupported window type but g_AlwaysShowMenu is true. 163 | Run "explorer " path ; Might work on more systems without double quotes. 164 | } 165 | 166 | 167 | ;----Display the menu 168 | DisplayMenu(*) 169 | { 170 | ; These first few variables are set here and used by OpenFavorite: 171 | try global g_window_id := WinGetID("A") 172 | try global g_class := WinGetClass(g_window_id) 173 | if g_AlwaysShowMenu = false ; The menu should be shown only selectively. 174 | { 175 | if !(g_class ~= "#32770|ExploreWClass|CabinetWClass|ConsoleWindowClass|CASCADIA_HOSTING_WINDOW_CLASS") 176 | return ; Since it's some other window type, don't display menu. 177 | } 178 | ; Otherwise, the menu should be presented for this type of window: 179 | g_Menu.Show() 180 | } 181 | 182 | ; Get the WebBrowser object of the active Explorer tab for the given window, 183 | ; or the window itself if it doesn't have tabs. Supports IE and File Explorer. 184 | ; https://www.autohotkey.com/boards/viewtopic.php?t=109907 185 | GetActiveExplorerTab(hwnd := WinExist("A")) { 186 | activeTab := 0 187 | try activeTab := ControlGetHwnd("ShellTabWindowClass1", hwnd) ; File Explorer (Windows 11) 188 | catch 189 | try activeTab := ControlGetHwnd("TabWindowClass1", hwnd) ; IE 190 | for w in ComObject("Shell.Application").Windows { 191 | if w.hwnd != hwnd 192 | continue 193 | if activeTab { ; The window has tabs, so make sure this is the right one. 194 | static IID_IShellBrowser := "{000214E2-0000-0000-C000-000000000046}" 195 | shellBrowser := ComObjQuery(w, IID_IShellBrowser, IID_IShellBrowser) 196 | ComCall(3, shellBrowser, "uint*", &thisTab:=0) 197 | if thisTab != activeTab 198 | continue 199 | } 200 | return w 201 | } 202 | } 203 | 204 | ExpandEnvVars(str) 205 | { 206 | if sz:=DllCall("ExpandEnvironmentStrings", "Str", str, "Ptr", 0, "UInt", 0) 207 | { 208 | buf := Buffer(sz * 2) 209 | if DllCall("ExpandEnvironmentStrings", "Str", str, "Ptr", buf, "UInt", sz) 210 | return StrGet(buf) 211 | } 212 | return str 213 | } -------------------------------------------------------------------------------- /docs/scripts/KeyboardOnScreen.ahk: -------------------------------------------------------------------------------- 1 | ; On-Screen Keyboard (based on the v1 script by Jon) 2 | ; https://www.autohotkey.com 3 | ; This script creates a mock keyboard at the bottom of your screen that shows 4 | ; the keys you are pressing in real time. I made it to help me to learn to 5 | ; touch-type (to get used to not looking at the keyboard). The size of the 6 | ; on-screen keyboard can be customized at the top of the script. Also, you 7 | ; can double-click the tray icon to show or hide the keyboard. 8 | 9 | ;---- Configuration Section: Customize the size of the on-screen keyboard and 10 | ; other options here. 11 | 12 | ; Changing this font size will make the entire on-screen keyboard get 13 | ; larger or smaller: 14 | k_FontSize := 10 15 | k_FontName := "Verdana" ; This can be blank to use the system's default font. 16 | k_FontStyle := "Bold" ; Example of an alternative: Italic Underline 17 | 18 | ; Names for the tray menu items: 19 | k_MenuItemHide := "Hide on-screen &keyboard" 20 | k_MenuItemShow := "Show on-screen &keyboard" 21 | 22 | ; To have the keyboard appear on a monitor other than the primary, specify 23 | ; a number such as 2 for the following variable. Leave it unset to use 24 | ; the primary: 25 | k_Monitor := unset 26 | 27 | ;---- End of configuration section. Don't change anything below this point 28 | ; unless you want to alter the basic nature of the script. 29 | 30 | ;---- Create a Gui window for the on-screen keyboard: 31 | MyGui := Gui("-Caption +ToolWindow +AlwaysOnTop +Disabled") 32 | MyGui.SetFont("s" k_FontSize " " k_FontStyle, k_FontName) 33 | MyGui.MarginY := 0, MyGui.MarginX := 0 34 | 35 | ;---- Alter the tray icon menu: 36 | A_TrayMenu.Delete() 37 | A_TrayMenu.Add(k_MenuItemHide, k_ShowHide) 38 | A_TrayMenu.Add("&Exit", (*) => ExitApp()) 39 | A_TrayMenu.Default := k_MenuItemHide 40 | 41 | ;---- Add a button for each key: 42 | 43 | ; The keyboard layout: 44 | k_Layout := [ 45 | ["``", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", "Backspace:3"], 46 | ["Tab:3", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "\"], 47 | ["CapsLock:3", "A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "'", "Enter:2"], 48 | ["LShift:3", "Z", "X", "C", "V", "B", "N", "M", ",", ".", "/", "Shift:3"], 49 | ["LCtrl:2", "LWin:2", "LAlt:2", "Space:2", "RAlt:2", "RWin:2", "AppsKey:2", "RCtrl:2"] 50 | ] 51 | 52 | ; Traverse the keys of the keyboard layout: 53 | for n, k_Row in k_Layout 54 | for i, k_Key in k_Row 55 | { 56 | k_KeyWidthMultiplier := 1 57 | ; Get custom key width multiplier: 58 | if RegExMatch(k_Key, "(.+):(\d)", &m) 59 | { 60 | k_Key := m[1] 61 | k_KeyWidthMultiplier := m[2] 62 | } 63 | ; Get localized key name: 64 | k_KeyNameText := GetKeyNameText(k_Key, 0, 1) 65 | ; Windows key names start with left or right so replace it: 66 | if (k_Key = "LWin" || k_Key = "RWin") 67 | k_KeyNameText := "Win" 68 | ; Truncate the key name: 69 | if (StrLen(k_Key) > 1) 70 | k_KeyNameText := Trim(SubStr(k_KeyNameText, 1, 5)) 71 | else 72 | k_KeyNameText := k_Key 73 | ; Convert to uppercase: 74 | k_KeyNameText := StrUpper(k_KeyNameText) 75 | ; Calculate object dimensions based on chosen font size: 76 | k_KeyHeight := k_FontSize * 3 77 | opt := "h" k_KeyHeight " w" k_KeyHeight * k_KeyWidthMultiplier " -Wrap x+m" 78 | if (i = 1) 79 | opt .= " y+m xm" 80 | ; Add the button: 81 | Btn := MyGui.Add("Button", opt, k_KeyNameText) 82 | ; When a key is pressed by the user, click the corresponding button on-screen: 83 | Hotkey("~*" k_Key, k_KeyPress.bind(Btn)) 84 | } 85 | 86 | ;---- Position the keyboard at the bottom of the screen (taking into account 87 | ; the position of the taskbar): 88 | MyGui.Show("Hide") ; Required to get the window's calculated width and height. 89 | ; Calculate window's X-position: 90 | MonitorGetWorkArea(k_Monitor?, &WL,, &WR, &WB) 91 | MyGui.GetPos(,, &k_width, &k_height) 92 | k_xPos := (WR - WL - k_width) / 2 ; Calculate position to center it horizontally. 93 | ; The following is done in case the window will be on a non-primary monitor 94 | ; or if the taskbar is anchored on the left side of the screen: 95 | k_xPos += WL 96 | ; Calculate window's Y-position: 97 | k_yPos := WB - k_height 98 | 99 | ;---- Show the window: 100 | MyGui.Show("x" k_xPos " y" k_yPos " NA") 101 | 102 | ;---- Function definitions: 103 | k_KeyPress(BtnCtrl, *) 104 | { 105 | BtnCtrl.Opt("Default") ; Highlight the last pressed key. 106 | ControlClick(, BtnCtrl,,,, "D") 107 | KeyWait(SubStr(A_ThisHotkey, 3)) 108 | ControlClick(, BtnCtrl,,,, "U") 109 | } 110 | 111 | k_ShowHide(*) 112 | { 113 | static isVisible := true 114 | if isVisible 115 | { 116 | MyGui.Hide() 117 | A_TrayMenu.Rename(k_MenuItemHide, k_MenuItemShow) 118 | isVisible := false 119 | } 120 | else 121 | { 122 | MyGui.Show() 123 | A_TrayMenu.Rename(k_MenuItemShow, k_MenuItemHide) 124 | isVisible := true 125 | } 126 | } 127 | 128 | GetKeyNameText(Key, Extended := false, DoNotCare := false) 129 | { 130 | Params := (GetKeySC(Key) << 16) | (Extended << 24) | (DoNotCare << 25) 131 | KeyNameText := Buffer(64, 0) 132 | DllCall("User32.dll\GetKeyNameText", "Int", Params, "Ptr", KeyNameText, "Int", 32) 133 | return StrGet(KeyNameText) 134 | } 135 | -------------------------------------------------------------------------------- /docs/scripts/MinimizeToTrayMenu.ahk: -------------------------------------------------------------------------------- 1 | ; Minimize Window to Tray Menu 2 | ; https://www.autohotkey.com 3 | ; This script assigns a hotkey of your choice to hide any window so that 4 | ; it becomes an entry at the bottom of the script's tray menu. Hidden 5 | ; windows can then be unhidden individually or all at once by selecting 6 | ; the corresponding item on the menu. If the script exits for any reason, 7 | ; all the windows that it hid will be unhidden automatically. 8 | 9 | ; CONFIGURATION SECTION: Change the below values as desired. 10 | 11 | ; This is the maximum number of windows to allow to be hidden (having a 12 | ; limit helps performance): 13 | g_MaxWindows := 50 14 | 15 | ; This is the hotkey used to hide the active window: 16 | g_Hotkey := "#h" ; Win+H 17 | 18 | ; This is the hotkey used to unhide the last hidden window: 19 | g_UnHotkey := "#u" ; Win+U 20 | 21 | ; If you prefer to have the tray menu empty of all the standard items, 22 | ; such as Help and Pause, use False. Otherwise, use True: 23 | g_StandardMenu := false 24 | 25 | ; These next few performance settings help to keep the action within the 26 | ; A_HotkeyModifierTimeout period, and thus avoid the need to release and 27 | ; press down the hotkey's modifier if you want to hide more than one 28 | ; window in a row. These settings are not needed if you choose to have 29 | ; the script use the keyboard hook via InstallKeybdHook or other means: 30 | A_HotkeyModifierTimeout := 100 31 | SetWinDelay 10 32 | SetKeyDelay 0 33 | 34 | #SingleInstance ; Allow only one instance of this script to be running. 35 | Persistent 36 | 37 | ; END OF CONFIGURATION SECTION (do not make changes below this point 38 | ; unless you want to change the basic functionality of the script). 39 | 40 | g_WindowIDs := [] 41 | g_WindowTitles := [] 42 | 43 | Hotkey g_Hotkey, Minimize 44 | Hotkey g_UnHotkey, UnMinimize 45 | 46 | ; If the user terminates the script by any means, unhide all the 47 | ; windows first: 48 | OnExit RestoreAllThenExit 49 | 50 | if g_StandardMenu = true 51 | A_TrayMenu.Add() 52 | else 53 | { 54 | A_TrayMenu.Delete() 55 | A_TrayMenu.Add("E&xit and Unhide All", RestoreAllThenExit) 56 | } 57 | A_TrayMenu.Add("&Unhide All Hidden Windows", RestoreAll) 58 | A_TrayMenu.Add() ; Another separator line to make the above more special. 59 | 60 | g_MaxLength := 260 ; Reduce this to restrict the width of the menu. 61 | 62 | Minimize(*) 63 | { 64 | if g_WindowIDs.Length >= g_MaxWindows 65 | { 66 | MsgBox "No more than " g_MaxWindows " may be hidden simultaneously." 67 | return 68 | } 69 | 70 | ; Set the "last found window" to simplify and help performance. 71 | ; Since in certain cases it is possible for there to be no active window, 72 | ; a timeout has been added: 73 | if !WinWait("A",, 2) ; It timed out, so do nothing. 74 | return 75 | 76 | ; Otherwise, the "last found window" has been set and can now be used: 77 | ActiveID := WinGetID() 78 | ActiveTitle := WinGetTitle() 79 | ActiveClass := WinGetClass() 80 | if ActiveClass ~= "Shell_TrayWnd|Progman" 81 | { 82 | MsgBox "The desktop and taskbar cannot be hidden." 83 | return 84 | } 85 | ; Because hiding the window won't deactivate it, activate the window 86 | ; beneath this one (if any). I tried other ways, but they wound up 87 | ; activating the task bar. This way sends the active window (which is 88 | ; about to be hidden) to the back of the stack, which seems best: 89 | Send "!{esc}" 90 | ; Hide it only now that WinGetTitle/WinGetClass above have been run (since 91 | ; by default, those functions cannot detect hidden windows): 92 | WinHide 93 | 94 | ; If the title is blank, use the class instead. This serves two purposes: 95 | ; 1) A more meaningful name is used as the menu name. 96 | ; 2) Allows the menu item to be created (otherwise, blank items wouldn't 97 | ; be handled correctly by the various routines below). 98 | if ActiveTitle = "" 99 | ActiveTitle := "ahk_class " ActiveClass 100 | ; Ensure the title is short enough to fit. ActiveTitle also serves to 101 | ; uniquely identify this particular menu item. 102 | ActiveTitle := SubStr(ActiveTitle, 1, g_MaxLength) 103 | 104 | ; In addition to the tray menu requiring that each menu item name be 105 | ; unique, it must also be unique so that we can reliably look it up in 106 | ; the array when the window is later unhidden. So make it unique if it 107 | ; isn't already: 108 | for WindowTitle in g_WindowTitles 109 | { 110 | if WindowTitle = ActiveTitle 111 | { 112 | ; Match found, so it's not unique. 113 | ActiveIDShort := Format("{:X}" ,ActiveID) 114 | ActiveIDShortLength := StrLen(ActiveIDShort) 115 | ActiveTitleLength := StrLen(ActiveTitle) 116 | ActiveTitleLength += ActiveIDShortLength 117 | ActiveTitleLength += 1 ; +1 the 1 space between title & ID. 118 | if ActiveTitleLength > g_MaxLength 119 | { 120 | ; Since menu item names are limted in length, trim the title 121 | ; down to allow just enough room for the Window's Short ID at 122 | ; the end of its name: 123 | TrimCount := ActiveTitleLength 124 | TrimCount -= g_MaxLength 125 | ActiveTitle := SubStr(ActiveTitle, 1, -TrimCount) 126 | } 127 | ; Build unique title: 128 | ActiveTitle .= " " ActiveIDShort 129 | break 130 | } 131 | } 132 | 133 | ; First, ensure that this ID doesn't already exist in the list, which can 134 | ; happen if a particular window was externally unhidden (or its app unhid 135 | ; it) and now it's about to be re-hidden: 136 | AlreadyExists := false 137 | for WindowID in g_WindowIDs 138 | { 139 | if WindowID = ActiveID 140 | { 141 | AlreadyExists := true 142 | break 143 | } 144 | } 145 | 146 | ; Add the item to the array and to the menu: 147 | if AlreadyExists = false 148 | { 149 | A_TrayMenu.Add(ActiveTitle, RestoreFromTrayMenu) 150 | g_WindowIDs.Push(ActiveID) 151 | g_WindowTitles.Push(ActiveTitle) 152 | } 153 | } 154 | 155 | 156 | RestoreFromTrayMenu(ThisMenuItem, *) 157 | { 158 | A_TrayMenu.Delete(ThisMenuItem) 159 | ; Find window based on its unique title stored as the menu item name: 160 | for WindowTitle in g_WindowTitles 161 | { 162 | if WindowTitle = ThisMenuItem ; Match found. 163 | { 164 | IDToRestore := g_WindowIDs[A_Index] 165 | WinShow IDToRestore 166 | WinActivate IDToRestore ; Sometimes needed. 167 | g_WindowIDs.RemoveAt(A_Index) ; Remove it to free up a slot. 168 | g_WindowTitles.RemoveAt(A_Index) 169 | break 170 | } 171 | } 172 | } 173 | 174 | 175 | ; This will pop the last minimized window off the stack and unhide it. 176 | UnMinimize(*) 177 | { 178 | ; Make sure there's something to unhide. 179 | if g_WindowIDs.Length > 0 180 | { 181 | ; Get the id of the last window minimized and unhide it 182 | IDToRestore := g_WindowIDs.Pop() 183 | WinShow IDToRestore 184 | WinActivate IDToRestore 185 | 186 | ; Get the menu name of the last window minimized and remove it 187 | MenuToRemove := g_WindowTitles.Pop() 188 | A_TrayMenu.Delete(MenuToRemove) 189 | } 190 | } 191 | 192 | 193 | RestoreAllThenExit(*) 194 | { 195 | RestoreAll() 196 | ExitApp ; Do a true exit. 197 | } 198 | 199 | 200 | RestoreAll(*) 201 | { 202 | for WindowID in g_WindowIDs 203 | { 204 | IDToRestore := WindowID 205 | WinShow IDToRestore 206 | WinActivate IDToRestore ; Sometimes needed. 207 | ; Do it this way vs. DeleteAll so that the sep. line and first 208 | ; item are retained: 209 | MenuToRemove := g_WindowTitles[A_Index] 210 | A_TrayMenu.Delete(MenuToRemove) 211 | } 212 | ; Free up all slots: 213 | global g_WindowIDs := [] 214 | global g_WindowTitles := [] 215 | } 216 | -------------------------------------------------------------------------------- /docs/scripts/MsgBoxButtonNames.ahk: -------------------------------------------------------------------------------- 1 | ; Changing MsgBox's Button Names 2 | ; https://www.autohotkey.com 3 | ; This is a working example script that uses a timer to change 4 | ; the names of the buttons in a message box. Although the button 5 | ; names are changed, the MsgBox's return value still requires that the 6 | ; buttons be referred to by their original names. 7 | 8 | #SingleInstance 9 | SetTimer ChangeButtonNames, 50 10 | Result := MsgBox("Choose a button:", "Add or Delete", 4) 11 | if Result = "Yes" 12 | MsgBox "You chose Add." 13 | else 14 | MsgBox "You chose Delete." 15 | 16 | ChangeButtonNames() 17 | { 18 | if !WinExist("Add or Delete") 19 | return ; Keep waiting. 20 | SetTimer , 0 21 | WinActivate 22 | ControlSetText "&Add", "Button1" 23 | ControlSetText "&Delete", "Button2" 24 | } 25 | -------------------------------------------------------------------------------- /docs/scripts/Numpad000.ahk: -------------------------------------------------------------------------------- 1 | ; Numpad 000 Key 2 | ; https://www.autohotkey.com 3 | ; This example script makes the special 000 key that appears on certain 4 | ; keypads into an equals key. You can change the action by replacing the 5 | ; Send "=" line with line(s) of your choice. 6 | 7 | #MaxThreadsPerHotkey 5 ; Allow multiple threads for this hotkey. 8 | $Numpad0:: 9 | { 10 | #MaxThreadsPerHotkey 1 11 | ; Above: Use the $ to force the hook to be used, which prevents an 12 | ; infinite loop since this subroutine itself sends Numpad0, which 13 | ; would otherwise result in a recursive call to itself. 14 | DelayBetweenKeys := 30 ; Adjust this value if it doesn't work. 15 | if A_PriorHotkey = A_ThisHotkey 16 | { 17 | if A_TimeSincePriorHotkey < DelayBetweenKeys 18 | { 19 | if Numpad0Count = "" 20 | Numpad0Count := 2 ; i.e. This one plus the prior one. 21 | else if Numpad0Count = 0 22 | Numpad0Count := 2 23 | else 24 | { 25 | ; Since we're here, Numpad0Count must be 2 as set by 26 | ; prior calls, which means this is the third time the 27 | ; the key has been pressed. Thus, the hotkey sequence 28 | ; should fire: 29 | Numpad0Count := 0 30 | Send "=" ; ******* This is the action for the 000 key 31 | } 32 | ; In all the above cases, we return without further action: 33 | CalledReentrantly := true 34 | return 35 | } 36 | } 37 | ; Otherwise, this Numpad0 event is either the first in the series 38 | ; or it happened too long after the first one (e.g. perhaps the 39 | ; user is holding down the Numpad0 key to auto-repeat it, which 40 | ; we want to allow). Therefore, after a short delay -- during 41 | ; which another Numpad0 hotkey event may re-entrantly call this 42 | ; subroutine -- we'll send the key on through if no reentrant 43 | ; calls occurred: 44 | Numpad0Count := 0 45 | CalledReentrantly := false 46 | ; During this sleep, this subroutine may be reentrantly called 47 | ; (i.e. a simultaneous "thread" which runs in parallel to the 48 | ; call we're in now): 49 | Sleep DelayBetweenKeys 50 | if CalledReentrantly = true ; Another "thread" changed the value. 51 | { 52 | ; Since it was called reentrantly, this key event was the first in 53 | ; the sequence so should be suppressed (hidden from the system): 54 | CalledReentrantly := false 55 | return 56 | } 57 | ; Otherwise it's not part of the sequence so we send it through normally. 58 | ; In other words, the *real* Numpad0 key has been pressed, so we want it 59 | ; to have its normal effect: 60 | Send "{Numpad0}" 61 | } 62 | -------------------------------------------------------------------------------- /docs/scripts/NumpadMouse.ahk: -------------------------------------------------------------------------------- 1 | ; Using Keyboard Numpad as a Mouse (based on the v1 script by deguix) 2 | ; https://www.autohotkey.com 3 | ; This script makes mousing with your keyboard almost as easy 4 | ; as using a real mouse (maybe even easier for some tasks). 5 | ; It supports up to five mouse buttons and the turning of the 6 | ; mouse wheel. It also features customizable movement speed, 7 | ; acceleration, and "axis inversion". 8 | 9 | /* 10 | o------------------------------------------------------------o 11 | |Using Keyboard Numpad as a Mouse | 12 | (------------------------------------------------------------) 13 | | / A Script file for AutoHotkey | 14 | | ----------------------------------------| 15 | | | 16 | | This script is an example of use of AutoHotkey. It uses | 17 | | the remapping of numpad keys of a keyboard to transform it | 18 | | into a mouse. Some features are the acceleration which | 19 | | enables you to increase the mouse movement when holding | 20 | | a key for a long time, and the rotation which makes the | 21 | | numpad mouse to "turn". I.e. NumpadDown as NumpadUp | 22 | | and vice-versa. See the list of keys used below: | 23 | | | 24 | |------------------------------------------------------------| 25 | | Keys | Description | 26 | |------------------------------------------------------------| 27 | | ScrollLock (toggle on)| Activates numpad mouse mode. | 28 | |-----------------------|------------------------------------| 29 | | Numpad0 | Left mouse button click. | 30 | | Numpad5 | Middle mouse button click. | 31 | | NumpadDot | Right mouse button click. | 32 | | NumpadDiv/NumpadMult | X1/X2 mouse button click. | 33 | | NumpadSub/NumpadAdd | Moves up/down the mouse wheel. | 34 | | | | 35 | |-----------------------|------------------------------------| 36 | | NumLock (toggled off) | Activates mouse movement mode. | 37 | |-----------------------|------------------------------------| 38 | | NumpadEnd/Down/PgDn/ | Mouse movement. | 39 | | /Left/Right/Home/Up/ | | 40 | | /PgUp | | 41 | | | | 42 | |-----------------------|------------------------------------| 43 | | NumLock (toggled on) | Activates mouse speed adj. mode. | 44 | |-----------------------|------------------------------------| 45 | | Numpad7/Numpad1 | Inc./dec. acceleration per | 46 | | | button press. | 47 | | Numpad8/Numpad2 | Inc./dec. initial speed per | 48 | | | button press. | 49 | | Numpad9/Numpad3 | Inc./dec. maximum speed per | 50 | | | button press. | 51 | | !Numpad7/!Numpad1 | Inc./dec. wheel acceleration per | 52 | | | button press*. | 53 | | !Numpad8/!Numpad2 | Inc./dec. wheel initial speed per | 54 | | | button press*. | 55 | | !Numpad9/!Numpad3 | Inc./dec. wheel maximum speed per | 56 | | | button press*. | 57 | | Numpad4/Numpad6 | Inc./dec. rotation angle to | 58 | | | right in degrees. (i.e. 180°= | 59 | | | = inversed controls). | 60 | |------------------------------------------------------------| 61 | | * = These options are affected by the mouse wheel speed | 62 | | adjusted on Control Panel. If you don't have a mouse with | 63 | | wheel, the default is 3 +/- lines per option button press. | 64 | o------------------------------------------------------------o 65 | */ 66 | 67 | ;START OF CONFIG SECTION 68 | 69 | #SingleInstance 70 | A_MaxHotkeysPerInterval := 500 71 | 72 | ; Using the keyboard hook to implement the Numpad hotkeys prevents 73 | ; them from interfering with the generation of ANSI characters such 74 | ; as à. This is because AutoHotkey generates such characters 75 | ; by holding down ALT and sending a series of Numpad keystrokes. 76 | ; Hook hotkeys are smart enough to ignore such keystrokes. 77 | #UseHook 78 | 79 | g_MouseSpeed := 1 80 | g_MouseAccelerationSpeed := 1 81 | g_MouseMaxSpeed := 5 82 | 83 | ;Mouse wheel speed is also set on Control Panel. As that 84 | ;will affect the normal mouse behavior, the real speed of 85 | ;these three below are times the normal mouse wheel speed. 86 | g_MouseWheelSpeed := 1 87 | g_MouseWheelAccelerationSpeed := 1 88 | g_MouseWheelMaxSpeed := 5 89 | 90 | g_MouseRotationAngle := 0 91 | 92 | ;END OF CONFIG SECTION 93 | 94 | ;This is needed or key presses would faulty send their natural 95 | ;actions. Like NumpadDiv would send sometimes "/" to the 96 | ;screen. 97 | InstallKeybdHook 98 | 99 | g_Temp := 0 100 | g_Temp2 := 0 101 | 102 | ;Divide by 45° because MouseMove only supports whole numbers, 103 | ;and changing the mouse rotation to a number lesser than 45° 104 | ;could make strange movements. 105 | ; 106 | ;For example: 22.5° when pressing NumpadUp: 107 | ; First it would move upwards until the speed 108 | ; to the side reaches 1. 109 | g_MouseRotationAnglePart := g_MouseRotationAngle / 45 110 | 111 | g_MouseCurrentAccelerationSpeed := 0 112 | g_MouseCurrentSpeed := g_MouseSpeed 113 | g_MouseCurrentSpeedToDirection := 0 114 | g_MouseCurrentSpeedToSide := 0 115 | 116 | g_MouseWheelCurrentAccelerationSpeed := 0 117 | g_MouseWheelCurrentSpeed := g_MouseSpeed 118 | g_MouseWheelAccelerationSpeedReal := 0 119 | g_MouseWheelMaxSpeedReal := 0 120 | g_MouseWheelSpeedReal := 0 121 | 122 | g_Button := 0 123 | 124 | SetKeyDelay -1 125 | SetMouseDelay -1 126 | 127 | Hotkey "*Numpad0", ButtonLeftClick 128 | Hotkey "*NumpadIns", ButtonLeftClickIns 129 | Hotkey "*Numpad5", ButtonMiddleClick 130 | Hotkey "*NumpadClear", ButtonMiddleClickClear 131 | Hotkey "*NumpadDot", ButtonRightClick 132 | Hotkey "*NumpadDel", ButtonRightClickDel 133 | Hotkey "*NumpadDiv", ButtonX1Click 134 | Hotkey "*NumpadMult", ButtonX2Click 135 | 136 | Hotkey "*NumpadSub", ButtonWheelAcceleration 137 | Hotkey "*NumpadAdd", ButtonWheelAcceleration 138 | 139 | Hotkey "*NumpadUp", ButtonAcceleration 140 | Hotkey "*NumpadDown", ButtonAcceleration 141 | Hotkey "*NumpadLeft", ButtonAcceleration 142 | Hotkey "*NumpadRight", ButtonAcceleration 143 | Hotkey "*NumpadHome", ButtonAcceleration 144 | Hotkey "*NumpadEnd", ButtonAcceleration 145 | Hotkey "*NumpadPgUp", ButtonAcceleration 146 | Hotkey "*NumpadPgDn", ButtonAcceleration 147 | 148 | Hotkey "Numpad8", ButtonSpeedUp 149 | Hotkey "Numpad2", ButtonSpeedDown 150 | Hotkey "Numpad7", ButtonAccelerationSpeedUp 151 | Hotkey "Numpad1", ButtonAccelerationSpeedDown 152 | Hotkey "Numpad9", ButtonMaxSpeedUp 153 | Hotkey "Numpad3", ButtonMaxSpeedDown 154 | 155 | Hotkey "Numpad6", ButtonRotationAngleUp 156 | Hotkey "Numpad4", ButtonRotationAngleDown 157 | 158 | Hotkey "!Numpad8", ButtonWheelSpeedUp 159 | Hotkey "!Numpad2", ButtonWheelSpeedDown 160 | Hotkey "!Numpad7", ButtonWheelAccelerationSpeedUp 161 | Hotkey "!Numpad1", ButtonWheelAccelerationSpeedDown 162 | Hotkey "!Numpad9", ButtonWheelMaxSpeedUp 163 | Hotkey "!Numpad3", ButtonWheelMaxSpeedDown 164 | 165 | ToggleKeyActivationSupport ; Initialize based on current ScrollLock state. 166 | 167 | ;Key activation support 168 | 169 | ~ScrollLock:: 170 | ToggleKeyActivationSupport(*) 171 | { 172 | ; Wait for it to be released because otherwise the hook state gets reset 173 | ; while the key is down, which causes the up-event to get suppressed, 174 | ; which in turn prevents toggling of the ScrollLock state/light: 175 | KeyWait "ScrollLock" 176 | if GetKeyState("ScrollLock", "T") 177 | { 178 | Hotkey "*Numpad0", "On" 179 | Hotkey "*NumpadIns", "On" 180 | Hotkey "*Numpad5", "On" 181 | Hotkey "*NumpadDot", "On" 182 | Hotkey "*NumpadDel", "On" 183 | Hotkey "*NumpadDiv", "On" 184 | Hotkey "*NumpadMult", "On" 185 | 186 | Hotkey "*NumpadSub", "On" 187 | Hotkey "*NumpadAdd", "On" 188 | 189 | Hotkey "*NumpadUp", "On" 190 | Hotkey "*NumpadDown", "On" 191 | Hotkey "*NumpadLeft", "On" 192 | Hotkey "*NumpadRight", "On" 193 | Hotkey "*NumpadHome", "On" 194 | Hotkey "*NumpadEnd", "On" 195 | Hotkey "*NumpadPgUp", "On" 196 | Hotkey "*NumpadPgDn", "On" 197 | 198 | Hotkey "Numpad8", "On" 199 | Hotkey "Numpad2", "On" 200 | Hotkey "Numpad7", "On" 201 | Hotkey "Numpad1", "On" 202 | Hotkey "Numpad9", "On" 203 | Hotkey "Numpad3", "On" 204 | 205 | Hotkey "Numpad6", "On" 206 | Hotkey "Numpad4", "On" 207 | 208 | Hotkey "!Numpad8", "On" 209 | Hotkey "!Numpad2", "On" 210 | Hotkey "!Numpad7", "On" 211 | Hotkey "!Numpad1", "On" 212 | Hotkey "!Numpad9", "On" 213 | Hotkey "!Numpad3", "On" 214 | } 215 | else 216 | { 217 | Hotkey "*Numpad0", "Off" 218 | Hotkey "*NumpadIns", "Off" 219 | Hotkey "*Numpad5", "Off" 220 | Hotkey "*NumpadDot", "Off" 221 | Hotkey "*NumpadDel", "Off" 222 | Hotkey "*NumpadDiv", "Off" 223 | Hotkey "*NumpadMult", "Off" 224 | 225 | Hotkey "*NumpadSub", "Off" 226 | Hotkey "*NumpadAdd", "Off" 227 | 228 | Hotkey "*NumpadUp", "Off" 229 | Hotkey "*NumpadDown", "Off" 230 | Hotkey "*NumpadLeft", "Off" 231 | Hotkey "*NumpadRight", "Off" 232 | Hotkey "*NumpadHome", "Off" 233 | Hotkey "*NumpadEnd", "Off" 234 | Hotkey "*NumpadPgUp", "Off" 235 | Hotkey "*NumpadPgDn", "Off" 236 | 237 | Hotkey "Numpad8", "Off" 238 | Hotkey "Numpad2", "Off" 239 | Hotkey "Numpad7", "Off" 240 | Hotkey "Numpad1", "Off" 241 | Hotkey "Numpad9", "Off" 242 | Hotkey "Numpad3", "Off" 243 | 244 | Hotkey "Numpad6", "Off" 245 | Hotkey "Numpad4", "Off" 246 | 247 | Hotkey "!Numpad8", "Off" 248 | Hotkey "!Numpad2", "Off" 249 | Hotkey "!Numpad7", "Off" 250 | Hotkey "!Numpad1", "Off" 251 | Hotkey "!Numpad9", "Off" 252 | Hotkey "!Numpad3", "Off" 253 | } 254 | } 255 | 256 | ;Mouse click support 257 | 258 | ButtonLeftClick(*) 259 | { 260 | if GetKeyState("LButton") 261 | return 262 | Button2 := "Numpad0" 263 | ButtonClick := "Left" 264 | ButtonClickStart Button2, ButtonClick 265 | } 266 | 267 | ButtonLeftClickIns(*) 268 | { 269 | if GetKeyState("LButton") 270 | return 271 | Button2 := "NumpadIns" 272 | ButtonClick := "Left" 273 | ButtonClickStart Button2, ButtonClick 274 | } 275 | 276 | ButtonMiddleClick(*) 277 | { 278 | if GetKeyState("MButton") 279 | return 280 | Button2 := "Numpad5" 281 | ButtonClick := "Middle" 282 | ButtonClickStart Button2, ButtonClick 283 | } 284 | 285 | ButtonMiddleClickClear(*) 286 | { 287 | if GetKeyState("MButton") 288 | return 289 | Button2 := "NumpadClear" 290 | ButtonClick := "Middle" 291 | ButtonClickStart Button2, ButtonClick 292 | } 293 | 294 | ButtonRightClick(*) 295 | { 296 | if GetKeyState("RButton") 297 | return 298 | Button2 := "NumpadDot" 299 | ButtonClick := "Right" 300 | ButtonClickStart Button2, ButtonClick 301 | } 302 | 303 | ButtonRightClickDel(*) 304 | { 305 | if GetKeyState("RButton") 306 | return 307 | Button2 := "NumpadDel" 308 | ButtonClick := "Right" 309 | ButtonClickStart Button2, ButtonClick 310 | } 311 | 312 | ButtonX1Click(*) 313 | { 314 | if GetKeyState("XButton1") 315 | return 316 | Button2 := "NumpadDiv" 317 | ButtonClick := "X1" 318 | ButtonClickStart Button2, ButtonClick 319 | } 320 | 321 | ButtonX2Click(*) 322 | { 323 | if GetKeyState("XButton2") 324 | return 325 | Button2 := "NumpadMult" 326 | ButtonClick := "X2" 327 | ButtonClickStart Button2, ButtonClick 328 | } 329 | 330 | ButtonClickStart(Button2, ButtonClick) 331 | { 332 | MouseClick ButtonClick,,, 1, 0, "D" 333 | SetTimer ButtonClickEnd.Bind(Button2, ButtonClick), 10 334 | } 335 | 336 | ButtonClickEnd(Button2, ButtonClick) 337 | { 338 | if GetKeyState(Button2, "P") 339 | return 340 | 341 | SetTimer , 0 342 | MouseClick ButtonClick,,, 1, 0, "U" 343 | } 344 | 345 | ;Mouse movement support 346 | 347 | ButtonSpeedUp(*) 348 | { 349 | global 350 | g_MouseSpeed++ 351 | ToolTip "Mouse speed: " g_MouseSpeed " pixels" 352 | SetTimer ToolTip, -1000 353 | } 354 | 355 | ButtonSpeedDown(*) 356 | { 357 | global 358 | if g_MouseSpeed > 1 359 | g_MouseSpeed-- 360 | if g_MouseSpeed = 1 361 | ToolTip "Mouse speed: " g_MouseSpeed " pixel" 362 | else 363 | ToolTip "Mouse speed: " g_MouseSpeed " pixels" 364 | SetTimer ToolTip, -1000 365 | } 366 | 367 | ButtonAccelerationSpeedUp(*) 368 | { 369 | global 370 | g_MouseAccelerationSpeed++ 371 | ToolTip "Mouse acceleration speed: " g_MouseAccelerationSpeed " pixels" 372 | SetTimer ToolTip, -1000 373 | } 374 | 375 | ButtonAccelerationSpeedDown(*) 376 | { 377 | global 378 | if g_MouseAccelerationSpeed > 1 379 | g_MouseAccelerationSpeed-- 380 | if g_MouseAccelerationSpeed = 1 381 | ToolTip "Mouse acceleration speed: " g_MouseAccelerationSpeed " pixel" 382 | else 383 | ToolTip "Mouse acceleration speed: " g_MouseAccelerationSpeed " pixels" 384 | SetTimer ToolTip, -1000 385 | } 386 | 387 | ButtonMaxSpeedUp(*) 388 | { 389 | global 390 | g_MouseMaxSpeed++ 391 | ToolTip "Mouse maximum speed: " g_MouseMaxSpeed " pixels" 392 | SetTimer ToolTip, -1000 393 | } 394 | 395 | ButtonMaxSpeedDown(*) 396 | { 397 | global 398 | if g_MouseMaxSpeed > 1 399 | g_MouseMaxSpeed-- 400 | if g_MouseMaxSpeed = 1 401 | ToolTip "Mouse maximum speed: " g_MouseMaxSpeed " pixel" 402 | else 403 | ToolTip "Mouse maximum speed: " g_MouseMaxSpeed " pixels" 404 | SetTimer ToolTip, -1000 405 | } 406 | 407 | ButtonRotationAngleUp(*) 408 | { 409 | global 410 | g_MouseRotationAnglePart++ 411 | if g_MouseRotationAnglePart >= 8 412 | g_MouseRotationAnglePart := 0 413 | g_MouseRotationAngle := g_MouseRotationAnglePart 414 | g_MouseRotationAngle *= 45 415 | ToolTip "Mouse rotation angle: " g_MouseRotationAngle "°" 416 | SetTimer ToolTip, -1000 417 | } 418 | 419 | ButtonRotationAngleDown(*) 420 | { 421 | global 422 | g_MouseRotationAnglePart-- 423 | if g_MouseRotationAnglePart < 0 424 | g_MouseRotationAnglePart := 7 425 | g_MouseRotationAngle := g_MouseRotationAnglePart 426 | g_MouseRotationAngle *= 45 427 | ToolTip "Mouse rotation angle: " g_MouseRotationAngle "°" 428 | SetTimer ToolTip, -1000 429 | } 430 | 431 | ButtonAcceleration(ThisHotkey) 432 | { 433 | global 434 | if g_Button != 0 435 | { 436 | if !InStr(ThisHotkey, g_Button) 437 | { 438 | g_MouseCurrentAccelerationSpeed := 0 439 | g_MouseCurrentSpeed := g_MouseSpeed 440 | } 441 | } 442 | g_Button := StrReplace(ThisHotkey, "*") 443 | ButtonAccelerationStart 444 | } 445 | 446 | ButtonAccelerationStart() 447 | { 448 | global 449 | 450 | if g_MouseAccelerationSpeed >= 1 451 | { 452 | if g_MouseMaxSpeed > g_MouseCurrentSpeed 453 | { 454 | g_Temp := 0.001 455 | g_Temp *= g_MouseAccelerationSpeed 456 | g_MouseCurrentAccelerationSpeed += g_Temp 457 | g_MouseCurrentSpeed += g_MouseCurrentAccelerationSpeed 458 | } 459 | } 460 | 461 | ;g_MouseRotationAngle convertion to speed of button direction 462 | g_MouseCurrentSpeedToDirection := g_MouseRotationAngle 463 | g_MouseCurrentSpeedToDirection /= 90.0 464 | g_Temp := g_MouseCurrentSpeedToDirection 465 | 466 | if g_Temp >= 0 467 | { 468 | if g_Temp < 1 469 | { 470 | g_MouseCurrentSpeedToDirection := 1 471 | g_MouseCurrentSpeedToDirection -= g_Temp 472 | EndMouseCurrentSpeedToDirectionCalculation 473 | return 474 | } 475 | } 476 | if g_Temp >= 1 477 | { 478 | if g_Temp < 2 479 | { 480 | g_MouseCurrentSpeedToDirection := 0 481 | g_Temp -= 1 482 | g_MouseCurrentSpeedToDirection -= g_Temp 483 | EndMouseCurrentSpeedToDirectionCalculation 484 | return 485 | } 486 | } 487 | if g_Temp >= 2 488 | { 489 | if g_Temp < 3 490 | { 491 | g_MouseCurrentSpeedToDirection := -1 492 | g_Temp -= 2 493 | g_MouseCurrentSpeedToDirection += g_Temp 494 | EndMouseCurrentSpeedToDirectionCalculation 495 | return 496 | } 497 | } 498 | if g_Temp >= 3 499 | { 500 | if g_Temp < 4 501 | { 502 | g_MouseCurrentSpeedToDirection := 0 503 | g_Temp -= 3 504 | g_MouseCurrentSpeedToDirection += g_Temp 505 | EndMouseCurrentSpeedToDirectionCalculation 506 | return 507 | } 508 | } 509 | EndMouseCurrentSpeedToDirectionCalculation 510 | } 511 | 512 | EndMouseCurrentSpeedToDirectionCalculation() 513 | { 514 | global 515 | 516 | ;g_MouseRotationAngle convertion to speed of 90 degrees to right 517 | g_MouseCurrentSpeedToSide := g_MouseRotationAngle 518 | g_MouseCurrentSpeedToSide /= 90.0 519 | g_Temp := Mod(g_MouseCurrentSpeedToSide, 4) 520 | 521 | if g_Temp >= 0 522 | { 523 | if g_Temp < 1 524 | { 525 | g_MouseCurrentSpeedToSide := 0 526 | g_MouseCurrentSpeedToSide += g_Temp 527 | EndMouseCurrentSpeedToSideCalculation 528 | return 529 | } 530 | } 531 | if g_Temp >= 1 532 | { 533 | if g_Temp < 2 534 | { 535 | g_MouseCurrentSpeedToSide := 1 536 | g_Temp -= 1 537 | g_MouseCurrentSpeedToSide -= g_Temp 538 | EndMouseCurrentSpeedToSideCalculation 539 | return 540 | } 541 | } 542 | if g_Temp >= 2 543 | { 544 | if g_Temp < 3 545 | { 546 | g_MouseCurrentSpeedToSide := 0 547 | g_Temp -= 2 548 | g_MouseCurrentSpeedToSide -= g_Temp 549 | EndMouseCurrentSpeedToSideCalculation 550 | return 551 | } 552 | } 553 | if g_Temp >= 3 554 | { 555 | if g_Temp < 4 556 | { 557 | g_MouseCurrentSpeedToSide := -1 558 | g_Temp -= 3 559 | g_MouseCurrentSpeedToSide += g_Temp 560 | EndMouseCurrentSpeedToSideCalculation 561 | return 562 | } 563 | } 564 | EndMouseCurrentSpeedToSideCalculation 565 | } 566 | 567 | EndMouseCurrentSpeedToSideCalculation() 568 | { 569 | global 570 | 571 | g_MouseCurrentSpeedToDirection *= g_MouseCurrentSpeed 572 | g_MouseCurrentSpeedToSide *= g_MouseCurrentSpeed 573 | 574 | g_Temp := Mod(g_MouseRotationAnglePart, 2) 575 | 576 | if g_Button = "NumpadUp" 577 | { 578 | if g_Temp = 1 579 | { 580 | g_MouseCurrentSpeedToSide *= 2 581 | g_MouseCurrentSpeedToDirection *= 2 582 | } 583 | 584 | g_MouseCurrentSpeedToDirection *= -1 585 | MouseMove g_MouseCurrentSpeedToSide, g_MouseCurrentSpeedToDirection, 0, "R" 586 | } 587 | else if g_Button = "NumpadDown" 588 | { 589 | if g_Temp = 1 590 | { 591 | g_MouseCurrentSpeedToSide *= 2 592 | g_MouseCurrentSpeedToDirection *= 2 593 | } 594 | 595 | g_MouseCurrentSpeedToSide *= -1 596 | MouseMove g_MouseCurrentSpeedToSide, g_MouseCurrentSpeedToDirection, 0, "R" 597 | } 598 | else if g_Button = "NumpadLeft" 599 | { 600 | if g_Temp = 1 601 | { 602 | g_MouseCurrentSpeedToSide *= 2 603 | g_MouseCurrentSpeedToDirection *= 2 604 | } 605 | 606 | g_MouseCurrentSpeedToSide *= -1 607 | g_MouseCurrentSpeedToDirection *= -1 608 | 609 | MouseMove g_MouseCurrentSpeedToDirection, g_MouseCurrentSpeedToSide, 0, "R" 610 | } 611 | else if g_Button = "NumpadRight" 612 | { 613 | if g_Temp = 1 614 | { 615 | g_MouseCurrentSpeedToSide *= 2 616 | g_MouseCurrentSpeedToDirection *= 2 617 | } 618 | 619 | MouseMove g_MouseCurrentSpeedToDirection, g_MouseCurrentSpeedToSide, 0, "R" 620 | } 621 | else if g_Button = "NumpadHome" 622 | { 623 | g_Temp := g_MouseCurrentSpeedToDirection 624 | g_Temp -= g_MouseCurrentSpeedToSide 625 | g_Temp *= -1 626 | g_Temp2 := g_MouseCurrentSpeedToDirection 627 | g_Temp2 += g_MouseCurrentSpeedToSide 628 | g_Temp2 *= -1 629 | MouseMove g_Temp, g_Temp2, 0, "R" 630 | } 631 | else if g_Button = "NumpadPgUp" 632 | { 633 | g_Temp := g_MouseCurrentSpeedToDirection 634 | g_Temp += g_MouseCurrentSpeedToSide 635 | g_Temp2 := g_MouseCurrentSpeedToDirection 636 | g_Temp2 -= g_MouseCurrentSpeedToSide 637 | g_Temp2 *= -1 638 | MouseMove g_Temp, g_Temp2, 0, "R" 639 | } 640 | else if g_Button = "NumpadEnd" 641 | { 642 | g_Temp := g_MouseCurrentSpeedToDirection 643 | g_Temp += g_MouseCurrentSpeedToSide 644 | g_Temp *= -1 645 | g_Temp2 := g_MouseCurrentSpeedToDirection 646 | g_Temp2 -= g_MouseCurrentSpeedToSide 647 | MouseMove g_Temp, g_Temp2, 0, "R" 648 | } 649 | else if g_Button = "NumpadPgDn" 650 | { 651 | g_Temp := g_MouseCurrentSpeedToDirection 652 | g_Temp -= g_MouseCurrentSpeedToSide 653 | g_Temp2 *= -1 654 | g_Temp2 := g_MouseCurrentSpeedToDirection 655 | g_Temp2 += g_MouseCurrentSpeedToSide 656 | MouseMove g_Temp, g_Temp2, 0, "R" 657 | } 658 | 659 | SetTimer ButtonAccelerationEnd, 10 660 | } 661 | 662 | ButtonAccelerationEnd() 663 | { 664 | global 665 | 666 | if GetKeyState(g_Button, "P") 667 | { 668 | ButtonAccelerationStart 669 | return 670 | } 671 | 672 | SetTimer , 0 673 | g_MouseCurrentAccelerationSpeed := 0 674 | g_MouseCurrentSpeed := g_MouseSpeed 675 | g_Button := 0 676 | } 677 | 678 | ;Mouse wheel movement support 679 | 680 | ButtonWheelSpeedUp(*) 681 | { 682 | global 683 | g_MouseWheelSpeed++ 684 | local MouseWheelSpeedMultiplier := RegRead("HKCU\Control Panel\Desktop", "WheelScrollLines") 685 | if MouseWheelSpeedMultiplier <= 0 686 | MouseWheelSpeedMultiplier := 1 687 | g_MouseWheelSpeedReal := g_MouseWheelSpeed 688 | g_MouseWheelSpeedReal *= MouseWheelSpeedMultiplier 689 | ToolTip "Mouse wheel speed: " g_MouseWheelSpeedReal " lines" 690 | SetTimer ToolTip, -1000 691 | } 692 | 693 | ButtonWheelSpeedDown(*) 694 | { 695 | global 696 | local MouseWheelSpeedMultiplier := RegRead("HKCU\Control Panel\Desktop", "WheelScrollLines") 697 | if MouseWheelSpeedMultiplier <= 0 698 | MouseWheelSpeedMultiplier := 1 699 | if g_MouseWheelSpeedReal > MouseWheelSpeedMultiplier 700 | { 701 | g_MouseWheelSpeed-- 702 | g_MouseWheelSpeedReal := g_MouseWheelSpeed 703 | g_MouseWheelSpeedReal *= MouseWheelSpeedMultiplier 704 | } 705 | if g_MouseWheelSpeedReal = 1 706 | ToolTip "Mouse wheel speed: " g_MouseWheelSpeedReal " line" 707 | else 708 | ToolTip "Mouse wheel speed: " g_MouseWheelSpeedReal " lines" 709 | SetTimer ToolTip, -1000 710 | } 711 | 712 | ButtonWheelAccelerationSpeedUp(*) 713 | { 714 | global 715 | g_MouseWheelAccelerationSpeed++ 716 | local MouseWheelSpeedMultiplier := RegRead("HKCU\Control Panel\Desktop", "WheelScrollLines") 717 | if MouseWheelSpeedMultiplier <= 0 718 | MouseWheelSpeedMultiplier := 1 719 | g_MouseWheelAccelerationSpeedReal := g_MouseWheelAccelerationSpeed 720 | g_MouseWheelAccelerationSpeedReal *= MouseWheelSpeedMultiplier 721 | ToolTip "Mouse wheel acceleration speed: " g_MouseWheelAccelerationSpeedReal " lines" 722 | SetTimer ToolTip, -1000 723 | } 724 | 725 | ButtonWheelAccelerationSpeedDown(*) 726 | { 727 | global 728 | local MouseWheelSpeedMultiplier := RegRead("HKCU\Control Panel\Desktop", "WheelScrollLines") 729 | if MouseWheelSpeedMultiplier <= 0 730 | MouseWheelSpeedMultiplier := 1 731 | if g_MouseWheelAccelerationSpeed > 1 732 | { 733 | g_MouseWheelAccelerationSpeed-- 734 | g_MouseWheelAccelerationSpeedReal := g_MouseWheelAccelerationSpeed 735 | g_MouseWheelAccelerationSpeedReal *= MouseWheelSpeedMultiplier 736 | } 737 | if g_MouseWheelAccelerationSpeedReal = 1 738 | ToolTip "Mouse wheel acceleration speed: " g_MouseWheelAccelerationSpeedReal " line" 739 | else 740 | ToolTip "Mouse wheel acceleration speed: " g_MouseWheelAccelerationSpeedReal " lines" 741 | SetTimer ToolTip, -1000 742 | } 743 | 744 | ButtonWheelMaxSpeedUp(*) 745 | { 746 | global 747 | g_MouseWheelMaxSpeed++ 748 | local MouseWheelSpeedMultiplier := RegRead("HKCU\Control Panel\Desktop", "WheelScrollLines") 749 | if MouseWheelSpeedMultiplier <= 0 750 | MouseWheelSpeedMultiplier := 1 751 | g_MouseWheelMaxSpeedReal := g_MouseWheelMaxSpeed 752 | g_MouseWheelMaxSpeedReal *= MouseWheelSpeedMultiplier 753 | ToolTip "Mouse wheel maximum speed: " g_MouseWheelMaxSpeedReal " lines" 754 | SetTimer ToolTip, -1000 755 | } 756 | 757 | ButtonWheelMaxSpeedDown(*) 758 | { 759 | global 760 | local MouseWheelSpeedMultiplier := RegRead("HKCU\Control Panel\Desktop", "WheelScrollLines") 761 | if MouseWheelSpeedMultiplier <= 0 762 | MouseWheelSpeedMultiplier := 1 763 | if g_MouseWheelMaxSpeed > 1 764 | { 765 | g_MouseWheelMaxSpeed-- 766 | g_MouseWheelMaxSpeedReal := g_MouseWheelMaxSpeed 767 | g_MouseWheelMaxSpeedReal *= MouseWheelSpeedMultiplier 768 | } 769 | if g_MouseWheelMaxSpeedReal = 1 770 | ToolTip "Mouse wheel maximum speed: " g_MouseWheelMaxSpeedReal " line" 771 | else 772 | ToolTip "Mouse wheel maximum speed: " g_MouseWheelMaxSpeedReal " lines" 773 | SetTimer ToolTip, -1000 774 | } 775 | 776 | ButtonWheelAcceleration(ThisHotkey) 777 | { 778 | global 779 | if g_Button != 0 780 | { 781 | if g_Button != ThisHotkey 782 | { 783 | g_MouseWheelCurrentAccelerationSpeed := 0 784 | g_MouseWheelCurrentSpeed := g_MouseWheelSpeed 785 | } 786 | } 787 | g_Button := StrReplace(ThisHotkey, "*") 788 | ButtonWheelAccelerationStart 789 | } 790 | 791 | ButtonWheelAccelerationStart() 792 | { 793 | global 794 | 795 | if g_MouseWheelAccelerationSpeed >= 1 796 | { 797 | if g_MouseWheelMaxSpeed > g_MouseWheelCurrentSpeed 798 | { 799 | g_Temp := 0.001 800 | g_Temp *= g_MouseWheelAccelerationSpeed 801 | g_MouseWheelCurrentAccelerationSpeed += g_Temp 802 | g_MouseWheelCurrentSpeed += g_MouseWheelCurrentAccelerationSpeed 803 | } 804 | } 805 | 806 | if g_Button = "NumpadSub" 807 | MouseClick "WheelUp",,, g_MouseWheelCurrentSpeed, 0, "D" 808 | else if g_Button = "NumpadAdd" 809 | MouseClick "WheelDown",,, g_MouseWheelCurrentSpeed, 0, "D" 810 | 811 | SetTimer ButtonWheelAccelerationEnd, 100 812 | } 813 | 814 | ButtonWheelAccelerationEnd() 815 | { 816 | global 817 | 818 | if GetKeyState(g_Button, "P") 819 | { 820 | ButtonWheelAccelerationStart 821 | return 822 | } 823 | 824 | g_MouseWheelCurrentAccelerationSpeed := 0 825 | g_MouseWheelCurrentSpeed := g_MouseWheelSpeed 826 | g_Button := 0 827 | } 828 | -------------------------------------------------------------------------------- /docs/scripts/Seek_(SearchTheStartMenu).ahk: -------------------------------------------------------------------------------- 1 | /* 2 | Seek (based on the v1 script by Phi) 3 | http://www.autohotkey.com 4 | Navigating the Start Menu can be a hassle, especially if you have installed 5 | many programs over time. 'Seek' lets you specify a case-insensitive key 6 | word/phrase that it will use to filter only the matching programs and 7 | directories from the Start Menu, so that you can easily open your target 8 | program from a handful of matched entries. This eliminates the drudgery of 9 | searching and traversing the Start Menu. 10 | */ 11 | /* 12 | Options: 13 | 14 | -cache Use the cached directory-listing if available (this is the default mode 15 | when no option is specified) 16 | -scan Force a directory scan to retrieve the latest directory listing 17 | -scex Scan & exit (this is useful for scheduling the potentially 18 | time-consuming directory-scanning as a background job) 19 | -help Show this help 20 | 21 | Important notes: 22 | 23 | Check AutoHotkey's Tutorial how to run this script, or to compile it if 24 | necessary. 25 | 26 | The only file 'Seek' creates is placed in your TMP directory: 27 | 28 | a. _Seek.ini (cache file for last query string and directory listing) 29 | 30 | When you run 'Seek' for the first time, it'll scan your Start Menu, 31 | and save the directory listing into a cache file. 32 | 33 | The following directories are included in the scanning: 34 | - A_StartMenu 35 | - A_StartMenuCommon 36 | 37 | By default, subsequent runs will read from the cache file so as to reduce the 38 | loading time. For more info on options, run 'Seek.exe -help'. If you think your 39 | Start Menu doesn't contain too many programs, you can choose not to use the 40 | cache and instruct 'Seek' to always do a directory scan (via option -scan). 41 | That way, you will always get the latest listing. 42 | 43 | When you run 'Seek', a window will appear, waiting for you to enter a 44 | key word/phrase. After you have entered a query string, a list of 45 | matching records will be displayed. Next, you need to highlight an entry and 46 | press ENTER or click on the 'Open' button to run the selected program or open 47 | the selected directory. 48 | */ 49 | 50 | /* 51 | Specify which program to use when opening a directory. If the program cannot 52 | be found or is not specified (i.e. variable is unassigned or assigned 53 | a null value), the default Explorer will be used. 54 | */ 55 | g_dirExplorer := "E:\utl\xplorer2_lite\xplorer2.exe" 56 | 57 | /* 58 | User's customised list of additional directories to be included in the 59 | scanning. The full path must not be enclosed by quotes or double-quotes. 60 | If this file is missing, only the default directories will be scanned. 61 | */ 62 | g_SeekMyDir := A_ScriptDir "\Seek.dir" 63 | 64 | /* 65 | Specify the filename and directory location to save the cached directory/program 66 | listing and the cached key word/phrase of the last search. 67 | There is no need to change this unless you want to. 68 | */ 69 | g_saveFile := A_Temp "\_Seek.ini" 70 | 71 | /* 72 | Track search string (True/False) 73 | If true, the last-used query string will be re-used as the default query 74 | string the next time you run Seek. If false, the last-used query string will 75 | not be tracked and there will not be a default query string value the 76 | next time you run Seek. 77 | */ 78 | g_TrackKeyPhrase := True 79 | 80 | /* 81 | Specify what should be included in scan. 82 | F: Files are included. 83 | D: Directories are included. 84 | */ 85 | g_ScanMode := "FD" 86 | 87 | ; Init: 88 | ; #NoTrayIcon 89 | 90 | ; Define the script title: 91 | g_ScriptTitle := "Seek - Search the Start Menu" 92 | 93 | ; Display the help instructions: 94 | if (A_Args.Length && A_Args[1] ~= "^(--help|-help|/h|-h|/\?|-\?)$") 95 | { 96 | MsgBox(" 97 | ( 98 | Navigating the Start Menu can be a hassle, especially if you have installed 99 | many programs over time. 'Seek' lets you specify a case-insensitive key 100 | word/phrase that it will use to filter only the matching programs and 101 | directories from the Start Menu, so that you can easily open your target 102 | program from a handful of matched entries. This eliminates the drudgery of 103 | searching and traversing the Start Menu. 104 | 105 | Options: 106 | -cache Use the cached directory-listing if available (this is the default mode 107 | when no option is specified) 108 | -scan Force a directory scan to retrieve the latest directory listing 109 | -scex Scan & exit (this is useful for scheduling the potentially 110 | time-consuming directory-scanning as a background job) 111 | -help Show this help 112 | )", g_ScriptTitle) 113 | ExitApp 114 | } 115 | 116 | ; Check that the mandatory environment variables exist and are valid: 117 | if !DirExist(A_Temp) ; Path does not exist. 118 | { 119 | MsgBox 120 | ( 121 | "This mandatory environment variable is either not defined or invalid: 122 | 123 | TMP = " A_Temp " 124 | 125 | Please fix it before running Seek." 126 | ), g_ScriptTitle 127 | ExitApp 128 | } 129 | 130 | ; Scan the Start Menu without Gui: 131 | if (A_Args.Length && A_Args[1] = "-scex") 132 | { 133 | SaveFileList() 134 | return 135 | } 136 | 137 | ; Create the GUI window: 138 | G := Gui(, g_ScriptTitle) 139 | 140 | ; Add the text box for user to enter the query string: 141 | E_Search := G.Add("Edit", "W600") 142 | E_Search.OnEvent("Change", FindMatches) 143 | if g_TrackKeyPhrase 144 | try E_Search.Value := IniRead(g_saveFile, "LastSession", "SearchText") 145 | 146 | ; Add my fav tagline: 147 | G.Add("Text", "X625 Y10", "What do you seek, my friend?") 148 | 149 | ; Add the status bar for providing feedback to user: 150 | T_Info := G.Add("Text", "X10 Y31 R1 W764") 151 | 152 | ; Add the selection listbox for displaying search results: 153 | LB := G.Add("ListBox", "X10 Y53 R28 W764 HScroll Disabled") 154 | LB.OnEvent("DoubleClick", OpenTarget) 155 | 156 | ; Add these buttons, but disable them for now: 157 | B1 := G.Add("Button", "Default X10 Y446 Disabled", "Open") 158 | B1.OnEvent("Click", OpenTarget) 159 | B2 := G.Add("Button", "X59 Y446 Disabled", "Open Directory") 160 | B2.OnEvent("Click", OpenFolder) 161 | B3 := G.Add("Button", "X340 Y446", "Scan Start-Menu") 162 | B3.OnEvent("Click", ScanStartMenu) 163 | 164 | ; Add the Exit button: 165 | G.Add("Button", "X743 Y446", "Exit").OnEvent("Click", (*) => Gui_Close(G)) 166 | 167 | ; Add window events: 168 | G.OnEvent("Close", Gui_Close) 169 | G.OnEvent("Escape", Gui_Close) 170 | 171 | ; Pop-up the query window: 172 | G.Show("Center") 173 | 174 | ; Force re-scanning if -scan is enabled or listing cache file does not exist: 175 | if (A_Args.Length && A_Args[1] = "-scan" || !FileExist(g_saveFile)) 176 | ScanStartMenu() 177 | 178 | ; Retrieve an set the matching list: 179 | FindMatches() 180 | 181 | ; Retrieve the last selection from cache file and select the item: 182 | if g_TrackKeyPhrase 183 | try if (LastSelection := IniRead(g_saveFile, "LastSession", "Selection")) 184 | LB.Choose(LastSelection) 185 | 186 | ; Function definitions --- 187 | 188 | ; Scan the start-menu and store the directory/program listings in a cache file: 189 | ScanStartMenu(*) 190 | { 191 | ; Inform user that scanning has started: 192 | T_Info.Value := "Scanning directory listing..." 193 | 194 | ; Disable listbox while scanning is in progress: 195 | LB.Enabled := false 196 | B1.Enabled := false 197 | B2.Enabled := false 198 | B3.Enabled := false 199 | 200 | ; Retrieve and save the start menu files: 201 | SaveFileList() 202 | 203 | ; Inform user that scanning has completed: 204 | T_Info.Value := "Scan completed." 205 | 206 | ; Enable listbox: 207 | LB.Enabled := true 208 | B1.Enabled := true 209 | B2.Enabled := true 210 | B3.Enabled := true 211 | 212 | ; Filter for search string with the new listing: 213 | FindMatches() 214 | } 215 | 216 | ; Retrieve and save the start menu files: 217 | SaveFileList() 218 | { 219 | ; Define the directory paths to retrieve: 220 | LocationArray := [A_StartMenu, A_StartMenuCommon] 221 | 222 | ; Include additional user-defined paths for scanning: 223 | if FileExist(g_SeekMyDir) 224 | Loop Read, g_SeekMyDir 225 | { 226 | if !DirExist(A_LoopReadLine) 227 | MsgBox 228 | ( 229 | "Processing your customised directory list... 230 | 231 | '" A_LoopReadLine "' does not exist and will be excluded from the scanning. 232 | Please update [ " g_SeekMyDir " ]." 233 | ), g_ScriptTitle, 8192 234 | else 235 | LocationArray.Push(A_LoopReadLine) 236 | } 237 | 238 | ; Scan directory listing by recursing each directory to retrieve the contents. 239 | ; Hidden files are excluded: 240 | IniDelete(g_saveFile, "LocationList") 241 | For i, Location in LocationArray 242 | { 243 | ; Save space by using relative paths: 244 | IniWrite(Location, g_saveFile, "LocationList", "L" i) 245 | A_WorkingDir := Location 246 | FileList := "" 247 | Loop Files, "*", g_ScanMode "R" 248 | if !InStr(FileGetAttrib(A_LoopFilePath), "H") ; Exclude hidden file. 249 | FileList .= "%L" i "%\" A_LoopFilePath "`n" 250 | } 251 | IniDelete(g_saveFile, "FileList") 252 | IniWrite(FileList, g_saveFile, "FileList") 253 | } 254 | 255 | ; Search and display all matching records in the listbox: 256 | FindMatches(*) 257 | { 258 | FileArray := [] 259 | SearchText := E_Search.Value 260 | ; Filter matching records based on user query string: 261 | if SearchText 262 | { 263 | L := Map() 264 | while (Location := IniRead(g_saveFile, "LocationList", "L" A_Index, "")) 265 | L[A_Index] := Location 266 | Loop Parse, IniRead(g_saveFile, "FileList"), "`n" 267 | { 268 | Line := A_LoopField 269 | if RegExMatch(Line, "%L(\d+)%", &m) ; Replace %L1% etc. with location paths. 270 | Line := StrReplace(Line, "%L" m[1] "%", L[Integer(m[1])]) 271 | if (SearchText != E_Search.Value) 272 | { 273 | ; User has changed the search string. 274 | ; There is no point to continue searching using the old string, so abort. 275 | return 276 | } 277 | else 278 | { 279 | ; Append matching records into the list: 280 | SplitPath(Line, &Name) 281 | MatchFound := true 282 | Loop Parse, SearchText, "`s" 283 | { 284 | if A_LoopField = "" 285 | continue 286 | if !InStr(Name, A_LoopField) 287 | { 288 | MatchFound := false 289 | break 290 | } 291 | } 292 | if MatchFound 293 | FileArray.Push(Line) 294 | } 295 | } 296 | } 297 | 298 | ; Refresh list with search results: 299 | LB.Delete(), LB.Add(FileArray) 300 | 301 | if !FileArray.Length 302 | { 303 | ; No matching record is found. Disable listbox: 304 | LB.Enabled := false 305 | B1.Enabled := false 306 | B2.Enabled := false 307 | } 308 | else 309 | { 310 | ; Matching records are found. Enable listbox: 311 | LB.Enabled := true 312 | B1.Enabled := true 313 | B2.Enabled := true 314 | ; Select the first record if no other record has been selected: 315 | if (LB.Text = "") 316 | LB.Choose(1) 317 | } 318 | } 319 | 320 | ; User clicked on 'Open' button or pressed ENTER: 321 | OpenTarget(*) 322 | { 323 | ; Selected record does not exist (file or directory not found): 324 | if !FileExist(LB.Text) 325 | { 326 | MsgBox 327 | ( 328 | LB.Text " does not exist. 329 | 330 | This means that the directory cache is outdated. You may click on 331 | the 'Scan Start-Menu' button below to update the directory cache with your 332 | latest directory listing now." 333 | ), g_ScriptTitle, 8192 334 | return 335 | } 336 | 337 | ; Check whether the selected record is a file or directory: 338 | fileAttrib := FileGetAttrib(LB.Text) 339 | if InStr(fileAttrib, "D") ; is directory 340 | OpenFolder() 341 | else if fileAttrib ; is file 342 | Run(LB.Text) 343 | else 344 | { 345 | MsgBox 346 | ( 347 | LB.Text " is neither a DIRECTORY or a FILE. 348 | 349 | This shouldn't happen. Seek cannot proceed. Quitting..." 350 | ) 351 | } 352 | WinClose 353 | } 354 | 355 | ; User clicked on 'Open Directory' button: 356 | OpenFolder(*) 357 | { 358 | Path := LB.Text 359 | ; If user selected a file-record instead of a directory-record, extract the 360 | ; directory path (I'm using DriveGetStatus instead of FileGetAttrib to allow the 361 | ; scenario whereby LB.Text is invalid but the directory path of LB.Text is valid): 362 | if (DriveGetStatus(Path) != "Ready") ; not a directory 363 | { 364 | SplitPath(Path,, &Dir) 365 | Path := Dir 366 | } 367 | 368 | ; Check whether directory exists: 369 | if !DirExist(Path) 370 | { 371 | MsgBox 372 | ( 373 | Path " does not exist. 374 | 375 | This means that the directory cache is outdated. You may click on 376 | the 'Scan Start-Menu' button below to update the directory cache with your 377 | latest directory listing now." 378 | ), g_ScriptTitle, 8192 379 | return 380 | } 381 | 382 | ; Open the directory: 383 | if FileExist(g_dirExplorer) 384 | Run(Format('"{1}" "{2}"', g_dirExplorer, Path)) ; Open with custom file explorer. 385 | else 386 | Run(Path) ; Open with default windows file explorer. 387 | } 388 | 389 | 390 | Gui_Close(*) 391 | { 392 | ; Save the key word/phrase for next run: 393 | if g_TrackKeyPhrase 394 | { 395 | IniWrite(E_Search.Value, g_saveFile, "LastSession", "SearchText") 396 | IniWrite(LB.Text, g_saveFile, "LastSession", "Selection") 397 | } 398 | ExitApp 399 | } 400 | -------------------------------------------------------------------------------- /docs/scripts/TooltipMouseMenu.ahk: -------------------------------------------------------------------------------- 1 | ; ToolTip Mouse Menu (based on the v1 script by Rajat) 2 | ; https://www.autohotkey.com 3 | ; This script displays a popup menu in response to briefly holding down 4 | ; the middle mouse button. Select a menu item by left-clicking it. 5 | ; Cancel the menu by left-clicking outside of it. A recent improvement 6 | ; is that the contents of the menu can change depending on which type of 7 | ; window is active (Notepad and Word are used as examples here). 8 | 9 | ; You can set any title here for the menu: 10 | g_MenuTitle := "-=-=-=-=-=-=-=-" 11 | 12 | ; This is how long the mouse button must be held to cause the menu to appear: 13 | g_UMDelay := 20 14 | 15 | #SingleInstance 16 | 17 | 18 | ;___________________________________________ 19 | ;_____Menu Definitions______________________ 20 | 21 | ; Create / Edit Menu Items here. 22 | ; You can't use spaces in keys/values/section names. 23 | 24 | ; Don't worry about the order, the menu will be sorted. 25 | 26 | g_MenuItems := "Notepad/Calculator/Section 3/Section 4/Section 5" 27 | 28 | 29 | ;___________________________________________ 30 | ;______Dynamic menuitems here_______________ 31 | 32 | ; Syntax: 33 | ; "MenuItem|Window title" 34 | 35 | g_Dyn := [ 36 | "MS Word|- Microsoft Word", 37 | "Notepad II|- Notepad", 38 | ] 39 | 40 | ;___________________________________________ 41 | 42 | Exit 43 | 44 | 45 | ;___________________________________________ 46 | ;_____Menu Sections_________________________ 47 | 48 | ; Create / Edit Menu Sections here. 49 | 50 | Notepad() 51 | { 52 | Run "Notepad.exe" 53 | } 54 | 55 | Calculator() 56 | { 57 | Run "Calc" 58 | } 59 | 60 | Section3() 61 | { 62 | MsgBox "You selected 3" 63 | } 64 | 65 | Section4() 66 | { 67 | MsgBox "You selected 4" 68 | } 69 | 70 | Section5() 71 | { 72 | MsgBox "You selected 5" 73 | } 74 | 75 | MSWord() 76 | { 77 | MsgBox "this is a dynamic entry (word)" 78 | } 79 | 80 | NotepadII() 81 | { 82 | MsgBox "this is a dynamic entry (notepad)" 83 | } 84 | 85 | 86 | ;___________________________________________ 87 | ;_____Hotkey Section________________________ 88 | 89 | ~MButton:: 90 | { 91 | HowLong := 0 92 | Loop 93 | { 94 | HowLong++ 95 | Sleep 10 96 | if !GetKeyState("MButton", "P") 97 | Break 98 | } 99 | if HowLong < g_UMDelay 100 | return 101 | 102 | 103 | ; Prepares dynamic menu: 104 | DynMenu := "" 105 | For i, item in g_Dyn 106 | { 107 | mp := StrSplit(item, "|") 108 | if WinActive(mp[2]) 109 | DynMenu .= "/" mp[1] 110 | } 111 | 112 | 113 | ; Joins sorted main menu and dynamic menu, and 114 | ; clears earlier entries and creates new entries: 115 | MenuItem := StrSplit(Sort(g_MenuItems, "D/") DynMenu, "/") 116 | 117 | ; Creates the menu: 118 | ToolTipMenu := g_MenuTitle 119 | For i, item in MenuItem 120 | ToolTipMenu .= "`n" item 121 | 122 | MouseGetPos &mX, &mY 123 | Hotkey "~LButton", MenuClick 124 | Hotkey "~LButton", "On" 125 | ToolTip ToolTipMenu, mX, mY 126 | WinActivate g_MenuTitle 127 | WinGetPos ,,, &tH, g_MenuTitle 128 | 129 | MenuClick(*) 130 | { 131 | Hotkey "~LButton", "Off" 132 | if !WinActive(g_MenuTitle) 133 | { 134 | ToolTip 135 | return 136 | } 137 | 138 | MouseGetPos &mX, &mY 139 | ToolTip 140 | mY /= tH / (MenuItem.Length + 1) ; Space taken by each line. 141 | if mY < 1 142 | return 143 | TargetSection := MenuItem[Integer(mY)] 144 | %StrReplace(TargetSection, "`s")%() 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /docs/scripts/UpDownCustomIncrements.ahk: -------------------------------------------------------------------------------- 1 | ; Custom Increments for UpDown Controls (based on the v1 script by numEric) 2 | ; https://www.autohotkey.com 3 | ; This script demonstrates how to change an UpDown's increment to a value 4 | ; other than 1 (such as 5 or 0.1). 5 | 6 | #SingleInstance 7 | 8 | ; *** UpDown properties *** 9 | ; UpDown_fIncrement: Custom increment to be used by control UpDown. 10 | ; UpDown_fPos: Initial position (= 0 if omitted). 11 | ; UpDown_fRangeMin: Minimum position (= 0 if omitted). 12 | ; UpDown_fRangeMax: Maximum position (= (UpDown_fRangeMin + Abs(UpDown_fIncrement) * 100) if omitted). 13 | ; 14 | UpDown4_fIncrement := .1 15 | UpDown4_fPos := 0 16 | UpDown4_fRangeMin := -10 17 | UpDown4_fRangeMax := 10 18 | UpDown6_fIncrement := 5 19 | UpDown6_fPos := 10 20 | 21 | ; The following "-2" option disables the control's UDS_SETBUDDYINT style. 22 | ; This is recommended when creating non-unitary UpDown controls, because 23 | ; it prevents a glitch that may otherwise occur when the control is greatly 24 | ; solicited (e.g. when using the mouse wheel to scroll the value). 25 | G := Gui() 26 | G.OnEvent("Escape", (*) => ExitApp()) 27 | E1 := G.Add("Edit", "+Right") 28 | G.Add("UpDown", "-2") 29 | E2 := G.Add("Edit", "ym +Right") 30 | G.Add("UpDown", "-2") 31 | ; Set initial positions for all UpDown controls 32 | E1.Value := UpDown4_fPos 33 | E2.Value := UpDown6_fPos 34 | G.Show() 35 | 36 | OnMessage(0x004E, WM_NOTIFY) ; 0x004E is WM_NOTIFY 37 | 38 | WM_NOTIFY(wParam, lParam, Msg, hWnd) 39 | { 40 | static is64Bit := (A_PtrSize = 8) ? true : false 41 | static UDM_GETBUDDY := 0x046A 42 | static UDN_DELTAPOS := 0xFFFFFD2E 43 | 44 | NMUPDOWN_NMHDR_hwndFrom := NumGet(lParam, 0, "UInt") 45 | NMUPDOWN_NMHDR_idFrom := NumGet(lParam, is64Bit?8:4, "UInt") 46 | NMUPDOWN_NMHDR_code := NumGet(lParam, is64Bit?16:8, "UInt") 47 | ; NMUPDOWN_iPos := NumGet(lParam, is64Bit?20:12, "Int") 48 | NMUPDOWN_iDelta := NumGet(lParam, is64Bit?28:16, "Int") 49 | 50 | UpDown_fIncrement := UpDown%NMUPDOWN_NMHDR_idFrom%_fIncrement 51 | 52 | if (NMUPDOWN_NMHDR_code = UDN_DELTAPOS && IsSet(UpDown_fIncrement)) 53 | { 54 | try BuddyCtrl_hWnd := SendMessage(UDM_GETBUDDY, 0, 0, NMUPDOWN_NMHDR_hwndFrom) 55 | if IsSet(BuddyCtrl_hWnd) 56 | { 57 | UpDown_ID := NMUPDOWN_NMHDR_idFrom 58 | 59 | UpDown_fRangeMin := (IsSet(UpDown%UpDown_ID%_fRangeMin)) 60 | ? UpDown%UpDown_ID%_fRangeMin 61 | : 0 62 | UpDown_fRangeMax := (IsSet(UpDown%UpDown_ID%_fRangeMax)) 63 | ? UpDown%UpDown_ID%_fRangeMax 64 | : UpDown_fRangeMin + Abs(UpDown_fIncrement) * 100 65 | 66 | BuddyCtrl_Text := ControlGetText(BuddyCtrl_hWnd) || 0 67 | BuddyCtrl_Text += NMUPDOWN_iDelta * UpDown_fIncrement 68 | BuddyCtrl_Text := (BuddyCtrl_Text < UpDown_fRangeMin) 69 | ? UpDown_fRangeMin 70 | : (BuddyCtrl_Text > UpDown_fRangeMax) 71 | ? UpDown_fRangeMax 72 | : BuddyCtrl_Text 73 | BuddyCtrl_Text := IsFloat(BuddyCtrl_Text) 74 | ? Format("{:0.1f}", BuddyCtrl_Text) 75 | : BuddyCtrl_Text 76 | ControlSetText(BuddyCtrl_Text, BuddyCtrl_hWnd) 77 | 78 | ; Done; discard proposed change 79 | return true 80 | } 81 | else 82 | { 83 | ; No buddy control 84 | return false 85 | } 86 | } 87 | else 88 | { 89 | ; Not UDN_DELTAPOS, or unit-incremented UpDown control 90 | return false 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /docs/scripts/VolumeOSD.ahk: -------------------------------------------------------------------------------- 1 | /* 2 | Volume On-Screen-Display (based on the v1 script by Rajat) 3 | https://www.autohotkey.com 4 | This script assigns hotkeys of your choice to raise and lower the master wave volume. 5 | */ 6 | 7 | ; --- User Settings --- 8 | 9 | ; The percentage by which to raise or lower the volume each time: 10 | g_Step := 4 11 | 12 | ; How long to display the volume level bar graphs: 13 | g_DisplayTime := 2000 14 | 15 | ; Master Volume Bar color (see the help file to use more precise shades): 16 | g_CBM := "Red" 17 | 18 | ; Background color: 19 | g_CW := "Silver" 20 | 21 | ; Bar's screen position. Use "center" to center the bar in that dimension: 22 | g_PosX := "center" 23 | g_PosY := "center" 24 | g_Width := 150 ; width of bar 25 | g_Thick := 12 ; thickness of bar 26 | 27 | ; If your keyboard has multimedia buttons for Volume, you can 28 | ; try changing the below hotkeys to use them by specifying 29 | ; Volume_Up and Volume_Down: 30 | g_MasterUp := "#Up" ; Win+UpArrow 31 | g_MasterDown := "#Down" 32 | 33 | ; --- Auto Execute Section --- 34 | 35 | ; DON'T CHANGE ANYTHING HERE (unless you know what you're doing). 36 | 37 | #SingleInstance 38 | 39 | ; Create the Progress window: 40 | G := Gui("+ToolWindow -Caption -Border +Disabled") 41 | G.MarginX := 0, G.MarginY := 0 42 | opt := "w" g_Width " h" g_Thick " background" g_CW 43 | Master := G.Add("Progress", opt " c" g_CBM) 44 | 45 | ; Register hotkeys: 46 | Hotkey g_MasterUp, (*) => ChangeVolume("+") 47 | Hotkey g_MasterDown, (*) => ChangeVolume("-") 48 | 49 | ; --- Function Definitions --- 50 | 51 | ChangeVolume(Prefix) 52 | { 53 | SoundSetVolume(Prefix g_Step) 54 | Master.Value := Round(SoundGetVolume()) 55 | G.Show("x" g_PosX " y" g_PosY) 56 | SetTimer HideWindow, -g_DisplayTime 57 | } 58 | 59 | HideWindow() 60 | { 61 | G.Hide() 62 | } 63 | -------------------------------------------------------------------------------- /docs/scripts/WinLIRC.ahk: -------------------------------------------------------------------------------- 1 | ; WinLIRC Client 2 | ; https://www.autohotkey.com 3 | ; This script receives notifications from WinLIRC whenever you press 4 | ; a button on your remote control. It can be used to automate Winamp, 5 | ; Windows Media Player, etc. It's easy to configure. For example, if 6 | ; WinLIRC recognizes a button named "VolUp" on your remote control, 7 | ; create a label named VolUp and beneath it use the function 8 | ; to increase the soundcard's volume by 5%. 9 | 10 | ; Here are the steps to use this script: 11 | ; 1) Configure WinLIRC to recognize your remote control and its buttons. 12 | ; WinLIRC is at https://sourceforge.net/projects/winlirc/ 13 | ; 2) Edit the WinLIRC path, address, and port in the CONFIG section below. 14 | ; 3) Launch this script. It will start the WinLIRC server if needed. 15 | ; 4) Press some buttons on your remote control. A small window will 16 | ; appear showing the name of each button as you press it. 17 | ; 5) Configure your buttons to send keystrokes and mouse clicks to 18 | ; windows such as Winamp, Media Player, etc. See the examples below. 19 | 20 | ; ------------------------------------------------- 21 | ; CONFIGURATION SECTION: Set your preferences here. 22 | ; ------------------------------------------------- 23 | ; Some remote controls repeat the signal rapidly while you're holding down 24 | ; a button. This makes it difficult to get the remote to send only a single 25 | ; signal. The following setting solves this by ignoring repeated signals 26 | ; until the specified time has passed. 200 is often a good setting. Set it 27 | ; to 0 to disable this feature. 28 | g_DelayBetweenButtonRepeats := 200 29 | 30 | ; Specify the path to WinLIRC, such as C:\WinLIRC\winlirc.exe 31 | WinLIRC_Path := A_ProgramFiles "\WinLIRC\winlirc.exe" 32 | 33 | ; Specify WinLIRC's address and port. The most common are 127.0.0.1 (localhost) and 8765. 34 | WinLIRC_Address := "127.0.0.1" 35 | WinLIRC_Port := "8765" 36 | 37 | ; Do not change the following line. Skip it and continue below. 38 | WinLIRC_Init(WinLIRC_Path, WinLIRC_Address, WinLIRC_Port) 39 | 40 | ; -------------------------------------------- 41 | ; ASSIGN ACTIONS TO THE BUTTONS ON YOUR REMOTE 42 | ; -------------------------------------------- 43 | ; Configure your remote control's buttons below. Use WinLIRC's names 44 | ; for the buttons, which can be seen in your WinLIRC config file 45 | ; (.cf file) -- or you can press any button on your remote and the 46 | ; script will briefly display the button's name in a small window. 47 | ; 48 | ; Below are some examples. Feel free to revise or delete them to suit 49 | ; your preferences. 50 | 51 | class Actions 52 | { 53 | VolUp() 54 | { 55 | SoundSetVolume "+5" ; Increase master volume by 5%. 56 | } 57 | 58 | VolDown() 59 | { 60 | SoundSetVolume "-5" ; Reduce master volume by 5%. 61 | } 62 | 63 | ChUp() 64 | { 65 | if WinGetClass("A") ~= "^(Winamp v1\.x|Winamp PE)$" ; Winamp is active. 66 | Send "{right}" ; Send a right-arrow keystroke. 67 | else ; Some other type of window is active. 68 | Send "{WheelUp}" ; Rotate the mouse wheel up by one notch. 69 | } 70 | 71 | ChDown() 72 | { 73 | if WinGetClass("A") ~= "^(Winamp v1\.x|Winamp PE)$" ; Winamp is active. 74 | Send "{left}" ; Send a left-arrow keystroke. 75 | else ; Some other type of window is active. 76 | Send "{WheelDown}" ; Rotate the mouse wheel down by one notch. 77 | } 78 | 79 | Menu() 80 | { 81 | if WinExist("Untitled - Notepad") 82 | { 83 | WinActivate 84 | } 85 | else 86 | { 87 | Run "Notepad" 88 | WinWait "Untitled - Notepad" 89 | WinActivate 90 | } 91 | Send "Here are some keystrokes sent to Notepad.{Enter}" 92 | } 93 | } 94 | 95 | ; The examples above give a feel for how to accomplish common tasks. 96 | ; To learn the basics of AutoHotkey, check out the Quick-start Tutorial 97 | ; at https://www.autohotkey.com/docs/Tutorial.htm 98 | 99 | ; ---------------------------- 100 | ; END OF CONFIGURATION SECTION 101 | ; ---------------------------- 102 | ; Do not make changes below this point unless you want to change the core 103 | ; functionality of the script. 104 | 105 | WinLIRC_Init(Path, IPAddress, Port) 106 | { 107 | OnExit ExitSub ; For connection cleanup purposes. 108 | 109 | ; Launch WinLIRC if it isn't already running: 110 | if not ProcessExist("winlirc.exe") ; No PID for WinLIRC was found. 111 | { 112 | if !FileExist(Path) 113 | { 114 | MsgBox "The file '" Path "' does not exist. Please edit this script to specify its location." 115 | ExitApp 116 | } 117 | Run Path 118 | Sleep 200 ; Give WinLIRC a little time to initialize (probably never needed, just for peace of mind). 119 | } 120 | 121 | ; Connect to WinLIRC (or any type of server for that matter): 122 | socket := ConnectToAddress(IPAddress, Port) 123 | if socket = -1 ; Connection failed (it already displayed the reason). 124 | ExitApp 125 | 126 | ; When the OS notifies the script that there is incoming data waiting to be received, 127 | ; the following causes a function to be launched to read the data: 128 | NotificationMsg := 0x5555 ; An arbitrary message number, but should be greater than 0x1000. 129 | OnMessage(NotificationMsg, ReceiveData) 130 | Persistent 131 | 132 | ; Set up the connection to notify this script via message whenever new data has arrived. 133 | ; This avoids the need to poll the connection and thus cuts down on resource usage. 134 | FD_READ := 1 ; Received when data is available to be read. 135 | FD_CLOSE := 32 ; Received when connection has been closed. 136 | if DllCall("Ws2_32\WSAAsyncSelect", "UInt", socket, "UInt", A_ScriptHwnd, "UInt", NotificationMsg, "Int", FD_READ|FD_CLOSE) 137 | { 138 | MsgBox "WSAAsyncSelect() indicated Winsock error " DllCall("Ws2_32\WSAGetLastError") 139 | ExitApp 140 | } 141 | } 142 | 143 | 144 | 145 | ConnectToAddress(IPAddress, Port) 146 | ; This can connect to most types of TCP servers, not just WinLIRC. 147 | ; Returns -1 (INVALID_SOCKET) upon failure or the socket ID upon success. 148 | { 149 | wsaData := Buffer(400) 150 | result := DllCall("Ws2_32\WSAStartup", "UShort", 0x0002, "Ptr", wsaData) ; Request Winsock 2.0 (0x0002) 151 | if result ; Non-zero, which means it failed (most Winsock functions return 0 upon success). 152 | { 153 | MsgBox "WSAStartup() indicated Winsock error " DllCall("Ws2_32\WSAGetLastError") 154 | return -1 155 | } 156 | 157 | AF_INET := 2 158 | SOCK_STREAM := 1 159 | IPPROTO_TCP := 6 160 | socket := DllCall("Ws2_32\socket", "Int", AF_INET, "Int", SOCK_STREAM, "Int", IPPROTO_TCP) 161 | if socket = -1 162 | { 163 | MsgBox "socket() indicated Winsock error " DllCall("Ws2_32\WSAGetLastError") 164 | return -1 165 | } 166 | 167 | ; Prepare for connection: 168 | SizeOfSocketAddress := 16 169 | SocketAddress := Buffer(SizeOfSocketAddress, 0) 170 | NumPut( "UShort", 2 ; sin_family 171 | , "UShort", DllCall("Ws2_32\htons", "UShort", Port) ; sin_port 172 | , "UInt", DllCall("Ws2_32\inet_addr", "AStr", IPAddress) ; sin_addr.s_addr 173 | , SocketAddress) 174 | 175 | ; Attempt connection: 176 | if DllCall("Ws2_32\connect", "UInt", socket, "Ptr", SocketAddress, "Int", SizeOfSocketAddress) 177 | { 178 | MsgBox "connect() indicated Winsock error " DllCall("Ws2_32\WSAGetLastError") ". Is WinLIRC running?" 179 | return -1 180 | } 181 | return socket ; Indicate success by returning a valid socket ID rather than -1. 182 | } 183 | 184 | 185 | 186 | ReceiveData(wParam, lParam, *) 187 | ; By means of OnMessage, this function has been set up to be called automatically whenever new data 188 | ; arrives on the connection. It reads the data from WinLIRC and takes appropriate action depending 189 | ; on the contents. 190 | { 191 | Critical ; Prevents another of the same message from being discarded due to thread-already-running. 192 | socket := wParam 193 | ReceivedDataSize := 4096 ; Large in case a lot of data gets buffered due to delay in processing previous data. 194 | 195 | ReceivedData := Buffer(ReceivedDataSize, 0) 196 | ReceivedDataLength := DllCall("Ws2_32\recv", "UInt", socket, "Ptr", ReceivedData, "Int", ReceivedDataSize, "Int", 0) 197 | if ReceivedDataLength = 0 ; The connection was gracefully closed, probably due to exiting WinLIRC. 198 | ExitApp ; The OnExit routine will call WSACleanup() for us. 199 | if ReceivedDataLength = -1 200 | { 201 | WinsockError := DllCall("Ws2_32\WSAGetLastError") 202 | if WinsockError = 10035 ; WSAEWOULDBLOCK, which means "no more data to be read". 203 | return 1 204 | if WinsockError != 10054 ; WSAECONNRESET, which happens when WinLIRC closes via system shutdown/logoff. 205 | ; Since it's an unexpected error, report it. Also exit to avoid infinite loop. 206 | MsgBox "recv() indicated Winsock error " WinsockError 207 | ExitApp ; The OnExit routine will call WSACleanup() for us. 208 | } 209 | ; Otherwise, process the data received. Testing shows that it's possible to get more than one line 210 | ; at a time (even for explicitly-sent IR signals), which the following method handles properly. 211 | ; Data received from WinLIRC looks like the following example (see the WinLIRC docs for details): 212 | ; 0000000000eab154 00 NameOfButton NameOfRemote 213 | Loop Parse, StrGet(ReceivedData, "CP0"), "`n", "`r" 214 | { 215 | if A_LoopField ~= "^(|BEGIN|SIGHUP|END)$" ; Ignore blank lines and WinLIRC's start-up messages. 216 | continue 217 | ButtonName := "" ; Init to blank in case there are less than 3 fields found below. 218 | Loop Parse, A_LoopField, "`s" ; Extract the button name, which is the third field. 219 | if A_Index = 3 220 | ButtonName := A_LoopField 221 | static PrevButtonName := "", PrevButtonTime := 0, RepeatCount := 0 ; These variables remember their values between calls. 222 | if (ButtonName != PrevButtonName || A_TickCount - PrevButtonTime > g_DelayBetweenButtonRepeats) 223 | { 224 | if HasMethod(Actions.Prototype, ButtonName) ; There is a method associated with this button. 225 | Actions.Prototype.%ButtonName%() ; Call the method. 226 | else ; Since there is no associated function, briefly display which button was pressed. 227 | { 228 | if (ButtonName == PrevButtonName) 229 | RepeatCount += 1 230 | else 231 | RepeatCount := 1 232 | ToolTip "Button from WinLIRC, " ButtonName " (" RepeatCount ")" 233 | SetTimer () => ToolTip(), -3000 ; This allows more signals to be processed while displaying the window. 234 | } 235 | PrevButtonName := ButtonName 236 | PrevButtonTime := A_TickCount 237 | } 238 | } 239 | return 1 ; Tell the program that no further processing of this message is needed. 240 | } 241 | 242 | 243 | 244 | ExitSub(*) ; This function is called automatically when the script exits for any reason. 245 | { 246 | ; MSDN: "Any sockets open when WSACleanup is called are reset and automatically 247 | ; deallocated as if closesocket was called." 248 | DllCall("Ws2_32\WSACleanup") 249 | } 250 | -------------------------------------------------------------------------------- /docs/scripts/WindowShading.ahk: -------------------------------------------------------------------------------- 1 | ; Window Shading (based on the v1 script by Rajat) 2 | ; https://www.autohotkey.com 3 | ; This script reduces a window to its title bar and then back to its 4 | ; original size by pressing a single hotkey. Any number of windows 5 | ; can be reduced in this fashion (the script remembers each). If the 6 | ; script exits for any reason, all "rolled up" windows will be 7 | ; automatically restored to their original heights. 8 | 9 | ; Set the height of a rolled up window here. The operating system 10 | ; probably won't allow the title bar to be hidden regardless of 11 | ; how low this number is: 12 | g_MinHeight := 25 13 | 14 | ; This line will unroll any rolled up windows if the script exits 15 | ; for any reason: 16 | OnExit ExitSub 17 | 18 | IDs := Array() 19 | Windows := Map() 20 | 21 | #z:: ; Change this line to pick a different hotkey. 22 | ; Below this point, no changes should be made unless you want to 23 | ; alter the script's basic functionality. 24 | { 25 | ; Uncomment this next line if this subroutine is to be converted 26 | ; into a custom menu item rather than a hotkey. The delay allows 27 | ; the active window that was deactivated by the displayed menu to 28 | ; become active again: 29 | ;Sleep 200 30 | ActiveID := WinGetID("A") 31 | for ID in IDs 32 | { 33 | if ID = ActiveID 34 | { 35 | ; Match found, so this window should be restored (unrolled): 36 | Height := Windows[ActiveID] 37 | WinMove ,,, Height, ActiveID 38 | IDs.RemoveAt(A_Index) 39 | return 40 | } 41 | } 42 | WinGetPos ,,, &Height, "A" 43 | Windows.Set(ActiveID, Height) 44 | WinMove ,,, g_MinHeight, ActiveID 45 | IDs.Push(ActiveID) 46 | } 47 | 48 | ExitSub(*) 49 | { 50 | for ID in IDs 51 | { 52 | Height := Windows[ID] 53 | WinMove ,,, Height, ID 54 | } 55 | ExitApp ; Must do this for the OnExit subroutine to actually Exit the script. 56 | } 57 | -------------------------------------------------------------------------------- /docs/scripts/index.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Script Showcase | AutoHotkey v2 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |

AutoHotkey Script Showcase

16 |

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 |

Table of Contents

19 |
    20 |
  • Context Sensitive Help in Any Editor
  • 21 |
  • Easy Window Dragging
  • 22 |
  • Easy Window Dragging (KDE style)
  • 23 |
  • Easy Access to Favorite Folders
  • 24 |
  • Using a Controller as a Mouse
  • 25 |
  • Controller Test Script
  • 26 |
  • On-Screen Keyboard
  • 27 |
  • Minimize Window to Tray Menu
  • 28 |
  • Changing MsgBox's Button Names
  • 29 |
  • Numpad 000 Key
  • 30 |
  • Using Keyboard Numpad as a Mouse
  • 31 |
  • Seek (Search the Start Menu)
  • 32 |
  • ToolTip Mouse Menu
  • 33 |
  • Volume On-Screen-Display (OSD)
  • 34 |
  • Window Shading
  • 35 |
  • WinLIRC Client
  • 36 |
  • HTML Entities Encoding
  • 37 |
  • Custom Increments for UpDown Controls
  • 38 |
  • AutoHotkey v1 Scripts and Functions Forum
  • 39 |
40 | 41 |

Context Sensitive Help in Any Editor

42 |

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 |

Show code

45 | 46 |

Easy Window Dragging

47 |

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 |

Show code

49 | 50 |

Easy Window Dragging (KDE style)

51 |

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 |

Show code

54 | 55 |

Easy Access to Favorite Folders

56 |

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 |

Show code

59 | 60 |

Using a Controller as a Mouse

61 |

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 |

Show code

64 | 65 |

Controller Test Script

66 |

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 |

Show code

68 | 69 |

On-Screen Keyboard

70 |

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 |

Show code

73 | 74 |

Minimize Window to Tray Menu

75 |

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 |

Show code

77 | 78 |

Changing MsgBox's Button Names

79 |

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 |

Show code

81 | 82 |

Numpad 000 Key

83 |

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.

84 |

Show code

85 | 86 |

Using Keyboard Numpad as a Mouse

87 |

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 |

Show code

90 | 91 |

Seek (Search the Start Menu)

92 |

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 |

Show code

95 | 96 |

ToolTip Mouse Menu

97 |

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 |

Show code

100 | 101 |

Volume On-Screen-Display (OSD)

102 |

Based on the v1 script by Rajat

103 |

This script assigns hotkeys of your choice to raise and lower the master volume.

104 |

Show code

105 | 106 |

Window Shading

107 |

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 |

Show code

110 | 111 |

WinLIRC Client

112 |

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 %.

113 |

Show code

114 | 115 |

HTML Entities Encoding

116 |

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 &pound;). In addition, the four characters "&<> are translated to &quot;&amp;&lt;&gt;. Finally, each linefeed (`n) is translated to <br>`n (i.e. <br> followed by a linefeed).

117 |

Show code

118 | 119 |

Custom Increments for UpDown Controls

120 |

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 |

Show code

123 | 124 |

AutoHotkey v1 Scripts and Functions Forum

125 |

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 |

Hide code

130 |

Loading code...

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 | Help Settings 6 | 7 | 8 | 9 | 10 | 11 | 35 | 36 | 37 | 38 |

Help Settings

39 |

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 | 41 | 42 | 45 | 54 | 55 | 56 | 59 | 66 | 67 | 68 | 71 | 77 | 78 | 79 | 82 | 88 | 89 | 90 | 93 | 99 | 100 |
43 | 44 | 46 | 53 |
57 | 58 | 60 | 65 |
69 | 70 | 72 | 76 |
80 | 81 | 83 | 87 |
91 | 92 | 94 | 98 |
101 |
102 |

103 | Note: If you press the following button, ActiveX is used to create a config file named 'chm_config.js' in the same directory as the CHM file, with the following content:

104 |

105 |   
106 | 107 | 108 | 109 | 112 | 113 |
  110 | 111 |
114 |

Permission denied. Run the CHM file as administrator or create the config file manually.

115 | 116 | 229 | 230 | 231 | -------------------------------------------------------------------------------- /docs/static/ahk16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AutoHotkey/AutoHotkeyDocs/v2/docs/static/ahk16.png -------------------------------------------------------------------------------- /docs/static/ahk16_pause.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AutoHotkey/AutoHotkeyDocs/v2/docs/static/ahk16_pause.png -------------------------------------------------------------------------------- /docs/static/ahk16_pause_suspend.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AutoHotkey/AutoHotkeyDocs/v2/docs/static/ahk16_pause_suspend.png -------------------------------------------------------------------------------- /docs/static/ahk16_suspend.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AutoHotkey/AutoHotkeyDocs/v2/docs/static/ahk16_suspend.png -------------------------------------------------------------------------------- /docs/static/ahk_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AutoHotkey/AutoHotkeyDocs/v2/docs/static/ahk_logo.png -------------------------------------------------------------------------------- /docs/static/ahk_logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | AutoHotkey modern logo 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | image/svg+xml 76 | 77 | AutoHotkey modern logo 78 | Unfont: fonts converted to paths. Recreation of the Modern logo for AutoHotkey, 79 | fonts used are Myriad Pro 12 pt and 36 pt, and Helvetica 16 pt. 80 | 81 | 82 | joedf 83 | 84 | 85 | July 27th 2020 86 | 87 | 88 | Author unknown for original logo 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | -------------------------------------------------------------------------------- /docs/static/ahk_logo_no_text.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AutoHotkey/AutoHotkeyDocs/v2/docs/static/ahk_logo_no_text.png -------------------------------------------------------------------------------- /docs/static/ahkfile16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AutoHotkey/AutoHotkeyDocs/v2/docs/static/ahkfile16.png -------------------------------------------------------------------------------- /docs/static/content.css: -------------------------------------------------------------------------------- 1 | @import url('highlighter/light.css'); 2 | 3 | @font-face { 4 | font-family:'icons'; /* http://fontastic.me/ */ 5 | src:url(fonts/icons.eot?) format("embedded-opentype") 6 | } 7 | 8 | @font-face { 9 | font-family:'icons'; 10 | src:url(data:font/opentype;base64,AAEAAAANAIAAAwBQRkZUTZJYLx8AAA7QAAAAHEdERUYAKQAaAAAOsAAAAB5PUy8yckiB9AAAAVgAAABWY21hcJAhfusAAAHgAAABymdhc3D//wADAAAOqAAAAAhnbHlmxMZ8YQAAA9gAAAh0aGVhZB2SKmMAAADcAAAANmhoZWEEIwIFAAABFAAAACRobXR4B9QCnwAAAbAAAAAwbG9jYRVAEzQAAAOsAAAAKm1heHAAWwCIAAABOAAAACBuYW1lCzmJ1AAADEwAAAFucG9zdPeb9YQAAA28AAAA6gABAAAAAQAAeVRfBF8PPPUACwIAAAAAAN41dLMAAAAA3jV0swAAABUCCQHrAAAACAACAAAAAAAAAAEAAAHrAAAALgIAAAAAAAIJAAEAAAAAAAAAAAAAAAAAAAAEAAEAAAAUAIUABQAAAAAAAgAAAAEAAQAAAEAAAAAAAAAAAQIAAZAABQAIAUwBZgAAAEcBTAFmAAAA9QAZAIQAAAIABQkAAAAAAAAAAAKDAAAgIAAAAAAAAAAAUGZFZABAACElxAHg/+AALgHr/+sAAAABAAAAAAAAAgAAAAAAAAACAAAAAgAAOQBPADEATwBAADYAQAAAAEAAPAA8ADMAbAAgACUAcQCoAAAAAwAAAAMAAAAcAAEAAAAAAMQAAwABAAAAHAAEAKgAAAAmACAABAAGAAAAIQBDAEUATABQAFMAWgCsA5QDngQFIZMlsiW2JbolvCXE//8AAAAAACEAQwBFAEwAUABTAFoArAOUA54EBSGTJbIltiW6JbwlxP//AAD/8P/E/8n/vv+1/7b/qf9f/HL8ZvwL3nXaXdpd2lPaVtpIAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQYAAAEAAAAAAAAAAQIAAAACAAAAAAAAAAAAAAAAAAAAAQAAABEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAA4AAAAAAAAKAAAABQAACQAAAAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFYApADaAPwBGAFeAdwClgK2AtoC/gMiA0YDkgPoBBIEOgAAAAMAOQA1AccBywAVACEAQwAAASIGFRQXBwYUFjMyNxU3FjMyNjU0JgMiJjU0NjMyFhUUBjcjNTQrAiIdAiMiHQEUOwIHMxQzMTMyPQEzMTI9ATQBI0RgF08OGxMUDFIiKERgYUIrPDwrKjw8EiQIAR8IJQgIASQBAQggCCQIActgRC8mTw4mGg4BUhFgRENh/vk7Kyo8PCorO34kCAgBIwggCCQICCQIIAgAAAAEAE8ATwGxAbEADQAbACkANwAAASEiBh0BFDMhMj0BNCYHISIGHQEUMyEyPQE0JgchIh0BFBYzITI2PQE0ByEiHQEUFjMhMjY9ATQBoP7ABwoRAUARCgf+wAcKEQFAEQoH/sARCgcBQAcKEf7AEQoHAUAHCgGxCgcQEhIQBwplCgcQEhIQBwplEhAHCgoHEBJlEhAHCgoHEBIAAAADADEAMwHPAc0AFwAfACcAAAE0KwE1NCsBIh0BIyIdARQ7ATUhFTMyNScjNTQ7ATIVAxQ7ATI9ASMBzwlDCvIKQwkJQwEGQwlm0gnACdEJvgnQAUwJbgoKbgm8Ck9PCpt/CQn+kwoKfgAAAAABAE8APgGxAcYAFgAAAScmDwEGHQEUOwEyPQEzFRQ7ATI9ATQBrKcHCaEFDWANbg1gDQE+gQcHgQMH6Q0Nj48NDekHAAIAQABAAcABwAAHAA0AAAAiBhQWMjY0JzIWFAYjAVCgcHCgcL86UlI6AcBwoHBwoD1TdFMAAAAAAgA2AEABygHAABkAMAAAASMiBw4BIiYnJisBIgYdARQWMyEyNj0BNCYHFjMyPwE2JyYrATU0KwEiHQEjIgcGFwGxWhMFByIsIgcFE1oLDg4LAWILDg7BAQQDA0UDAgIEIQc8ByEEAgIDAQIRFRkZFREOC5ALDg4LkAsODQMDYgMEA1gHB1gDBAMAAAADAEAAFQGrAesACwBGAFcAAAE1IxUzESMVMzUjEQc0JyYnJiMiBwYHDgEVFBcWMzI3NjU0JjU2NzYzMhcWHwEVFAcGBwYHBgcGBwYVFBcWMzI3NjczFh8BJwYHBiMiJyY1NDc2NzY3NjcBq4AqKoArVQcQFxQfFhURFRIWCAcSFAsKBgcMDhAYCwsJAz0fHgwODQkKBwUZFygcIhwUAgQRDiURDxIZFhAPCgkSFBUXGwHAKyv+gCsrAYAyAgUMBQQHBQsMHBEQCwwKCQ0LHAYHBAYKBw8ZMwQVCgwECQcLChIREiYYFxIPHB4MATsTCQwODhwYDhAMDgcJBwAFAAAAPgIJAcIAUgBbAGYAgACEAAAlFgcGByI1JyYnNDc2NzYnBgcGBwYHBicmJyY1NDc2NycGIwYnNCcmJzQuATUiNzM/ATwCJj0BNDM6ATYyMzIdATYzNhcUFxYXFRYjBxUzMhcWBxY3JwYHBhUUNzY3Njc2JyYrAQcnFhcWFxYVFCsBIjUnIwcUKwEiNTYTNjsBMgczJwcB+RAVEzEGCQQEASsRERcHDQsTFBgaHBoREB4bIAFIAwMCAQEBAQECAgICUAEEBQoGBAEGSQoEAgIBAQIEWgYsHyCxDhICEA8WVg4PEQYHAxMeAwPnBhUfDBQCLAMZWhoDLAIEVgEEMQVCSiUl6SgyMCEBCQYEBAEeMC8dERYVFBcKDAQDEhEeKyEZCTMMAgQBBAYEBAcEAQIBDgoUDQoCAwQBBDULAwYECAQFAwYQNBITcgMGbQYOFiIhCwwXGQ8SAwkBWw1HYiQ8BAICVVUCAgkBEQSlh4cAAAACAEAAQAHAAcAACQAQAAAlIRE3NSMRITUjJxcHFzcXNQGA/wBAgAGAQIBAYEBgQIAA/wFA/oCg4EBgQGBAwAAAAQA8AGwBxAGVABYAABMHBhUUHwEWNzY9ATMyPQE0KwE1NCcm/LsFBbsHBgenDQ2nBwcBj4UDBwgDhAUEBAc+DXQNPgcEBQAAAQA8AGsBxAGUABYAACU3NjU0LwEmBwYdASMiHQEUOwEVFBcWAQS7BQW7BwYHpw0NpwcHcYUDBwgDhAUEBAc+DXQNPgcEBQAAAgAzADIB0AHQAA8AEgAAAScmDwEzIwcGFxY/ATE3NgU3FwHHXQkL/QEBIwMGCAiA/gn+kBU4AWpdCQn+ggYIBwUi/gn/TDgAAQBsADwBlQHEABYAAAEnJiMiDwEGFxY7ARUUOwEyPQEzMjc2AY+FAwcIA4QFBAQHPg10DT4HBAUBBLsFBbsHBgenDQ2nBwcAAgAgACAB4AHgAAcALwAAACIGFBYyNjQXBx8BBycPAiMvAQ8BJzcvAjU/AS8BNxc/AjMfAT8BFwcfAhUBIkQvL0QvUQ4aAyQ7IxICMxYkMwckHA43Bz4OGgMkOyMSAjMWJDMHJBwONwcBUS9ELy9EUSMzByQcDjcHPg4aAyQ7IxICMxYkMwckHA43Bz4OGgMkOyMSAjMAAAADACUAJQHbAdsAEwAlADkAABIyFxYXFhQHBgcGIicmJyY0NzY3EzU0JisBIgYdARQXFjsBMjc2Jzc0JyYrASIHBhUXFBcWOwEyNzbCfDAyHh0dHjIwfDAyHh0dHjKTBgM3BAYDAwQ3AgQDAQUDAgU+BQIDBQMCBDUDBAMB2x0eMjB8MDIeHR0eMjB8MDIe/rk2BAYGBDYFAQMCA2ayAwICAgIDsgIDAgIDAAAAAQBxAJ8BjwFFABgAAAEUDwEGIi8BJjU0PwE2MzIfATc2MzIfARYBjwOFAwgDhQMDDwIEAwRwcAQDBAIPAwEuBAOFAwOFAwQDAw8CAnFxAgIPAwAAAQCoAF8BTwF8ABcAACUUDwEGIi8BJjU0PwEnJjU0PwE2Mh8BFgFPA4UDCAMOAwNwcAMDDgMIA4UD7gQDhQMDDgMEBQFxcAMEAwMOAwOFAwAAAAwAlgABAAAAAAABAAUADAABAAAAAAACAAcAIgABAAAAAAADACEAbgABAAAAAAAEAAUAnAABAAAAAAAFAAsAugABAAAAAAAGAAUA0gADAAEECQABAAoAAAADAAEECQACAA4AEgADAAEECQADAEIAKgADAAEECQAEAAoAkAADAAEECQAFABYAogADAAEECQAGAAoAxgBpAGMAbwBuAHMAAGljb25zAABSAGUAZwB1AGwAYQByAABSZWd1bGFyAABGAG8AbgB0AEYAbwByAGcAZQAgADIALgAwACAAOgAgAGkAYwBvAG4AcwAgADoAIAAxADgALQAyAC0AMgAwADIAMgAARm9udEZvcmdlIDIuMCA6IGljb25zIDogMTgtMi0yMDIyAABpAGMAbwBuAHMAAGljb25zAABWAGUAcgBzAGkAbwBuACAAMQAuADAAAFZlcnNpb24gMS4wAABpAGMAbwBuAHMAAGljb25zAAAAAAIAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAFAAAAAEAAgECAQMBBAEFAQYBBwEIAQkBCgELAQwBDQEOAQ8BEAERARIEem9vbQdzaWRlYmFyBXByaW50BGhvbWUIY29udHJhc3QIZG93bmxvYWQGc2VsZWN0CGxhbmd1YWdlDWxpbmstZXh0ZXJuYWwKYXJyb3ctbGVmdAthcnJvdy1yaWdodARlZGl0CGFycm93LXVwCHNldHRpbmdzEmV4Y2xhbWF0aW9uLWNpcmNsZQphbmdsZS1kb3duC2FuZ2xlLXJpZ2h0AAAAAAAB//8AAgABAAAADAAAABYAAAACAAEAAwATAAEABAAAAAIAAAAAAAAAAQAAAADV7UW4AAAAAN41dLMAAAAA3jV0sw==) format("truetype"),url(fonts/icons.woff) format("woff"),url(fonts/icons.svg) format("svg") 11 | } 12 | 13 | .body { 14 | height:100%; 15 | width:100%; 16 | position:fixed; 17 | margin:0em 18 | } 19 | 20 | [data-content]:before { 21 | content:attr(data-content); 22 | display:inline-block 23 | } 24 | 25 | #main { 26 | height:100%; 27 | padding-top:3em; 28 | box-sizing:border-box 29 | } 30 | 31 | #head { 32 | box-shadow:0px 4px 16px 0px rgba(0,0,0,0.2); 33 | z-index:999; 34 | background:#3F627F; 35 | position:absolute; 36 | height:3em; 37 | width:100%; 38 | -webkit-touch-callout:none; 39 | -webkit-user-select:none; 40 | -khtml-user-select:none; 41 | -moz-user-select:none; 42 | -ms-user-select:none; 43 | user-select:none; 44 | font-family:arial,helvetica,Segoe UI Symbol; 45 | color:#eee 46 | } 47 | 48 | #head .skip-nav { 49 | clip: rect(1px, 1px, 1px, 1px); 50 | height: 1px; 51 | overflow: hidden; 52 | white-space: nowrap; 53 | width: 1px; 54 | position: absolute; 55 | top: 0; 56 | left: 0; 57 | background: #000; 58 | color: #FFF; 59 | z-index: 100; 60 | padding: .4em; 61 | } 62 | 63 | #head .skip-nav:focus { 64 | clip: auto; 65 | width: auto; 66 | height: auto; 67 | overflow: auto; 68 | } 69 | 70 | #head div { 71 | display:table-cell 72 | } 73 | 74 | #head .h-area { 75 | display:table 76 | } 77 | 78 | #head ul { 79 | list-style:none; 80 | margin:0; 81 | padding:0; 82 | height:100%; 83 | width:100%; 84 | display:table; 85 | table-layout:fixed 86 | } 87 | 88 | #head .h-tabs { 89 | height:100%; 90 | width:18em; 91 | font-weight:700 92 | } 93 | 94 | #head .h-tabs ul { 95 | position:absolute; 96 | top:0; 97 | width:inherit 98 | } 99 | 100 | #head .h-tools { 101 | font-family:icons; 102 | font-size:2em 103 | } 104 | 105 | #head .h-tools.sidebar > ul { 106 | max-width:1.75em 107 | } 108 | 109 | #head .h-tools.online > ul { 110 | max-width:7em 111 | } 112 | 113 | #head .h-tools.chm > ul { 114 | max-width:8.75em 115 | } 116 | 117 | #head .h-tools.main > ul { 118 | max-width:3.5em 119 | } 120 | 121 | #head li { 122 | display:table-cell; 123 | text-align:center; 124 | line-height:1.5em; 125 | vertical-align:middle; 126 | height:100% 127 | } 128 | 129 | #head li > a { 130 | display:block; 131 | text-decoration:none; 132 | color:inherit 133 | } 134 | 135 | :focus:not(:focus-visible) { 136 | outline: 0; 137 | } 138 | 139 | #head button, #left button { 140 | border-width: 2px; 141 | } 142 | 143 | #head li > button { 144 | align-items: normal; 145 | background-color: transparent; 146 | border: 0; 147 | box-sizing: content-box; 148 | color: inherit; 149 | cursor: pointer; 150 | display: block; 151 | font: inherit; 152 | height: 100%; 153 | padding: 0; 154 | width: 100%; 155 | } 156 | 157 | #head .h-tools li { 158 | max-width:1.75em 159 | } 160 | 161 | #head li:hover { 162 | background:#fff; 163 | color:#d06d3c; 164 | cursor:pointer 165 | } 166 | 167 | @media (hover: none) { 168 | #head li:hover { 169 | background: inherit; 170 | color: inherit; 171 | } 172 | } 173 | 174 | #head .selected { 175 | background:#fff; 176 | color:#3F627F 177 | } 178 | 179 | #head .dropdown { 180 | display:none; 181 | position:absolute; 182 | height:auto; 183 | width:1.75em; 184 | top:1.5em; 185 | z-index:999; 186 | box-shadow:0px 8px 16px -4px rgba(0,0,0,0.2) 187 | } 188 | 189 | #head .dropdown li { 190 | display:block 191 | } 192 | 193 | #head div.dropdown { 194 | background-color:#f5f5f5; 195 | color:#000; 196 | max-width:30em; 197 | position:fixed; 198 | white-space:normal; 199 | padding:.72em 200 | } 201 | 202 | #head .dropdown li,li.version,li.language { 203 | font-family:arial,helvetica,Segoe UI Symbol!important 204 | } 205 | 206 | #head .online,#head .chm { 207 | display:none 208 | } 209 | 210 | #left { 211 | z-index:999; 212 | background:#f9f9f9; 213 | color:#000; 214 | float:left; 215 | width:18em; 216 | height:100%; 217 | -webkit-touch-callout:none; 218 | -webkit-user-select:none; 219 | -khtml-user-select:none; 220 | -moz-user-select:none; 221 | -ms-user-select:none; 222 | user-select:none; 223 | position:relative 224 | } 225 | 226 | #left.phone { 227 | float:none; 228 | height:auto; 229 | position:absolute; 230 | top:3em; 231 | bottom:0; 232 | left:0; 233 | z-index:999 234 | } 235 | 236 | #left .toc { 237 | overflow:auto; 238 | -webkit-overflow-scrolling:touch; 239 | float:left; 240 | width:inherit 241 | } 242 | 243 | #left .load { 244 | position:absolute; 245 | top:0; 246 | right:0; 247 | bottom:0; 248 | left:0; 249 | background-color: inherit; 250 | } 251 | 252 | #left .load div, #right .load div { 253 | height:100%; 254 | width:100%; 255 | display:flex; 256 | justify-content:center; 257 | align-items:center 258 | } 259 | 260 | .lds-dual-ring { 261 | display:inline-block; 262 | width:64px; 263 | height:64px; 264 | opacity: 0; 265 | animation: fadeIn .6s ease 1; 266 | animation-delay: 2s; 267 | animation-fill-mode: forwards; 268 | } 269 | 270 | .lds-dual-ring:after { 271 | content:" "; 272 | display:block; 273 | width:46px; 274 | height:46px; 275 | margin:1px; 276 | border-radius:50%; 277 | border:5px solid #fff; 278 | border-color:#3F627F transparent #3F627F transparent; 279 | animation:rotate 1.2s linear infinite 280 | } 281 | 282 | @keyframes rotate { 283 | 0% { 284 | transform:rotate(0deg); 285 | } 286 | 100% { 287 | transform:rotate(360deg); 288 | } 289 | } 290 | 291 | @keyframes fadeIn { 292 | 0% { 293 | opacity: 0; 294 | } 295 | 100% { 296 | opacity: 1; 297 | } 298 | } 299 | 300 | #left .toc ul, #left .quick .main ul { 301 | color:#3F5770; 302 | padding:0; 303 | margin:0 304 | } 305 | 306 | #left .toc > ul, #left .quick .main > ul { 307 | padding:1em 0 308 | } 309 | 310 | #left .toc li, #left .quick .main li { 311 | list-style:none; 312 | white-space:nowrap; 313 | overflow:hidden; 314 | margin:0; 315 | } 316 | 317 | #left .toc li > span, #left .quick .main li > span { 318 | box-sizing:border-box; 319 | padding:.1em 0; 320 | padding-left:1.5em; 321 | display:inline-block; 322 | height:100%; 323 | width:100%; 324 | border-left:.2em solid transparent; 325 | cursor: pointer; 326 | } 327 | 328 | #left .toc ul > li > ul { 329 | border-left:1px solid silver; 330 | margin-left:1.8em 331 | } 332 | 333 | #left .toc ul > li.highlighted > ul { 334 | border-left:1px solid #d06d3c 335 | } 336 | 337 | #left .toc li.closed > span,#left .toc li.opened > span { 338 | color:#000 339 | } 340 | 341 | #left .toc li.closed > span:before { 342 | content:'+'; 343 | width:1em; 344 | display:inline-block; 345 | margin-left:-1em; 346 | font-size:1.1em 347 | } 348 | 349 | #left .toc li.opened > span:before { 350 | content:'\2212'; 351 | width:1em; 352 | display:inline-block; 353 | margin-left:-1em; 354 | font-size:1.1em 355 | } 356 | 357 | #left .toc a, #left .quick .main a { 358 | box-sizing:border-box; 359 | color:inherit; 360 | display:inline-block; 361 | text-decoration: none; /* For IE only */ 362 | width: 100%; 363 | } 364 | 365 | #left .toc span:hover a:before, #left .quick .main span:hover a:before { 366 | text-decoration: underline; 367 | } 368 | 369 | #left .toc button, #left .quick button { 370 | align-items: normal; 371 | background-color: transparent; 372 | border: 0; 373 | box-sizing: content-box; 374 | color: inherit; 375 | cursor: pointer; 376 | font: inherit; 377 | height: auto; 378 | padding: 0; 379 | width: 100%; 380 | text-align: left; 381 | } 382 | 383 | #left .toc .selected { 384 | font-weight:700; 385 | border-left:.2em solid #d06d3c 386 | } 387 | 388 | #left .index,#left .search { 389 | position:absolute; 390 | top:0; 391 | left:0; 392 | right:0; 393 | bottom:0 394 | } 395 | 396 | #left .label { 397 | position:absolute; 398 | top:0; 399 | left:.72em; 400 | right:.72em 401 | } 402 | 403 | #left .input { 404 | position:absolute; 405 | top:.72em; 406 | left:.72em; 407 | right:.72em; 408 | height:2em 409 | } 410 | 411 | #left .input input { 412 | border:1px solid #ccc; 413 | width:100%; 414 | height:100%; 415 | box-sizing:border-box; 416 | color:inherit; 417 | background:#fff; 418 | padding:.3em .25em; 419 | font-family:helvetica,Arial,sans-serif; 420 | font-size:1em 421 | } 422 | 423 | #left .input input.match { 424 | background-color:#E6FFE6 425 | } 426 | 427 | #left .input input.mismatch { 428 | background-color:#fcc 429 | } 430 | 431 | #left .select { 432 | position:absolute; 433 | top:3em; 434 | left:.72em; 435 | right:.72em; 436 | height:2em 437 | } 438 | 439 | #left .select select { 440 | border:1px solid #ccc; 441 | width:100%; 442 | height:100%; 443 | box-sizing:border-box; 444 | color:inherit; 445 | background:#fff; 446 | font-size:inherit 447 | } 448 | 449 | #left .select select>option { 450 | font-size:inherit; 451 | color:black 452 | } 453 | 454 | #left .select .empty { 455 | color:grey !important 456 | } 457 | 458 | #left .list { 459 | position:absolute; 460 | left:.72em; 461 | right:.72em; 462 | background-color:#fff; 463 | border:1px solid silver; 464 | overflow:auto; 465 | -webkit-overflow-scrolling:touch 466 | } 467 | 468 | #left .index .list { 469 | top:5.28em; 470 | bottom:.72em 471 | } 472 | 473 | #left .search .list { 474 | top:3em; 475 | bottom:3em 476 | } 477 | 478 | #left .search .checkbox { 479 | position:absolute; 480 | bottom:.72em; 481 | left:.72em; 482 | right:.72em; 483 | height:2em 484 | } 485 | 486 | #left .search .checkbox input { 487 | height:100%; 488 | width:1em; 489 | margin:0 0 0 .5em; 490 | vertical-align:middle; 491 | text-align: center 492 | } 493 | 494 | #left .search .checkbox label { 495 | border:1px solid #ccc; 496 | box-sizing:border-box; 497 | padding-left:2em; 498 | height:100%; 499 | position:absolute; 500 | left:0; 501 | right:0; 502 | bottom:0; 503 | cursor: pointer; 504 | line-height: 1.9em; 505 | } 506 | 507 | #left .search .checkbox .updown { 508 | border:1px solid #ccc; 509 | position:absolute; 510 | bottom:0; 511 | right:0; 512 | top:0; 513 | width: 1.15em; 514 | } 515 | 516 | #left .search .checkbox .up { 517 | position:absolute; 518 | left:0; 519 | right:0; 520 | top:0; 521 | height: 50%; 522 | } 523 | 524 | .triangle-up { 525 | width:0; 526 | margin: auto; 527 | position: absolute; 528 | left: 0; 529 | right: 0; 530 | top: 25%; 531 | border-style:solid; 532 | border-width:0 .4em .4em .4em; 533 | border-color:transparent transparent #505050 transparent 534 | } 535 | 536 | #left .search .checkbox .up:hover { 537 | background-color:#c2c2c2; 538 | cursor:pointer 539 | } 540 | 541 | #left .search .checkbox .down { 542 | position:absolute; 543 | bottom:0; 544 | left:0; 545 | right:0; 546 | height: 50%; 547 | } 548 | 549 | #left .deprecated { 550 | color: brown !important; 551 | } 552 | 553 | .triangle-down { 554 | width:0; 555 | margin: auto; 556 | position: absolute; 557 | left: 0; 558 | right: 0; 559 | bottom: 25%; 560 | border-style:solid; 561 | border-width:.4em .4em 0 .4em; 562 | border-color:#505050 transparent transparent transparent; 563 | } 564 | 565 | #left .search .checkbox .down:hover { 566 | background-color:#c2c2c2; 567 | cursor:pointer 568 | } 569 | 570 | #left .list > a { 571 | text-decoration:none; 572 | color:inherit; 573 | line-height:1em; 574 | padding:.3em .25em; 575 | white-space:nowrap; 576 | text-overflow:ellipsis; 577 | overflow:hidden; 578 | display:block; 579 | cursor:default 580 | } 581 | 582 | #left .list > a:hover { 583 | color:inherit; 584 | background-color:silver; 585 | cursor:default 586 | } 587 | 588 | #left .list > a.selected { 589 | background-color:grey; 590 | color:#FFF 591 | } 592 | 593 | #left .tab { 594 | visibility: hidden; 595 | } 596 | 597 | #left .tab.full { 598 | height: calc(100% - 2em); 599 | transition: height .1s; 600 | } 601 | #left .tab.full.no-quick { /* for IE8 and IE9 */ 602 | height: 100%; 603 | } 604 | 605 | #left .tab.shrinked { 606 | height: 70%; 607 | transition: height .1s; 608 | } 609 | 610 | #left .quick { 611 | width: 100%; 612 | height: calc(30% - 2em); 613 | float: left; 614 | } 615 | 616 | #left .quick .main { 617 | overflow: auto; 618 | -webkit-overflow-scrolling: touch; 619 | height: 100%; 620 | width: inherit; 621 | } 622 | 623 | #left .quick .main.no-scroll { 624 | overflow: hidden; 625 | } 626 | 627 | #left .quick div { 628 | float: left; 629 | } 630 | 631 | #left .quick .header { 632 | height: 2em; 633 | line-height: 2em; 634 | cursor:pointer; 635 | border-top: 1px solid silver; 636 | border-bottom: 1px solid silver; 637 | } 638 | 639 | #left .quick .header .chevron { 640 | font-family: icons; 641 | font-size: 1.1em; 642 | margin: 0 .2em 0 .3em; 643 | } 644 | 645 | #left .quick .header .chevron.down:before { 646 | content: '\25BC'; 647 | } 648 | 649 | #left .quick .header .chevron.right:before { 650 | content: '\25B6'; 651 | } 652 | 653 | .dragbar { 654 | background-color:#eee; 655 | width:3px; 656 | cursor:col-resize; 657 | z-index:1000; 658 | position:absolute; 659 | top:0; 660 | bottom:0; 661 | left:18em 662 | } 663 | 664 | .ghostbar { 665 | width:3px; 666 | background-color:#000; 667 | opacity:0.5; 668 | position:absolute; 669 | cursor:col-resize; 670 | z-index:1000; 671 | height:100%; 672 | top:0 673 | } 674 | 675 | #right { 676 | height:100%; 677 | overflow:auto; 678 | -webkit-overflow-scrolling:touch; 679 | outline:none; 680 | } 681 | 682 | div#right { 683 | display: grid; 684 | grid-template-columns: 1fr; 685 | } 686 | 687 | #right .load { 688 | grid-row-start: 1; 689 | grid-column-start: 1; 690 | } 691 | 692 | #frame { 693 | border:0; 694 | height:100%; 695 | width:100%; 696 | display:block; 697 | position:relative; 698 | grid-row-start: 1; 699 | grid-column-start: 1; 700 | } 701 | 702 | #frame.hidden { 703 | opacity: 0; 704 | visibility: hidden; 705 | } 706 | 707 | #frame.visible { 708 | opacity: 1.0; 709 | visibility: visible; 710 | transition: opacity .1s, visibility .1s; 711 | } 712 | 713 | #right .area { 714 | padding:.72em 715 | } 716 | 717 | #right .footer { 718 | padding:15px 0 15px 0; 719 | margin-top:20px; 720 | opacity:0.5; 721 | border-top:1px solid silver 722 | } 723 | 724 | #right .back-to-top { 725 | display:none; 726 | line-height:20px; 727 | width:40px; 728 | font-family:icons; 729 | font-size:200%; 730 | text-align:center; 731 | position:fixed; 732 | bottom:10px; 733 | right:10px; 734 | z-index:999; 735 | background-color:#3F627F; 736 | color:white; 737 | cursor:pointer; 738 | padding-top:10px; 739 | padding-bottom:10px; 740 | opacity:0.5 741 | } 742 | 743 | div#right .back-to-top { 744 | right:27px; 745 | } 746 | 747 | #right .back-to-top:hover { 748 | opacity:1.0 749 | } 750 | 751 | @media (hover: none) { 752 | #right .back-to-top:hover { 753 | opacity: 0.5; 754 | } 755 | } 756 | 757 | #right .back-to-top:before { 758 | content:'\25B2' 759 | } 760 | 761 | #right pre.parent { 762 | position:relative 763 | } 764 | 765 | #right pre.origin { 766 | margin:0; 767 | padding:0; 768 | background-color:inherit; 769 | border:0; 770 | line-height:inherit 771 | } 772 | 773 | #right pre.parent > div.buttons { 774 | display:none; 775 | position:absolute; 776 | right:0; 777 | top:0 778 | } 779 | 780 | #right pre.parent > div.buttons > a { 781 | background-color:#777; 782 | color:#fff; 783 | cursor:pointer; 784 | display:inline-block; 785 | font-size:1.3em; 786 | line-height:1em; 787 | padding:.165em; 788 | font-family:icons 789 | } 790 | 791 | #right pre.parent > div.buttons > a:hover { 792 | cursor:pointer; 793 | background:rgba(0,0,0,.9); 794 | filter:progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#000000',endColorstr='#000000'); /* IE8 */ 795 | text-decoration:none 796 | } 797 | 798 | #right .headLine:hover:after { 799 | content:" \0000B6"; 800 | color:#888 801 | } 802 | 803 | #right .headLine > a.headLink, .ver > a { 804 | color:inherit !important 805 | } 806 | 807 | #right .headLine > a.headLink:hover { 808 | text-decoration:none; 809 | color:inherit 810 | } 811 | 812 | #right .extLink:after { 813 | content:"\00A0\00AC"; 814 | text-decoration:none; 815 | text-decoration-color: transparent; 816 | font-family:icons; 817 | vertical-align:-2px; 818 | } 819 | 820 | #right .search_highlight { 821 | background-color:#ff9632; 822 | color:#000 823 | } 824 | 825 | #right .search_highlight.current { 826 | background-color:#ff0000; 827 | color:#fff 828 | } 829 | 830 | #right table.mobile { 831 | border:solid 1px silver; 832 | border-collapse:collapse 833 | } 834 | 835 | #right table.mobile tbody { 836 | border-top:solid 1px silver 837 | } 838 | 839 | #right table.mobile td { 840 | vertical-align:top; 841 | padding:.3em .5em; 842 | border:none; 843 | width:100% 844 | } 845 | 846 | #right table.mobile p { 847 | margin-top:0 848 | } 849 | 850 | #right table.mobile td:first-child { 851 | background-color:#F6F6F6; 852 | width:auto; 853 | white-space:nowrap 854 | } 855 | 856 | #right .deprecated { 857 | color: brown; 858 | text-decoration: none; 859 | border-bottom: 1px dashed brown; 860 | } 861 | 862 | pre.origin em, code em { 863 | color:#008000 864 | } 865 | 866 | @media print { 867 | #head,#left,#main>.dragbar,#right>.load {display:none;} 868 | #main {padding-top: 0; } 869 | } 870 | 871 | pre.highlight>code { 872 | white-space: inherit; 873 | line-height: inherit; 874 | word-break: inherit; 875 | word-wrap: inherit; 876 | tab-size: inherit; 877 | padding: 0; 878 | } 879 | -------------------------------------------------------------------------------- /docs/static/content.js: -------------------------------------------------------------------------------- 1 | loadJQuery(); 2 | addPrototypeMethods(); 3 | 4 | // --- Get infos about this script file --- 5 | 6 | var scriptElement = document.querySelector('script[src$="static/content.js"]'); 7 | var scriptDir = scriptElement.src.substr(0, scriptElement.src.lastIndexOf('/')); 8 | 9 | // --- User data --- 10 | 11 | var user = { 12 | fontSize: 1.0, 13 | clickTab: 0, 14 | displaySidebar: true, 15 | colorTheme: 0, 16 | collapseQuickRef: false 17 | } 18 | 19 | // --- Cached data --- 20 | 21 | // To have the data remain while navigating through the docs, it'll be stored into 22 | // sessionStorage. Fallbacks to window.name if sessionStorage is not supported. 23 | // Note: CHM doesn't support window.localStorage/sessionStorage or cookies. 24 | 25 | var cache = { 26 | colorTheme: user.colorTheme, 27 | scriptDir: scriptDir, 28 | fontSize: user.fontSize, 29 | forceNoFrame: false, 30 | forceNoScript: false, 31 | clickTab: user.clickTab, 32 | displaySidebar: user.displaySidebar, 33 | sidebarWidth: '18em', 34 | collapseQuickRef: user.collapseQuickRef, 35 | RightIsFocused: true, 36 | toc_clickItem: null, 37 | toc_clickItemTemp: null, 38 | toc_scrollPos: 0, 39 | index_filter:-1, 40 | index_input: "", 41 | index_clickItem: 0, 42 | index_scrollPos: 0, 43 | search_data: {}, 44 | search_highlightWords: false, 45 | search_input: "", 46 | search_clickItem: 0, 47 | search_scrollPos: 0, 48 | load: function() { 49 | if (window.sessionStorage) 50 | { 51 | var data = JSON.parse(window.sessionStorage.getItem('data')); 52 | if (!data) 53 | return false; 54 | } 55 | else try { 56 | var data = JSON.parse(window.name); 57 | } catch(e) { 58 | return false; 59 | } 60 | if (data.scriptDir != scriptDir) 61 | return false; 62 | $.extend(this, data); 63 | return true; 64 | }, 65 | save: function() { 66 | if (window.sessionStorage) 67 | window.sessionStorage.setItem('data', JSON.stringify(this)); 68 | else 69 | window.name = JSON.stringify(this); 70 | }, 71 | set: function(prop, value) { 72 | this[prop] = value; 73 | try { 74 | postMessageToFrame('updateCache', [prop, value]) 75 | } catch(e) {} 76 | return value; 77 | } 78 | }; 79 | 80 | // --- Main Execute Area --- 81 | 82 | // Set global variables: 83 | var forceNoScript = forceNoScript || false; 84 | var isCacheLoaded = cache.load(); 85 | var workingDir = getWorkingDir(); 86 | var relPath = location.href.replace(workingDir, ''); 87 | var equivPath = $('meta[name|="ahk:equiv"]').prop('content'); 88 | var isInsideCHM = (location.href.search(/::/) > 0) ? 1 : 0; 89 | var supportsHistory = (history.replaceState) && !isInsideCHM; 90 | var isFrameCapable = !cache.forceNoFrame && (isInsideCHM || supportsHistory); 91 | var isInsideFrame = (window.self !== window.top); 92 | var isSearchBot = navigator.userAgent.match(/googlebot|bingbot|slurp/i); 93 | var isTouch = !!("ontouchstart" in window) || !!(navigator.msMaxTouchPoints); 94 | // http://stackoverflow.com/a/9851769 95 | var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0; // Opera 8.0+ 96 | var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+ 97 | var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0; // At least Safari 3+: "[object HTMLElementConstructor]" 98 | var isIE = /*@cc_on!@*/false || !!document.documentMode; // Internet Explorer 6-11 99 | var isIE8 = !-[1,]; // Internet Explorer 8 or below 100 | var isIE9 = navigator.userAgent.match(/MSIE 9/); // Internet Explorer 9 101 | var isEdge = !isIE && !!window.StyleMedia; // Edge 20+ 102 | var isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.csi); // Chrome 1+ 103 | var isBlink = (isChrome || isOpera) && !!window.CSS; // Blink engine detection 104 | var structure = new ctor_structure; 105 | var toc = new ctor_toc; 106 | var index = new ctor_index; 107 | var search = new ctor_search; 108 | var features = new ctor_features; 109 | var translate = {dataPath: scriptDir + '/source/data_translate.js'}; 110 | var deprecate = {dataPath: scriptDir + '/source/data_deprecate.js'}; 111 | 112 | scriptElement.insertAdjacentHTML('afterend', structure.metaViewport); 113 | var isPhone = (document.documentElement.clientWidth <= 600); 114 | 115 | (function() { 116 | // Exit the script if the user is a search bot. This is done because we want 117 | // to prevent the search bot from parsing the elements added via javascript, 118 | // otherwise the search results would be distorted: 119 | if (isSearchBot) 120 | return; 121 | 122 | // Get user data: 123 | if (!isCacheLoaded) { 124 | if (isInsideCHM) { 125 | var m = scriptDir.match(/mk:@MSITStore:(.*?)\\[^\\]+\.chm/i); 126 | if (m[1]) 127 | loadScript(decodeURI(m[1]) + '\\chm_config.js', function () { 128 | try { 129 | $.extend(cache, overwriteProps(user, config)); 130 | setInitialSettings(); 131 | } catch (e) {} 132 | }); 133 | } 134 | else if (window.localStorage) { 135 | config = JSON.parse(window.localStorage.getItem('config')); 136 | $.extend(cache, overwriteProps(user, config)); 137 | setInitialSettings(); 138 | } 139 | else if (navigator.cookieEnabled) { 140 | config = document.cookie.match(/config=([^;]+)/); 141 | config && (config = JSON.parse(config[1])); 142 | $.extend(cache, overwriteProps(user, config)); 143 | setInitialSettings(); 144 | } 145 | } 146 | else 147 | setInitialSettings(); 148 | 149 | function setInitialSettings() { 150 | // font size 151 | if (!isFrameCapable && cache.fontSize != 1) 152 | $('head').append(''); 153 | // color theme 154 | if (cache.colorTheme) 155 | structure.setTheme(cache.colorTheme); 156 | } 157 | 158 | // Exit the script on sites which doesn't need the sidebar: 159 | if (forceNoScript || cache.forceNoScript) 160 | return; 161 | 162 | // Special treatments for pages inside a frame: 163 | if (isFrameCapable) 164 | { 165 | if (isInsideFrame) 166 | { 167 | if (cache.fontSize != 1) 168 | $('head').append(''); 169 | normalizeParentURL = function() { 170 | var url = getUrlParameter('url'); 171 | postMessageToParent('normalizeURL', [url ? {"href": url} : $.extend({}, window.location), document.title, supportsHistory ? history.state : null, equivPath]); 172 | if (cache.toc_clickItemTemp) 173 | if (supportsHistory) 174 | history.replaceState($.extend(history.state, {toc_clickItemTemp: cache.toc_clickItemTemp}), null, null); 175 | cache.set('toc_clickItemTemp', null); 176 | } 177 | normalizeParentURL(); $(window).on('hashchange', normalizeParentURL); 178 | structure.setTheme(cache.colorTheme); 179 | structure.addShortcuts(); 180 | structure.addAnchorFlash(); 181 | structure.saveCacheBeforeLeaving(); 182 | if (!isIE) { 183 | structure.hideFrameBeforeLeaving(); 184 | postMessageToParent('unhideFrame', []); 185 | } 186 | $(document).ready(function() { 187 | $('html').attr({ id: 'right'}); 188 | features.add(); 189 | }); 190 | $(window).on('message onmessage', function(event) { 191 | var data = JSON.parse(event.originalEvent.data); 192 | switch(data[0]) { 193 | case 'updateCache': 194 | if(typeof data[1] === 'object') 195 | $.extend(cache, data[1]); 196 | else 197 | cache[data[1]] = data[2]; 198 | break; 199 | 200 | case 'highlightWords': 201 | search.highlightWords(data[1]); 202 | break; 203 | 204 | case 'scrollToMatch': 205 | search.scrollToMatch(data[1]); 206 | break; 207 | 208 | case 'setTheme': 209 | structure.setTheme(data[1]); 210 | break; 211 | } 212 | }); 213 | return; 214 | } 215 | else 216 | { 217 | $(window).on('message onmessage', function(event) { 218 | var data = JSON.parse(event.originalEvent.data); 219 | switch(data[0]) { 220 | case 'normalizeURL': 221 | var relPath = data[1].href.replace(workingDir, ''); 222 | try { 223 | if (history.replaceState) 224 | history.replaceState(null, null, data[1].href); 225 | } 226 | catch(e) { 227 | if (history.replaceState) 228 | history.replaceState(null, null, "?frame=" + encodeURI(relPath).replace(/#/g, '%23')); 229 | } 230 | document.title = data[2]; 231 | if (structure.modifyTools) 232 | structure.modifyTools(relPath, data[4]); 233 | if ($('#left > div.toc li > span.selected a').attr('href') == data[1].href) 234 | break; 235 | else if (data[3] && data[3].toc_clickItemTemp) { 236 | toc.deselect($('#left > div.toc')); 237 | $('#left > div.toc li > span').eq(data[3].toc_clickItemTemp).trigger('select'); 238 | } 239 | else 240 | toc.preSelect($('#left > div.toc'), data[1]); 241 | break; 242 | 243 | case 'pressKey': 244 | structure.pressKey(data[1]); 245 | break; 246 | 247 | case 'updateQuickRef': 248 | structure.updateQuickRef(data[1], data[2]); 249 | break; 250 | 251 | case 'hideFrame': 252 | $('#right .load').hide().show(0); // reload animation 253 | document.getElementById('frame').className = 'hidden'; 254 | break; 255 | 256 | case 'unhideFrame': 257 | document.getElementById('frame').className = 'visible'; 258 | break; 259 | } 260 | }); 261 | 262 | $(window).on('hashchange', function() { 263 | structure.openSite(location.href); 264 | }); 265 | } 266 | } 267 | 268 | // Add elements for sidebar: 269 | structure.build(); 270 | 271 | // Load current URL into frame: 272 | if (isFrameCapable) 273 | $(document).ready(function() { 274 | if (window.sessionStorage) 275 | window.sessionStorage.setItem('data', JSON.stringify(cache)); 276 | else 277 | document.getElementById('frame').contentWindow.name = JSON.stringify(cache); 278 | structure.openSite(scriptDir + '/../' + (getUrlParameter('frame') || relPath)); 279 | }); 280 | 281 | // Modify the site: 282 | document.getElementsByTagName('body')[0].className += ' body'; 283 | structure.modify(); 284 | if (!isFrameCapable) 285 | $(document).ready(features.add); 286 | toc.modify(); 287 | index.modify(); 288 | search.modify(); 289 | })(); 290 | 291 | // --- Constructor: Table of content --- 292 | 293 | function ctor_toc() 294 | { 295 | var self = this; 296 | self.dataPath = scriptDir + '/source/data_toc.js'; 297 | self.create = function(input) { // Create and add TOC items. 298 | var ul = document.createElement("ul"); 299 | for(var i = 0; i < input.length; i++) 300 | { 301 | var text = input[i][0]; 302 | var path = input[i][1]; 303 | var subitems = input[i][2]; 304 | if (path != '') 305 | { 306 | var el = document.createElement("a"); 307 | el.href = workingDir + path; 308 | if (cache.deprecate_data[path]) 309 | el.className = "deprecated"; 310 | } 311 | else 312 | var el = document.createElement("button"); 313 | if (isIE8) 314 | el.innerHTML = text; 315 | else 316 | { 317 | el.setAttribute("data-content", text); 318 | el.setAttribute("aria-label", text); 319 | } 320 | var span = document.createElement("span"); 321 | span.innerHTML = el.outerHTML; 322 | var li = document.createElement("li"); 323 | li.title = text; 324 | if (cache.deprecate_data[path]) 325 | li.title += "\n\n" + T("Deprecated. New scripts should use {0} instead.").format(cache.deprecate_data[path]); 326 | if (subitems != undefined && subitems.length > 0) 327 | { 328 | li.className = "closed"; 329 | li.innerHTML = span.outerHTML; 330 | li.innerHTML += self.create(subitems).outerHTML; 331 | } 332 | else 333 | li.innerHTML = span.outerHTML; 334 | ul.innerHTML += li.outerHTML; 335 | } 336 | return ul; 337 | }; 338 | // --- Modify the elements of the TOC tab --- 339 | self.modify = function() { 340 | 341 | if (!retrieveData(self.dataPath, "toc_data", "tocData", self.modify)) 342 | return; 343 | if (!retrieveData(deprecate.dataPath, "deprecate_data", "deprecateData", self.modify)) 344 | return; 345 | if (!retrieveData(translate.dataPath, "translate_data", "translateData", self.modify)) 346 | return; 347 | 348 | $toc = $('#left div.toc').html(self.create(cache.toc_data)); 349 | $tocList = $toc.find('li > span'); 350 | // --- Fold items with subitems --- 351 | 352 | $toc.find('li > ul').hide(); 353 | 354 | // --- Hook up events --- 355 | 356 | // Select the item on click: 357 | registerEvent($toc, 'click', 'li > span', function() { 358 | $this = $(this); 359 | cache.set('toc_clickItem', $tocList.index(this)); 360 | cache.set('toc_scrollPos', $toc.scrollTop()); 361 | // Fold/unfold item with subitems: 362 | if ($this.parent().has("ul").length) { 363 | $this.siblings("ul").slideToggle(100); 364 | $this.closest("li").toggleClass("closed opened"); 365 | } 366 | // Higlight and open item with link: 367 | if ($this.has("a").length) { 368 | self.deselect($toc); $this.trigger('select'); 369 | structure.openSite($this.children('a').attr('href')); 370 | structure.focusContent(); 371 | return false; 372 | } 373 | }); 374 | 375 | // Highlight the item and parents on select: 376 | registerEvent($toc, 'select', 'li > span', function() { 377 | $this = $(this); 378 | // Highlight the item: 379 | $this.addClass("selected"); 380 | // Highlight its parents: 381 | $this.parent("li").has('ul').addClass('highlighted'); 382 | $this.parent().parents('li').addClass('highlighted'); 383 | // Unfold parent items: 384 | $this.parents("ul").show(); 385 | $this.parents("ul").closest("li").removeClass('closed').addClass('opened'); 386 | }); 387 | 388 | // --- Show scrollbar on mouseover --- 389 | 390 | if (!isTouch) // if not touch device. 391 | { 392 | $toc.css("overflow", "hidden").hover(function() { 393 | $(this).css("overflow", "auto"); 394 | }, function() { 395 | $(this).css("overflow", "hidden"); 396 | }); 397 | } 398 | self.preSelect($toc, location); 399 | if (!isFrameCapable || cache.search_input) 400 | $(document).ready(function() { 401 | setTimeout( function() { self.preSelect($toc, location); }, 0); 402 | }); 403 | }; 404 | self.preSelect = function($toc, url) { // Apply stored settings. 405 | var tocList = $toc.find('li > span'); 406 | var clicked = tocList.eq(cache.toc_clickItem); 407 | var found = null; 408 | var foundList = []; 409 | var foundNoHashList = []; 410 | var url_href = (url.href.slice(-1) == '/') ? url.href + 'index.htm' : url.href; 411 | for (var i = 0; i < tocList.length; i++) { 412 | var href = tocList[i].firstChild.href; 413 | if (!href) 414 | continue; 415 | // Search for items matching the address: 416 | if (href == url_href) 417 | foundList.push($(tocList[i])); 418 | // Search for items matching the address without anchor: 419 | else if (href == url_href.substring(0, url_href.length - url.hash.length)) 420 | foundNoHashList.push($(tocList[i])); 421 | } 422 | if (foundList.length) 423 | found = $(foundList).map($.fn.toArray); 424 | else if (foundNoHashList.length) 425 | found = $(foundNoHashList).map($.fn.toArray); 426 | var el = found; 427 | // If the last clicked item can be found in the matches, use it instead: 428 | if (clicked.is(found)) 429 | el = clicked; 430 | else 431 | cache.set('toc_scrollPos', ""); // Force calculated scrolling. 432 | // If items are found: 433 | if (el) { 434 | // Highlight items and parents: 435 | self.deselect($toc); el.trigger('select'); 436 | // Scroll to the last match: 437 | if (cache.toc_scrollPos != "" || cache.toc_scrollPos != 0) 438 | $toc.scrollTop(cache.toc_scrollPos); 439 | if (!isScrolledIntoView(el, $toc)) { 440 | el[el.length-1].scrollIntoView(false); 441 | $toc.scrollTop($toc.scrollTop()+100); 442 | } 443 | } 444 | } 445 | self.deselect = function($toc) { // Deselect all items. 446 | $toc.find("span.selected").removeClass("selected"); 447 | $toc.find(".highlighted").removeClass("highlighted"); 448 | } 449 | } 450 | 451 | // --- Constructor: Keyword search --- 452 | 453 | function ctor_index() 454 | { 455 | var self = this; 456 | self.dataPath = scriptDir + '/source/data_index.js'; 457 | self.create = function(input, filter) { // Create and add the index links. 458 | 459 | var output = '', label, path, type; 460 | var type_name = {2: T("function"), 4: T("operator"), 6: T("class")}; 461 | input.sort(function(a, b) { 462 | var textA = a[0].toLowerCase(), textB = b[0].toLowerCase() 463 | return textA.localeCompare(textB); 464 | }); 465 | for (var i = 0, len = input.length; i < len; i++) 466 | { 467 | label = input[i][0]; 468 | path = input[i][1]; 469 | type = input[i][2]; 470 | if (filter != -1 && type != filter) 471 | continue; 472 | // Append type name for ambiguities: 473 | if (filter == -1 && type && type_name[type]) 474 | if (input[i-1] && input[i-1][0] == label || input[i+1] && input[i+1][0] == label) 475 | label += ' (' + type_name[type] + ')' 476 | var a = document.createElement("a"); 477 | a.href = workingDir + path; 478 | a.setAttribute("tabindex", "-1"); 479 | if (isIE8) 480 | a.innerHTML = label; 481 | else 482 | { 483 | a.setAttribute("data-content", label); 484 | a.setAttribute("aria-label", label); 485 | } 486 | output += a.outerHTML; 487 | } 488 | return output; 489 | }; 490 | self.modify = function() { // Modify the elements of the index tab. 491 | 492 | if (!retrieveData(self.dataPath, "index_data", "indexData", self.modify)) 493 | return; 494 | if (!retrieveData(translate.dataPath, "translate_data", "translateData", self.modify)) 495 | return; 496 | 497 | var $index = $('#left div.index'); 498 | var $indexSelect = $index.find('.select select'); 499 | var $indexInput = $index.find('.input input'); 500 | var $indexList = $index.find('div.list'); 501 | 502 | // --- Hook up events --- 503 | 504 | // Filter list on change: 505 | $indexSelect.on('change', function(e) { 506 | cache.set('index_filter', this.value); 507 | if(this.value == -1) 508 | $(this).addClass('empty'); 509 | else 510 | $(this).removeClass('empty'); 511 | $indexList.html(self.create(cache.index_data, this.value)); 512 | structure.addEventsForListBoxItems($indexList); 513 | }); 514 | 515 | // Select closest index entry and show color indicator on input: 516 | $indexInput.on('keyup input', function(e, noskip) { 517 | var $this = $(this); 518 | var prevInput = cache.index_input; // defaults to undefined 519 | var input = cache.set('index_input', $this.val().toLowerCase()); 520 | // if no input, remove color indicator and return: 521 | if (!input) { 522 | $this.removeAttr('class'); 523 | return; 524 | } 525 | // Skip subsequent index-matching if we have the same query as the last search, to prevent double execution: 526 | if (!noskip && input == prevInput) 527 | return; 528 | // Otherwise find the first item which matches the input value: 529 | var indexListChildren = $indexList.children(); 530 | var match = self.findMatch(indexListChildren, input); 531 | // Select the found item, scroll to it and add color indicator: 532 | if (match.length) { 533 | match.click(); 534 | // Scroll to 5th item below the match to improve readability: 535 | scrollTarget = match.next().next().next().next().next(); 536 | if (!scrollTarget.length) { scrollTarget = indexListChildren.last(); }; 537 | scrollTarget[0].scrollIntoView(false); 538 | $this.attr('class', 'match'); // 'items found' 539 | } 540 | else 541 | $this.attr('class', 'mismatch'); // 'items not found' 542 | }); 543 | $indexSelect.val(cache.index_filter).trigger('change'); 544 | self.preSelect($indexList, $indexInput); 545 | if (!isFrameCapable || cache.index_input) 546 | $(document).ready(function() { 547 | setTimeout( function() { self.preSelect($indexList, $indexInput); }, 0); 548 | }); 549 | }; 550 | self.findMatch = function(indexListChildren, input) { 551 | var match = {}; 552 | if (!input) 553 | return match; 554 | for (var i = 0; i < indexListChildren.length; i++) { 555 | var text = isIE8 ? indexListChildren[i].innerText : indexListChildren[i].getAttribute('data-content'); 556 | var listitem = text.substr(0, input.length).toLowerCase(); 557 | if (listitem == input) { 558 | match = indexListChildren.eq(i); 559 | break; 560 | } 561 | } 562 | return match; 563 | }; 564 | self.preSelect = function($indexList, $indexInput) { // Apply stored settings. 565 | var clicked = $indexList.children().eq(cache.index_clickItem); 566 | $indexInput.val(cache.index_input); 567 | if (cache.index_scrollPos == null) 568 | $indexInput.trigger('keyup', true); 569 | else 570 | { 571 | $indexList.scrollTop(cache.index_scrollPos); 572 | clicked.click(); 573 | } 574 | }; 575 | } 576 | 577 | // --- Constructor: Full text search --- 578 | 579 | function ctor_search() 580 | { 581 | var self = this; 582 | self.dataPath = scriptDir + '/source/data_search.js'; 583 | self.modify = function() { // Modify the elements of the search tab. 584 | 585 | if (!retrieveData(self.dataPath, "search_index", "SearchIndex", self.modify)) 586 | return; 587 | if (!retrieveData(self.dataPath, "search_files", "SearchFiles", self.modify)) 588 | return; 589 | if (!retrieveData(self.dataPath, "search_titles", "SearchTitles", self.modify)) 590 | return; 591 | 592 | var $search = $('#left div.search'); 593 | var $searchList = $search.find('div.list'); 594 | var $searchInput = $search.find('.input input'); 595 | var $searchCheckBox = $search.find('.checkbox input'); 596 | 597 | // --- Hook up events --- 598 | 599 | // Refresh the search list and show color indicator on input: 600 | $searchInput.on('keyup input', function(e, noskip) { 601 | var $this = $(this); 602 | var prevInput = cache.search_input; // defaults to undefined 603 | var input = cache.set('search_input', $this.val()); 604 | // if no input, empty the search list, remove color indicator and return: 605 | if (!input) { 606 | $searchList.empty(); 607 | $this.removeAttr('class'); 608 | return; 609 | } 610 | // Skip subsequent search if we have the same query as the last search, to prevent double execution: 611 | if (!noskip && input == prevInput) 612 | return; 613 | // Otherwise fill the search list: 614 | cache.set('search_data', self.create(input)); 615 | $searchList.html(cache.search_data); 616 | structure.addEventsForListBoxItems($searchList); 617 | // Select the first item and add color indicator: 618 | var searchListChildren = $searchList.children(); 619 | if (searchListChildren.length) { 620 | searchListChildren.first().click(); 621 | cache.set('search_clickItem', 0); 622 | $this.attr('class', 'match'); // 'items found' 623 | } 624 | else 625 | $this.attr('class', 'mismatch'); // 'items not found' 626 | }); 627 | self.preSelect($searchList, $searchInput, $searchCheckBox); 628 | if (!isFrameCapable) 629 | setTimeout( function() { self.preSelect($searchList, $searchInput, $searchCheckBox); }, 0); 630 | }; 631 | self.preSelect = function($searchList, $searchInput, $searchCheckBox) { // Apply stored settings. 632 | $searchInput.val(cache.search_input); 633 | if (cache.search_scrollPos == null) 634 | $searchInput.trigger('keyup', true); 635 | else 636 | { 637 | $searchList.html(cache.search_data); 638 | structure.addEventsForListBoxItems($searchList); 639 | $searchList.scrollTop(cache.search_scrollPos); 640 | $searchList.children().eq(cache.search_clickItem).click(); 641 | } 642 | $searchCheckBox.prop('checked', cache.search_highlightWords); 643 | }; 644 | self.convertToArray = function(SearchText) { // Convert text to array. 645 | // Normalize whitespace: 646 | SearchText = SearchText.toLowerCase().replace(/^ +| +$| +(?= )|\+/, ''); 647 | if (SearchText == '') 648 | return ''; 649 | else // split and remove undefined or empty strings 650 | return $(SearchText.split(' ')).filter(function(){return (!!this)}); 651 | } 652 | self.highlightWords = function(words) { 653 | var content = $(isInsideFrame ? 'body' : '#right .area'); 654 | if(words) 655 | { 656 | var qry = self.convertToArray(words); 657 | for (var i = 0; i < qry.length; i++) { 658 | content.highlight(qry[i]); 659 | } 660 | self.scrollToMatch(); // Scroll to first match. 661 | } 662 | else 663 | content.removeHighlight(); 664 | } 665 | self.scrollToMatch = function(direction) { 666 | var matches = $(isInsideFrame ? 'body' : '#right .area').find('span.search_highlight'); 667 | if (!matches.length) 668 | return; 669 | var currMatch = matches.filter('.current'); 670 | if (currMatch.length) 671 | { 672 | index = matches.index(currMatch) + (direction == 'next' ? 1 : -1); 673 | if (index > matches.length - 1) 674 | index = 0; 675 | else if (index < 0) 676 | index = matches.length - 1; 677 | currMatch.removeClass('current'); 678 | } 679 | else 680 | index = 0; 681 | matches.eq(index).addClass('current'); 682 | matches.eq(index)[0].scrollIntoView(isIE8 ? true : {block: 'center'}); 683 | } 684 | self.create = function(qry) { // Create search list. 685 | var PartialIndex = {}; 686 | var RESULT_LIMIT = 50; 687 | qry = self.convertToArray(qry); 688 | if (qry == '') 689 | return 690 | 691 | function file_has_all_words(file_index, words, start) { 692 | for ( ; start < words.length; ++start) { 693 | var iw = index_partial(words[start]) 694 | if (!iw || iw.indexOf(file_index) == -1) 695 | return false 696 | } 697 | return true 698 | } 699 | 700 | // Get each word from index and clone for modification below: 701 | var all_results = [] 702 | for (var i = 0; i < qry.length; ++i) { 703 | var t = qry[i].replace(/(\(|\(\))$/,'') // special case for page names ending with () 704 | var w = index_partial(t) 705 | w = w ? w.slice() : [] 706 | all_results[i] = get_results(w) 707 | } 708 | var ranked = rank_results(all_results,qry) 709 | return append_results(ranked); 710 | 711 | // Get normal results for each term: 712 | function get_results(w) { 713 | var c = 0 714 | var ret = [] 715 | for (var i = 0; i < w.length && c < RESULT_LIMIT; ++i) { 716 | if (!file_has_all_words(w[i], qry, 1)) 717 | continue // Skip files which don't have all the words. 718 | c++ 719 | var f = cache.search_files[w[i]] 720 | // data.files excludes '.htm' to save space, so add it back: 721 | if (f.indexOf('#') != -1) 722 | f = f.replace('#', '.htm#') 723 | else 724 | f = f + '.htm' 725 | // var ret_i = { u: location.href.replace(/\/docs\/.*/, "/docs/" + f), 726 | var ret_i = { u: f, 727 | t: (cache.search_titles[w[i]] || f) } 728 | ret.push(ret_i) 729 | } 730 | return ret 731 | } 732 | 733 | function rank_results(aro,terms) { 734 | // Organize the info: 735 | var aro_k = [] 736 | var aro_ua = [] 737 | var aro_ka = [] 738 | for (var i = 0; i < aro.length; ++i) { 739 | aro_k[i] = [] 740 | if (aro[i] === undefined) { continue; } 741 | for (var j = 0; j < aro[i].length; ++j) { 742 | aro_k[i].push(aro[i][j].t) 743 | aro_ka.push(aro[i][j].t) 744 | aro_ua[aro[i][j].t] = aro[i][j].u 745 | } 746 | } 747 | 748 | // Assemble list of unique results: 749 | var ukeys = [] 750 | for (var i = 0; i < aro_ka.length; ++i) 751 | if (ukeys.indexOf(aro_ka[i]) == -1) 752 | ukeys.push(aro_ka[i]) 753 | 754 | // The lower the rank the better 755 | // normal ranking (based on page contents): 756 | var uranks = [] 757 | for (var i = 0; i < ukeys.length; ++i) { 758 | uranks[ukeys[i]] = [] 759 | for (var j = 0; j < aro_k.length; ++j) { 760 | uranks[ukeys[i]][j] = ukeys[i].indexOf(aro_k[j]) 761 | } 762 | } 763 | // Added ranking (based on page names) 764 | // and calculate the ranks: 765 | for (var i = 0; i < ukeys.length; ++i){ 766 | var name = ukeys[i] 767 | var tmp = uranks[name] 768 | // If the name contains any of the search terms: 769 | if ( anyContains(name.toLowerCase(),terms) ) { 770 | tmp.push(0) // Give it a better rank. 771 | } else { 772 | tmp.push(1,8) // Give it a worse rank, Tweakable! 773 | } 774 | uranks[name] = array_avg(tmp) 775 | } 776 | 777 | // Sort results by rank average and finalize: 778 | var ret = [] 779 | for (var i = 0; i < ukeys.length; ++i){ 780 | var name = ukeys[i] 781 | var url = aro_ua[name] 782 | var avg = uranks[name] 783 | ret.push({n:name,u:url,a:avg}) 784 | } 785 | ret.sort(function(a,b){return (a.a - b.a)}) 786 | ret.slice(0,RESULT_LIMIT) 787 | 788 | return ret 789 | } 790 | 791 | function array_avg(arr) { 792 | var sum = 0 793 | var total = arr.length 794 | for (var j = 0; j < arr.length; ++j){ 795 | if ( (arr[j] < 0) || (arr[j-1] == arr[j]) ) 796 | total -= 1 // Give a worse rank, duplicate ranks are ignored. 797 | else 798 | sum += arr[j] 799 | } 800 | return (sum/total) 801 | } 802 | 803 | function anyContains(str, arr) { // http://stackoverflow.com/a/5582640/883015 804 | for (var i = 0, len = arr.length; i < len; ++i) { 805 | if (str.indexOf(arr[i]) != -1) 806 | return 1 807 | } 808 | return 0 809 | } 810 | 811 | function append_results(ro) { 812 | var output = ''; 813 | for (var t = 0; t < ro.length && t < RESULT_LIMIT; ++t) { 814 | var a = document.createElement("a"); 815 | a.href = workingDir + ro[t].u; 816 | a.setAttribute("tabindex", "-1"); 817 | if (isIE8) 818 | a.innerHTML = ro[t].n; 819 | else 820 | { 821 | a.setAttribute("data-content", ro[t].n); 822 | a.setAttribute("aria-label", ro[t].n); 823 | } 824 | output += a.outerHTML; 825 | } 826 | return output; 827 | } 828 | 829 | function decode_numbers(a) { 830 | // Decode a string of [a-zA-Z] based 'numbers' 831 | var n = [] 832 | for (i = 0; i < a.length; i += 2) 833 | n.push(decode_number(a.substr(i, 2))) 834 | return n 835 | } 836 | 837 | function decode_number(a) { 838 | // Decode a number encoded by encode_number() in build_search.ahk: 839 | var n = 0, c 840 | for (var i = 0; i < a.length; ++i) { 841 | c = a.charCodeAt(i) 842 | n = n*52 + c - ((c >= 97 && c <= 122) ? 97 : 39) 843 | } 844 | return n 845 | } 846 | 847 | function index_whole(word) { 848 | // Return a word from the index, decoding the list of files 849 | // if it hasn't been decoded already: 850 | var files = cache.search_index[word] 851 | if (typeof(files) == "string") { 852 | files = decode_numbers(files) 853 | cache.search_index[word] = files 854 | } 855 | return files 856 | } 857 | 858 | function index_partial(word) { 859 | if (word[0] == '+') // + prefix disables partial matching. 860 | return index_whole(word.substr(1)) 861 | // Check if we've already indexed this partial word. 862 | var files = PartialIndex[word] 863 | if (files !== undefined) 864 | return files 865 | // Find all words in search.index which *contain* this word 866 | // and cache the result. 867 | files = [] 868 | var files_low = [] 869 | for (iw in cache.search_index) { 870 | var p = iw.indexOf(word) 871 | if (p != -1) 872 | files.push.apply(p == 0 ? files : files_low, index_whole(iw)) 873 | } 874 | files = files.concat(files_low) 875 | var unique = [] 876 | for (var i = 0; i < files.length; ++i) 877 | if (unique.indexOf(files[i]) == -1) 878 | unique.push(files[i]) 879 | PartialIndex[word] = unique 880 | return unique 881 | } 882 | }; 883 | } 884 | 885 | // --- Constructor: Navigation structure --- 886 | 887 | function ctor_structure() 888 | { 889 | var self = this; 890 | self.metaViewport = ''; 891 | self.template = '
  • Δ
  • ¬