Functions

General Remarks

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:

  • SendEvent and SendInput use SendInput() with the . : ANSI builds of AutoHotkey convert the character to Unicode before sending it. Prior to v1.1.27, ANSI builds used the Alt+nnnnn method.
  • SendPlay uses the method, which produces Unicode only if supported by the target application.
  • ControlSend posts a WM_CHAR message.

Note: Characters sent using any of the above methods usually do not trigger keyboard shortcuts or hotkeys.

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

  • If a naked letter is sent (that is, without modifiers or braces), or if mode is in effect, it is sent as a character. For example, sends the expected text, even though pressing the R key (vk52) produces some other character (such as К on the Russian layout). can be omitted in this case, unless a modifier key was put into effect by a prior Send.
  • If one or more modifier keys have been put into effect by the Send command, 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, and activate the standard Ctrl+C shortcut and is equivalent to .

If the letter exists in the current keyboard layout, it is always sent as whichever keycode the layout associates with that letter (unless the 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.

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

BlockInput Compared to SendInput/SendPlay: Although the BlockInput command 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 or 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.

When sending a large number of keystrokes, a can be used to improve readability and maintainability.

Since the operating system does not allow simulation of the Ctrl+Alt+Delete combination, doing something like will have no effect.

Send may have no effect on Windows Vista or later 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.

Libraries of Functions: Standard Library and User Library [v1.0.47+]

A script may call a function in an external file without having to use #Include. For this to work, a file of the same name as the function must exist in one of the following library directories:

\Lib\  ; Local library - requires .
\AutoHotkey\Lib\  ; User library.
directory-of-the-currently-running-AutoHotkey.exe\Lib\  ; Standard library.

For example, if a script calls a nonexistent function , the program searches for a file named «MyFunc.ahk» in the user library. If not found there, it searches for it in the standard library. If a match is still not found and the function’s name contains an underscore (e.g. ), the program searches both libraries for a file named and loads it if it exists. This allows to contain both the function and other related functions whose names start with .

: The local library is supported and is searched before the user library and standard library.

Only a direct function call such as can cause a library to be auto-included. If the function is only called dynamically or indirectly, such as by a timer or GUI event, the library must be explicitly included in the script. For example:

Although a library file generally contains only a single function of the same name as its filename, it may also contain private functions and subroutines 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.

If a library file uses #Include, the working directory for #Include is the library file’s own directory. This can be used to create a redirect to a larger library file that contains that function and others related to it.

The also supports library functions. However, it requires that a copy of AutoHotkey.exe exist in the directory above the compiler directory (which is normally the case). If AutoHotkey.exe is absent, the compiler still works but library functions are not automatically included.

Functions included from a library perform just as well as other functions because they are pre-loaded before the script begins executing.

Как пользоваться

Дальше давайте переходить к практике и разбираться, где бесплатно скачать последнюю версию данного предложения, как его установить, а также как написать свой первый скрипт при помощи AutoHotkey.

Загрузка и установка

Начинать мы будем именно с установки. Тем более, что как таковой, ее здесь нет. Данная программа работает сразу после запуска. Рассмотрим, как его осуществить:

  1. Сначала мы загружаем архив с приложением, прокрутив страничку ниже и воспользовавшись кнопкой для его скачивания. Распаковываем исполняемый файл и запускаем его двойным левым кликом.

  1. Теперь нам необходимо предоставить доступ к администраторским полномочиям. В противном случае приложение не сможет корректно работать.

  1. На этом все. Наша программа установленная и теперь можно переходить непосредственно к работе с ней.

Инструкция по работе

Теперь давайте в общих чертах разберемся, как пользоваться данным приложением. Первое, что следует знать, это скриптовый язык программирования, который тут используется. Без него ни одного макроса написать, к сожалению, не получится. А сам алгоритм использования программы выглядит следующим образом:

  1. Вы пишите макрос, которым должна руководствоваться в своей работе AutoHotkey.
  2. Далее при помощи программы открываем данный скрипт и, при необходимости, преобразуем его в EXE-файл.
  3. Дальше мы можем использовать файл где угодно.

Вот так выглядит сам скрипт, а также созданный с его помощью исполняемый файл.

Repeating or Holding Down a Key

To repeat a keystroke: Enclose in braces the name of the key followed by the number of times to repeat it. For example:

Send {DEL 4}  ; Presses the Delete key 4 times.
Send {S 30}   ; Sends 30 uppercase S characters.
Send +{TAB 4}  ; Presses Shift-Tab 4 times.

To hold down or release a key: Enclose in braces the name of the key followed by the word Down or Up. For example:

Send {b down}{b up}
Send {TAB down}{TAB up}
Send {Up down}  ; Press down the up-arrow key.
Sleep 1000  ; Keep it down for one second.
Send {Up up}  ; Release the up-arrow key.

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:

Loop 20
{
    Send {Tab down}  ; Auto-repeat consists of consecutive down-events (with no up-events).
    Sleep 30  ; The number of milliseconds between keystrokes (or use SetKeyDelay).
}
Send {Tab up}  ; Release the key.

By default, Send will not automatically release a modifier key (Control/Shift/Alt/Win) if that modifier key was «pressed down» by sending it. For example, may behave similar to if the user is physically holding Ctrl, but followed by will produce a Control+A keystroke. 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/Win).

