Autohotkey — программа для автоматизации действий на пк
Содержание:
- Other Features
- Mouse
- О языке
- Variables
- Commands
- Libraries of Functions: Standard Library and User Library [v1.0.47+]
- Remapping the Keyboard and Mouse
- 8 — Other Helpful Goodies
- Functions
- Установка AutoHotkey
- Parameters
- Как пользоваться
- SendPlay [v1.0.43+]
- Context-sensitive Hotkeys
- CapsLock and IME
- Introduction and Simple Examples
- Script File Codepage [AHK_L 51+]
- Returning Values to Caller
- Remapping via the Registry’s «Scancode Map»
- Introduction and Simple Examples
Other Features
NumLock, CapsLock, and ScrollLock: These keys may be forced to be «AlwaysOn» or «AlwaysOff». For example: .
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.
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:
RControl & RShift::AltTab ; Hold down right-control then press right-shift repeatedly to move forward. RControl & Enter::ShiftAltTab ; Without even having to release right-control, press Enter to reverse direction.
For more details, see .
Mouse
General Buttons
Name | Description |
---|---|
LButton | The left mouse button when used with Send, but the primary mouse button when used with hotkeys. In other words, if the user has swapped the buttons via system settings, is physically activated by clicking the right mouse button, but performs the same as physically clicking the left button. To always perform a logical left click, use or . |
RButton | The right mouse button when used with Send, but the secondary mouse button when used with hotkeys. In other words, if the user has swapped the buttons via system settings, is physically activated by clicking the left mouse button, but performs the same as physically clicking the right button. To always perform a logical right click, use or . |
MButton | Middle or wheel mouse button |
Advanced Buttons
Name | Description |
---|---|
XButton1 | 4th mouse button. Typically performs the same function as Browser_Back. |
XButton2 | 5th mouse button. Typically performs the same function as Browser_Forward. |
Wheel
Name | Description |
---|---|
WheelDown | Turn the wheel downward (toward you). |
WheelUp | Turn the wheel upward (away from you). |
WheelLeftWheelRight |
: Scroll to the left or right. Requires Windows Vista or later. These can be 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. |
О языке
Возможности языка включают:
- Совместимость с 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, можно воспользоваться большой библиотекой готовых функций.
Популярное использование AutoHotkey:
- Разработка утилит для Microsoft Windows.
- Мониторинг веб-сайтов, сетей.
- Дефрагментация дисков и резервное копирование.
- Переназначение клавиш, глобально или у отдельных программ
- Управление мышкой с помощью клавиатуры или джойстика
- Слежение за системой, автоматическое выполнение некоторых действий по желанию пользователя.
- Создание ботов/читов/помощников/биндерам к играм. Боты позволяют автоматизировать некоторые действия в играх, в результате пользователь может быстрее добиться нужного результата.
Для упрощения разработки графических интерфейсов существует визуальный редактор SmartGUI Creator.
Исходный код AutoHotkey всех версий на языке С++ доступен для загрузки на GitHub.
Текущая версия языка доступна для скачивания на официальном сайте проекта, также как и предыдущие релизы.
Variables
Feature | Description |
---|---|
A_Is64bitOS | Contains 1 (true) if the OS is 64-bit or 0 (false) if it is 32-bit. |
A_IsUnicode | In Unicode builds, this variable contains 1 (true). In ANSI builds it is not defined, so is effectively false. |
A_FileEncoding | Contains the default encoding for various commands; see FileEncoding. |
A_OSVersion | Supports Windows 7 and Windows 8; see . |
A_PriorKey | The name of the last key which was pressed prior to the most recent key-press or key-release … |
A_PtrSize | Contains the size of a pointer, in bytes. This is either 4 (32-bit) or 8 (64-bit). |
A_RegView | The current registry view as set by SetRegView. |
A_ScriptHwnd | The unique ID (HWND/handle) of the script’s hidden main window. |
Commands
Feature | Description |
---|---|
FileEncoding | Sets the default encoding for FileRead, FileReadLine, Loop Read, FileAppend, and FileOpen().See also: |
Gui | See below. |
IniRead/Write/Delete | Read, write or delete entire sections, or retrieve a list of all section names. |
Sets or removes a menu item’s icon. | |
Run | were made to the way parameters are parsed. |
Sends a Unicode character. Unicode characters may be used directly in Unicode builds. | |
SendLevel | Controls which artificial keyboard and mouse events are ignored by hotkeys and hotstrings. |
SetFormat, IntegerFast, h|H | Set lower-case or upper-case hexadecimal format. |
SetRegView, RegView | Allows registry commands in a 32-bit script to access the 64-bit registry view and vice versa. |
Perform code page or HTML transformations. | |
Retrieves the full path and name of the process that owns a given window. |
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.
Remapping the Keyboard and Mouse
The syntax for the built-in remapping feature is . For example, a script consisting only of the following line would make A behave like B:
a::b
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:
a::b b::a
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):
a::B
However, a remapping opposite to the one above would not work as one might expect, as a remapping never «releases» the modifier keys which are used to trigger it. For example, is typically equivalent to and is equivalent to . This is because each remapping to allow the key or key combination to be combined with other modifiers.
Mouse Remapping
To remap the mouse instead of the keyboard, use the same approach. For example:
Example | Description |
---|---|
Makes the middle button behave like Shift. | |
Makes the fourth mouse button behave like the left mouse button. | |
Makes the right Alt behave like the right mouse button. |
Other Useful Remappings
Example | Description |
---|---|
Makes CapsLock become Ctrl. To retain the ability to turn CapsLock on and off, add the remapping 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 remapping must be placed first for it to work. | |
Makes the fifth mouse button (XButton2) produce a control-click. | |
Makes the right Alt become Menu (which is the key that opens the context menu). | |
Makes the right Ctrl become the right Win. | |
Makes both Ctrl behave like Alt. However, see . | |
Makes Ctrl+X produce Ctrl+C. It also makes Ctrl+Alt+X produce Ctrl+Alt+C, etc. | |
Disables the right Win by having it simply return. |
You can try out any of these examples by copying them into a new text file such as «Remap.ahk», then launching the file.
See the Key List for a complete list of key and mouse button names.
8 — Other Helpful Goodies
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!
a. The mysterious square brackets
Throughout the documentation, you will see these two symbols ( and ) surrounding code in the yellow syntax box at the top of almost all pages. Anything inside of these brackets are OPTIONAL. Meaning the stuff inside can be left out if you don’t need them. When writing your code, it is very important to NOT type the square brackets in your code.
On the ControlGetText page you will see this:
ControlGetText, OutputVar , Control, WinTitle, WinText, ExcludeTitle, ExcludeText
So you could simply do this if you wanted:
ControlGetText, OutputVar
Or add in some more details:
ControlGetText, OutputVar, Control, WinTitle
What if you wanted to use ExcludeTitle but not fill in WinText or WinTitle? Simple!
ControlGetText, OutputVar, Control,,, ExcludeTitle
Please note that you cannot IGNORE parameters, but you can leave them blank. If you were to ignore , it would look like this and cause issues:
ControlGetText, OutputVar, Control, ExcludeTitle
b. Finding your AHK version
Run this code to see your AHK version:
MsgBox, %A_AhkVersion%
Or look for «AutoHotkey Help File» or «AutoHotkey.chm» in the start menu or your installation directory.
c. Trial and Error
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.
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!
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.
«If at first you don’t succeed, try, try, try again.» — Hickson, William E.
d. Indentation
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.
«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».
Not indented:
if (car = "old") { MsgBox, The car is really old. if (wheels = "flat") { MsgBox, This car is not safe to drive. return } else { MsgBox, Be careful! This old car will be dangerous to drive. } } else { MsgBox, My`, what a shiny new vehicle you have there. }
Indented:
if (car = "old") { MsgBox, The car is really old. if (wheels = "flat") { MsgBox, This car is not safe to drive. return } else { MsgBox, Be careful! This old car will be dangerous to drive. } } else { MsgBox, My`, what a shiny new vehicle you have there. }
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.
e. Asking for Help
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.
- Don’t be afraid to ask for help, even the smartest people ask others for help.
- Don’t be afraid to show what you tried, even if you think it’s silly.
- Post anything you have tried.
- 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.
- Be patient.
- Be polite.
- Be open.
- Be kind.
- Enjoy!
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.
And while you wait for help, you can try learning and doing it yourself. It’s a good feeling, making something yourself without help.
Functions
Feature | Description |
---|---|
ComObj… —ComObjActiveComObjEnwrap/UnwrapComObjParameterComObjType | Retrieves a registered COM object.Wraps/unwraps a COM object.Wraps a value and type to pass as a parameter.Retrieves a COM object’s type information. |
ComObjArray | Creates a SAFEARRAY for use with COM. |
ComObjConnect | Connects a COM object’s event sources to functions with a given prefix. |
ComObjCreate | Creates a COM object. |
ComObjError | Enables or disables notification of COM errors. |
ComObjFlags | Retrieves or changes flags which control a COM wrapper object’s behaviour. |
ComObjGet | Returns a reference to an object provided by a COM component. |
ComObjQuery | Queries a COM object for an interface or service. |
ComObjType | Retrieves type information from a COM object. |
ComObjValue | Retrieves the value or pointer stored in a COM wrapper object. |
Creates an exception object for Throw (also provides limited access to the call stack). | |
FileOpen | Provides object-oriented file I/O. |
Func | Retrieves a to a function. |
GetKeyName/VK/SC | Retrieves the name or text, virtual key code or scan code of a key. |
InStr | Searches for a given occurrence of a string, from the left or the right. |
IsByRef | Determines whether a ByRef parameter was supplied with a variable. |
IsObject | Determines whether a value is an object. |
StrPut / StrGet | Copies a string to or from a memory address, optional converting it between code pages. |
Trim | Trims certain characters from the beginning and/or end of a string. |
RegEx (?CNum:Func) | Calls a function during evaluation of a regex pattern. |
New «local library» and . | |
Functions may accept a variable number of parameters via an array. | |
Static variables can now be initialized using any expression. |
Установка AutoHotkey
Прежде чем вы сможете протестировать некоторые скрипты или создать свои собственные, вам нужно установить AutoHotkey. Посетите главную страницу AHK, нажмите Скачать на правой стороне, и выберите монтажник захватить самую простую версию для установки. Запустите диалог быстрой установки, и AutoHotkey будет запущен и готов к работе!
Теперь только что установленная программа обрабатывает выполнение сценариев, которые вы пишете на языке AutoHotkey, но у вас еще нет запущенных сценариев! Чтобы создать новый, убедитесь, что AutoHotkey запущен (откройте меню «Пуск» и введите AutoHotkey запустить программу), затем щелкните правой кнопкой мыши в любом месте на рабочем столе или в любом другом удобном месте и выберите New> AutoHotkey Script. Назовите это что-нибудь полезное и убедитесь, что файл заканчивается .АХК, или это не будет работать правильно.
Если вы собираетесь писать несколько сценариев для AutoHotkey, неплохо бы обновить ваш текстовый редактор из мягкого блокнота
, Notepad ++ — отличный бесплатный вариант, который рекомендуется для этой цели
Обратите внимание, что вы можете открыть свой текстовый редактор, ввести код и просто сохранить его как файл, оканчивающийся на .АХК и вы достигнете того же результата, что и вышеописанный метод
Теперь, когда у вас есть программное обеспечение для запуска сценариев, вы можете загрузить код, написанный другими, для автоматизации всех видов задач. Чтобы сохранить скрипт, просто загрузите его как .АХК файл и сохранить его, где вы хотите.
Возможно, вы захотите, чтобы некоторые из этих сценариев запускались сразу после загрузки компьютера, поэтому вам не нужно каждый раз запускать их вручную. Для этого скопируйте и вставьте .АХК файлы в папку «Автозагрузка», набрав оболочка: запуск в меню «Пуск» или перейдя по следующему адресу:
Это обеспечит их запуск сразу после запуска, поэтому вы не пытаетесь использовать комбинации клавиш и ничего не получаете!
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.
Как пользоваться
Дальше давайте переходить к практике и разбираться, где бесплатно скачать последнюю версию данного предложения, как его установить, а также как написать свой первый скрипт при помощи AutoHotkey.
Загрузка и установка
Начинать мы будем именно с установки. Тем более, что как таковой, ее здесь нет. Данная программа работает сразу после запуска. Рассмотрим, как его осуществить:
- Сначала мы загружаем архив с приложением, прокрутив страничку ниже и воспользовавшись кнопкой для его скачивания. Распаковываем исполняемый файл и запускаем его двойным левым кликом.
- Теперь нам необходимо предоставить доступ к администраторским полномочиям. В противном случае приложение не сможет корректно работать.
- На этом все. Наша программа установленная и теперь можно переходить непосредственно к работе с ней.
Инструкция по работе
Теперь давайте в общих чертах разберемся, как пользоваться данным приложением. Первое, что следует знать, это скриптовый язык программирования, который тут используется. Без него ни одного макроса написать, к сожалению, не получится. А сам алгоритм использования программы выглядит следующим образом:
- Вы пишите макрос, которым должна руководствоваться в своей работе AutoHotkey.
- Далее при помощи программы открываем данный скрипт и, при необходимости, преобразуем его в EXE-файл.
- Дальше мы можем использовать файл где угодно.
Вот так выглядит сам скрипт, а также созданный с его помощью исполняемый файл.
SendPlay [v1.0.43+]
Warning: SendPlay may have no effect at all if UAC is enabled, even if the script is running as an administrator. For more information, refer to the .
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 only when they have the .
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.
Like , 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.
Although SendPlay is considerably slower than SendInput, it is usually faster than the traditional mode (even when KeyDelay is -1).
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).
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:
SetKeyDelay, 0, 10, Play ; Note that both 0 and -1 are the same in SendPlay mode. SetMouseDelay, 10, Play
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 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 .
Unlike and , 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.
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 . For example, would show the Start Menu’s Run dialog.
Context-sensitive Hotkeys
The directives #IfWinActive/Exist and #If can be used to make a hotkey perform a different action (or none at all) depending on a specific condition. For example:
#IfWinActive, ahk_class Notepad ^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. #c::MsgBox You pressed Win-C while Notepad is active. #IfWinActive #c::MsgBox You pressed Win-C while any window except Notepad is active. #If MouseIsOver("ahk_class Shell_TrayWnd") ; For MouseIsOver, see . WheelUp::Send {Volume_Up} ; Wheel over taskbar: increase/decrease volume. WheelDown::Send {Volume_Down} ;
CapsLock and IME
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:
; Requires AutoHotkey v1.1.26+, and the keyboard hook must be installed. #InstallKeybdHook SendSuppressedKeyUp(key) { DllCall("keybd_event" , "char", GetKeyVK(key) , "char", GetKeySC(key) , "uint", KEYEVENTF_KEYUP := 0x2 , "uptr", KEY_BLOCK_THIS := 0xFFC3D450) }
After copying the function into a script or saving it as SendSuppressedKeyUp.ahk in a , it can be used as follows:
; Disable Alt+key shortcuts for the IME. ~LAlt::SendSuppressedKeyUp("LAlt") ; Test hotkey: !CapsLock::MsgBox % A_ThisHotkey ; Remap CapsLock to LCtrl in a way compatible with IME. *CapsLock:: Send {Blind}{LCtrl DownR} SendSuppressedKeyUp("LCtrl") return *CapsLock up:: Send {Blind}{LCtrl Up} return
Introduction and Simple Examples
A function is similar to a subroutine (Gosub) except that it can accept parameters (inputs) from its caller. In addition, a function may optionally return a value to its caller. Consider the following simple function that accepts two numbers and returns their sum:
Add(x, y) { return x + y ; "Return" expects an . }
The above is known as a function definition because it creates a function named «Add» (not case sensitive) and establishes that anyone who calls it must provide exactly two parameters (x and y). To call the function, assign its result to a variable with the := operator. For example:
Var := Add(2, 3) ; The number 5 will be stored in Var.
Also, a function may be called without storing its return value:
Add(2, 3)
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.
Since a function call is an , any variable names in its parameter list should not be enclosed in percent signs. By contrast, literal strings should be enclosed in double quotes. For example:
if (MyVar, "fox") MsgBox The variable MyVar contains the word fox.
Finally, functions may be called in the parameters of any command (except OutputVar and InputVar parameters such as those of StringLen). However, parameters that do not support must use the «% » prefix as in this example:
MsgBox % "The answer is: " . Add(3, 2)
The «% » prefix is also permitted in parameters that natively support expressions, but it is simply ignored.
Script File Codepage [AHK_L 51+]
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:
- If the file begins with a UTF-8 or UTF-16 (LE) byte order mark, the appropriate codepage is used and the switch is ignored.
- If the switch is passed on the command-line, codepage n is used. For a list of possible values, see Code Page Identifiers.
Note: The «Default to UTF-8» option in the AutoHotkey installer adds to the command line for all scripts launched via the shell (Explorer).
- In all other cases, the system default ANSI codepage is used.
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.
As all text is converted (where necessary) to the , characters which are invalid or don’t exist in the native codepage are replaced with a placeholder: ANSI ‘?’ or Unicode ‘�’. In Unicode builds, 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.
RegWrite may be used to set the default for scripts launched from Explorer (e.g. by double-clicking a file):
; Uncomment the appropriate line below or leave them all commented to ; reset to the default of the current build. Modify as necessary: ; codepage := 0 ; System default ANSI codepage ; codepage := 65001 ; UTF-8 ; codepage := 1200 ; UTF-16 ; codepage := 1252 ; ANSI Latin 1; Western European (Windows) if (codepage != "") codepage := " /CP" . codepage cmd="%A_AhkPath%"%codepage% "`%1" `%* key=AutoHotkeyScript\Shell\Open\Command if A_IsAdmin ; Set for all users. RegWrite, REG_SZ, HKCR, %key%,, %cmd% else ; Set for current user only. RegWrite, REG_SZ, HKCU, Software\Classes\%key%,, %cmd%
This assumes AutoHotkey has already been installed. Results may be less than ideal if it has not.
Returning Values to Caller
As described in , a function may optionally return a value to its caller.
Test := returnTest() MsgBox % Test returnTest() { return 123 }
If you want to return extra results from a function, you may also use :
returnByRef(A,B,C) MsgBox % A "," B "," C returnByRef(ByRef val1, ByRef val2, ByRef val3) { val1 := "A" val2 := 100 val3 := 1.1 return }
: and can be used to return multiple values or even named values:
Test1 := returnArray1() MsgBox % Test1 "," Test1 Test2 := returnArray2() MsgBox % Test2 "," Test2 Test3 := returnObject() MsgBox % Test3.id "," Test3.val returnArray1() { Test := return Test } returnArray2() { x := 456 y := "EFG" return } returnObject() { Test := {id: 789, val: "HIJ"} return Test }
Remapping via the Registry’s «Scancode Map»
Advantages:
- Registry remapping is generally more pure and effective than . For example, it works in a broader variety of games, it has no known , and it is capable of firing AutoHotkey’s hook hotkeys (whereas AutoHotkey’s remapping requires a ).
- 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).
Disadvantages:
- Registry remapping is relatively permanent: a reboot is required to undo the changes or put new ones into effect.
- Its effect is global: it cannot create remappings specific to a particular user, application, or locale.
- 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.
- It supports only the keyboard (AutoHotkey has and some limited joystick remapping).
How to Apply Changes to the Registry: There are at least two methods to remap keys via the registry:
- Use a program like KeyTweak (freeware) to visually remap your keys. It will change the registry for you.
- Remap keys manually by creating a .reg file (plain text) and loading it into the registry. This is demonstrated at
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 Win, which is known as a modifier key:
#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 Ctrl+Alt+S:
^!s:: Send Sincerely,{enter}John Smith ; This line sends keystrokes to the active (foremost) window. return