DownTemp tells subsequent sends that the key is not permanently down, and may be released whenever a keystroke calls for it. For example, followed later by would produce a normal A keystroke, not a Control+A keystroke. Any use of Send may potentially release the modifier permanently, so DownTemp is not ideal for remapping modifier keys.

: DownR (where «R» stands for remapping, which is its main use) tells subsequent sends that if the key is automatically released, it should be pressed down again when send is finished. For example, followed later by would produce a normal A keystroke, not a Control+A keystroke, but will leave the Control key in the pressed state for use with keyboard shortcuts. In other words, DownR has an effect similar to physically pressing the key.

If a character does not correspond to a virtual key on the current keyboard layout, it cannot be «pressed» or «released». For example, has no effect on most layouts, and is equivalent to .

О языке

Возможности языка включают:

  • Совместимость с Windows XP / / Vista / / / 2008 R2 / / 8.1 / 2012 /
  • Версия для 64-битных систем.
  • Поддержка Юникода.
  • Запуск консольных приложений и доступ к стандартным потокам ввода-вывода.
  • Запуск программ от имени другого пользователя.
  • Компиляция скрипта в EXE файл.
  • Включение файлов в скомпилированный файл, которые можно извлекать при запуске.
  • Сжатие и защита исполняемого файла от декомпиляции.
  • Создание графических интерфейсов GUI, информационных сообщений, форм ввода информации.
  • Вызов функций из динамических библиотек и функций Windows API.
  • Работа с реестром Windows, буфером обмена, файлами (чтение, изменение, копирование, удаление).
  • Работа с объектами COM (Сomponent object modelling).
  • Перехват и эмуляция клавиатурных нажатий и кликов мышки.
  • Работа с окнами (особенно легко работать с графическими элементами из Windows): передвижение, скрытие, отображение, изменение размера, активизация, закрытие. К окнам можно обращаться по их заголовку, отображаемому тексту, размеру, расположению, классу, по внутренним дескрипторам (handle) Win32 API, определяемым с помощью входящей в комплект поставки утилиты WindowSpy.
  • Получение информации и взаимодействие с элементами управления (особенно стандартными): поле редактирования, переключатель, список, кнопки, статусная строка и т. д., в том числе неактивными.
  • Интернет: чтение HTML кода страниц и скачивание файлов, работа с FTP, отправка E-mail сообщений, работа с базами данных MySQL и SQLite.
  • Работа с протоколами TCP и UDP.
  • Автоматизация работы в браузерах: Internet Explorer, Opera, Firefox, Google Chrome.
  • Обычные элементы высокоуровневого языка, такие как работа с циклами, функциями и переменными.
  • Огромное количество функций для работы с текстом (как со строками и массивами данных, так и с отдельными символами), в том числе с регулярными выражениями в стиле Perl (используется библиотека PCRE).
  • Работа со звуком и музыкой.
  • Работа со сложными математическими, геометрическими и физическими расчётами (например, с тригонометрическими функциями).
  • Простой синтаксис.
  • AutoHotkey_H — объединённая версия в виде COM и DLL, позволяющая использовать возможности AHK в программах, написанных на других языках.
  • Оптимизация и автоматизация монотонных действий (удаление, перемещение временных файлов, очистка кэш-данных, скачивание файлов).

Интерпретатор AutoHotkey имеет небольшой размер и не требует обязательной установки. Для работы достаточно основного файла, а для создания скрипта — любого текстового редактора. Для запуска без интерпретатора скрипт необходимо предварительно скомпилировать.

Для AutoHotkey существует интегрированная среда разработки под названием SciTE4AutoHotkey, основанная на бесплатном редакторе SciTE. Компилятор, вспомогательные утилиты и справочные материалы полностью интегрированы, что делает редактор стандартным окружением для разработчиков, использующих AHK. Компилятор AHK и среда разработки SciTE легко устанавливаются и в дополнительной настройке не нуждаются.

Подобно другим скриптовым языкам, AutoHotkey — , использующий классическую модель и переменные вариантного типа, позволяющие хранить различные типы данных, включая массивы.

Популярное использование AutoHotkey:

  • Разработка утилит для Microsoft Windows.
  • Мониторинг веб-сайтов, сетей.
  • Дефрагментация дисков и резервное копирование.
  • Переназначение клавиш, глобально или у отдельных программ
  • Управление мышкой с помощью клавиатуры или джойстика
  • Слежение за системой, автоматическое выполнение некоторых действий по желанию пользователя.
  • Создание ботов/читов/помощников/биндеров к играм. Боты позволяют автоматизировать некоторые действия в играх, в результате пользователь может быстрее добиться нужного результата.

Для упрощения разработки графических интерфейсов существует визуальный редактор SmartGUI Creator.

Исходный код AutoHotkey всех версий на языке С++ доступен для загрузки на GitHub.

Текущая версия языка доступна для скачивания на официальном сайте проекта, также как и предыдущие релизы.

Tray Icon

By default, each script adds its own icon to the taskbar notification area (commonly known as the tray).

The tray icon usually looks like this (but the color or letter changes when the script is paused or suspended):

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

  • Open — Open the script’s .
  • Help — Open the AutoHotkey offline help file.
  • Window Spy — Displays various information about a window.
  • Reload This Script — See Reload.
  • Edit This Script — See Edit.
  • Suspend Hotkeys — Suspend or unsuspend hotkeys.
  • Pause Script — Pause or unpause the script.
  • Exit — Exit the script.

By default, double-clicking the tray icon shows the script’s .

The Menu command can be used to customise the tray icon and menu.

The #NoTrayIcon directive can be used to hide the tray icon.

Language Syntax

When are quotation marks used with commands and their parameters?

Double quotes («) have special meaning only within . In all other places, they are treated literally as if they were normal characters. However, when a script launches a program or document, the operating system usually requires quotes around any command-line parameter that contains spaces, such as in this example: .

When exactly are variable names enclosed in percent signs?

Variable names are always enclosed in percent signs except in cases illustrated in bold below:

1) In parameters that are input or output variables:
2) On the left side of an assignment:
3) On the left side of traditional (non-expression) if-statements:
4) Everywhere in . For example:

If (Var1 <> Var2)
    Var1 := Var2 + 100

For further explanation of how percent signs are used, see and . Percent signs can also have other meanings:

  • The causes a command parameter to be interpreted as an expression.
  • percent signs () and percent signs in have no special meaning (they are interpreted as literal percent signs).

When should percent signs and commas be escaped?

Literal percent signs must be escaped by preceding them with an accent/backtick. For example: Literal commas must also be escaped () except when used in MsgBox or the last parameter of any command (in which case the accent is permitted but not necessary).

When commas or percent signs are enclosed in quotes within an , the accent is permitted but not necessary. For example: .

Законодательное регулирование

Parameters

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

ByRef Parameters: From the function’s point of view, parameters are essentially the same as unless they are defined as ByRef as in this example:

Swap(ByRef Left, ByRef Right)
{
    temp := Left
    Left := Right
    Right := temp
}

In the example above, the use of ByRef causes each parameter to become an alias for the variable passed in from the caller. In other words, the parameter and the caller’s variable both refer to the same contents in memory. This allows the Swap function to alter the caller’s variables by moving Left’s contents into Right and vice versa.

By contrast, if ByRef were not used in the example above, Left and Right would be copies of the caller’s variables and thus the Swap function would have no external effect.

Since return can send back only one value to a function’s caller, ByRef can be used to send back extra results. This is achieved by having the caller pass in a variable (usually empty) in which the function stores a value.

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 .

: If something other than a modifiable variable is passed to a ByRef parameter, the function behaves as though the keyword «ByRef» is absent. For example, stores the value of A_Index in i, but the value assigned to Left is discarded once the Swap function returns.

: The function can be used to determine whether the caller supplied a variable for a given ByRef parameter.

Known limitations:

  • Fields of objects are not considered variables for the purposes of ByRef. For example, if is passed to a ByRef parameter, it will behave as though ByRef was omitted.
  • It is not possible to pass Clipboard, , or to a function’s ByRef parameter, even when #NoEnv is absent from the script.
  • Although a function may call itself recursively, if it passes one of its own or non-ByRef parameters to itself ByRef, the new layer’s ByRef parameter will refer to its own local variable of that name rather than the previous layer’s. However, this issue does not occur when a function passes to itself a , , or ByRef parameter.
  • If a parameter in a function-call resolves to a variable (e.g. or or ), other parameters to its left or right can alter that variable before it is passed to the function. For example, would unexpectedly pass 1 and 0 when Var is initially 0, even when the function’s first parameter is not ByRef. Since this behavior is counterintuitive, it might change in a future release.
  • ByRef is not directly supported in functions called by COM clients, or when calling COM methods. Instead, the script receives or must pass a containing the VarType and address of the value.

Примеры

Программа «Привет, мир»:

1 ; Выводит стандартное окно с названием «Пример», надписью «Привет, мир!» и кнопкой «ОК».
2 MsgBox, , Пример, Привет, мир!

Создание диалогового окна:

1 ; Выводит диалоговое окно с кнопками «Да» и «Нет». В случае нажатия «Да» — выход из программы.
2 MsgBox, 4, Вопрос, Хотите выйти из программы? 
3 IfMsgBox, Yes
4     ExitApp
5 else
6     MsgBox, Спасибо что остались с нами.

Запуск блокнота:

1 Run, notepad.exe

Будильник на 12 часов и 00 минут:

 1 SetTimer, CheckTime, 300 ; Установка таймера на метку раз в 300 милисекунд.
 2 return ; Конец раздела автоматического выполнения. Сценарий приостанавливается, пока не сработает метка.
 3 
 4 CheckTime:
 5 	if (A_Hour == 12 && A_Min == 00) ; Если время настало.
 6 	{
 7 		ToolTip, Будильник. ; Выводим сообщение.
 8 		Sleep, 3000 ; Ждем 3 секунды.
 9 		ToolTip ; Скрываем сообщение.
10 	}
11 return

Скрытие/Показ курсора при нажатии Win + C.

 1 ; Скрывает/Показывает курсор мыши при нажатии клавиши Win + C.
 2 
 3 OnExit, ShowCursor ; При завершении работы скрипта, показываем курсор.
 4 return ; Конец раздела автоматического выполнения. Сценарий приостанавливается, пока пользователь не сделает что-нибудь.
 5 
 6 ShowCursor:
 7 	SystemCursor("On")
 8 ExitApp
 9 
10 #c::SystemCursor("Toggle") ; При нажатии на Win + C показываем/скрываем курсор.
11 
12 SystemCursor(status := 1)
13 {
14 	static AndMask, XorMask, $, hСursor
15 		, c0,c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13 ; Системный курсор.
16 		, b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13 ; Пустой курсор.
17 		, h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11,h12,h13 ; Дескрипторы курсора по умолчанию.
18 	if (status = "Init" or status = "I" or $ = "") ; Инициализация при первом вызове.
19 	{
20 		$ = h ; Активный курсор по умолчанию.
21 		VarSetCapacity( hСursor,4444, 1 )
22 		VarSetCapacity( AndMask, 32*4, 0xFF )
23 		VarSetCapacity( XorMask, 32*4,  )
24 		system_cursors = 32512,32513,32514,32515,32516,32642,32643,32644,32645,32646,32648,32649,32650
25 		StringSplit c, system_cursors, `,
26 		Loop %c0%
27 		{
28 			hСursor := DllCall("LoadCursor", "Ptr", , "Ptr", c%A_Index%)
29 			h%A_Index% := DllCall("CopyImage", "Ptr", hСursor, "UInt", 2, "Int", , "Int", , "UInt", )
30 			b%A_Index% := DllCall("CreateCursor", "Ptr", , "Int", , "Int", , "Int", 32, "Int", 32, "Ptr", &AndMask, "Ptr", &XorMask)
31         }
32     }
33 	if (status =  or status = "Off" or $ = "h" and (status <  or status = "Toggle" or status = "T"))
34 		$ = b  ; Используем пустой курсор.
35 	else
36 		$ = h  ; Используем системный курсор.
37 	
38 	Loop %c0%
39 	{
40 		hСursor := DllCall( "CopyImage", "Ptr",%$%%A_Index%, "UInt",2, "Int",, "Int",, "UInt", )
41 		DllCall("SetSystemCursor", "Ptr", hСursor, "UInt", c%A_Index%)
42 	}
43 }

Пример скрипта с использованием графического интерфейса:

 1 Gui, Add, Text,, Имя
 2 Gui, Add, Text,, Фамилия
 3 Gui, Add, Edit, vFirstName ym ; Параметр ym запускает новый столбец элементов управления.
 4 Gui, Add, Edit, vLastName
 5 Gui, Add, Button, default, OK ; Метка ButtonOK (если она существует) будет запущена при нажатии кнопки.
 6 Gui, Show,, Простой Пример Ввода
 7 return ; Конец раздела автоматического выполнения. Сценарий приостанавливается, пока пользователь не сделает что-нибудь.
 8 
 9 ButtonOK:
10 	Gui, Submit ; Сохраняет входные данные пользователя в связанную переменную каждого элемента управления.
11 	MsgBox Ваша Имя Фамилия "%FirstName% %LastName%".
12 GuiClose: ; Запускается при закрытии интерфейса.
13 ExitApp

Optional Parameters

When defining a function, one or more of its parameters can be marked as optional. This is done by appending (in or later) or , followed by the parameter’s default value, which must be one of the following: , , a literal integer, a literal floating point number, or a quoted/literal string such as «fox» or «» (but strings in versions prior to support only «»).

The use of (without a colon) is permitted for backward-compatibility, but not recommended, and will not be permitted by AutoHotkey v2. Regardless of which operator is used, default values which are strings must always be enclosed in quote marks.

The following function has its Z parameter marked optional:

Add(X, Y, Z:=0) {
    return X + Y + Z
}

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.

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. : Optional parameters may be omitted from the middle of the parameter list when calling the function, as shown below. For dynamic function calls and method calls, this requires .

MyFunc(1,, 3)
MyFunc(X, Y:=2, Z:=0) {  ; Note that Z must still be optional in this case.
    MsgBox %X%, %Y%, %Z%
}

: also support default values; for example: . 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 keyword «ByRef» is absent.

Introduction and Simple Examples

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 the Win key, which is known as a modifier:

#n::
Run Notepad
return

In the final line above, serves to finish the hotkey. 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 is implicit:

#n::Run Notepad

To use more than one modifier with a hotkey, list them consecutively (the order does not matter). The following example uses to indicate Control+Alt+S:

^!s::
Send Sincerely,{enter}John Smith  ; This line sends keystrokes to the active (foremost) window.
return

Dynamically Calling a Function

: A function (even a ) may be called dynamically via percent signs. For example, would call the function whose name is contained in Var. Similarly, would call Func1() or Func2(), etc., depending on the current value of A_Index.

: Var in can contain a function name or a function object. If the function does not exist, the ‘s __Call meta-function is invoked instead.

If the function cannot be called due to one of the reasons below, the evaluation of the expression containing the call stops silently and prematurely, which may lead to inconsistent results:

  • Calling a nonexistent function, which can be avoided by using . Except for , the called function’s must exist explicitly in the script by means such as #Include or a non-dynamic call to a .
  • Passing too few parameters, which can be avoided by checking ‘s return value (which is the number of mandatory parameters plus one). : Note that passing too many parameters is tolerated; each extra parameter is fully evaluated (including any calls to functions) and then discarded.

Finally, a dynamic call to a function is slightly slower than a normal call because normal calls are resolved (looked up) before the script begins running.

Скрипты AutoHotkey

Теперь, когда вы настроили AutoHotkey, пришло время получить ваш первый скрипт. Некоторые сценарии AutoHotkey настолько короткие, что публикуются в сети в виде коротких фрагментов текста. Выберите текст сценария и скопируйте его.

Теперь запустите «Блокнот» и вставьте скрипт. Убедитесь, что вы скопировали все с самого начала и до конца.

Затем сохраните файл где-нибудь на вашем компьютере. Имя файла не имеет значения, но расширение должно быть .ahk.

Пример скрипта:

#IfWinNotActive Total Commander
RButton::click right
RButton & WheelDown::Send {Browser_Back}
RButton & WheelUp::Send {Browser_Forward}
#IfWinNotActive

Этот скрипт делает так, что при зажатой правой кнопки мыши колёсико начинает выполнять функцию кнопок Вперёд и Назад. Например, в веб-браузере таким образом вы можете вернуться на предыдущую страницу.

Variadic Functions [AHK_L 60+]

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:

Join(sep, params*) {
    for index,param in params
        str .= param . sep
    return SubStr(str, 1, -StrLen(sep))
}
MsgBox % Join("`n", "one", "two", "three")

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 , the second at and so on. As with any standard object, can be used to determine the highest numeric index (in this case the number of parameters). However, if there are no parameters, MaxIndex returns an empty string.

Notes:

  • The «variadic» parameter can only appear at the end of the formal parameter list.
  • RegEx callouts cannot be variadic; the «variadic» parameter is tolerated but left blank.
  • Callbacks pass surplus parameters rather than via an array.

Variadic Function Calls

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:

substrings := 
MsgBox % Join("`n", substrings*)

Notes:

  • Numbering of parameters within the source array begins at 1.
  • Optional parameters may be entirely omitted from the array.
  • The array of parameters may contain named items when calling a user-defined function; in any other case, named items are not supported.
  • The target function may also be variadic, in which case named items are copied even if they have no corresponding formal parameter.
  • This syntax can also be used when calling methods or retrieving properties of objects; for example, . : It can also be used for setting properties.

Known limitations:

  • Only the right-most parameter can be expanded this way. For example, is supported but is not.
  • There must not be any non-whitespace characters between the asterisk () and the symbol which ends the parameter list.

Create a Script

There are a couple of common ways to create a script file:

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

    Be sure to save the file as UTF-8 with BOM if it will contain non-ASCII characters. For details, see the .

  • 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 extension if it is visible).

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

Hotkey Tips and Remarks

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 NumLock state. For example:

NumpadEnd::
Numpad1::
MsgBox, This hotkey is launched regardless of whether NumLock is on.
return

If the is used with a 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:

~RButton & LButton::MsgBox You pressed the left mouse button while holding down the right.
RButton & WheelUp::MsgBox You turned the mouse wheel up while holding down the right button.

The Suspend command can temporarily disable all hotkeys except for ones you make exempt. For greater selectivity, use #IfWinActive/Exist.

By means of the Hotkey command, hotkeys can be created dynamically while the script is running. The Hotkey command can also modify, disable, or enable the script’s existing hotkeys individually.

Joystick hotkeys do not currently support modifier prefixes such as ^ (Control) and # (Win). However, you can use GetKeyState to mimic this effect as shown in the following example:

Joy2::
if not GetKeyState("Control")  ; Neither the left nor right Control key is down.
    return  ; i.e. Do nothing.
MsgBox You pressed the first joystick's second button while holding down the Control key.
return

There may be times when a hotkey should wait for its own modifier keys to be released before continuing. Consider the following example:

^!s::Send {Delete}

Pressing Control+Alt+S would cause the system to behave as though you pressed Control+Alt+Delete (due to the system’s aggressive detection of Ctrl+Alt+Delete). To work around this, use KeyWait to wait for the keys to be released; for example:

^!s::
KeyWait Control
KeyWait Alt
Send {Delete}
return

If a hotkey label like produces an error like «Invalid Hotkey», your system’s keyboard layout/language might not have the specified character («Z» in this case). Try using a different character that you know exists in your keyboard layout.

A hotkey label can be used as the target of a Gosub or Goto. For example: .

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 .

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 MsgBox is being displayed by the current hotkey.

SendInput [v1.0.43+]

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.

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.

Note: SendInput ignores SetKeyDelay because the operating system does not support a delay in this mode. However, when SendInput reverts to under the conditions described below, it uses (unless SendEvent’s KeyDelay is , in which case is used). When SendInput reverts to , it uses SendPlay’s KeyDelay.

If a script other than the one executing SendInput has a low-level keyboard hook installed, SendInput automatically reverts to (or if 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 , it will not revert in these cases, making it less reliable than SendPlay/Event.

When SendInput sends mouse clicks by means such as , and is in effect (the default), 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 command will be wrong because they will still be relative to the old window rather than the new one.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector