Как написать ahk на нажатие клавиш

home icon
Все разделы

comunity icon
Нужна помощь?

Посылает нажатия клавиш и щелчки мыши в активное окно.

Send Keys
SendRaw Keys
SendInput Keys
SendPlay Keys
SendEvent Keys

Параметры

Keys Последовательность посылаемых клавиш. Как и в других командах, запятая перед первым параметром необязательна.

Режим Raw (как есть): Команда SendRaw посылает клавиши в точности как они указаны, т.е. не преобразует {Enter} в нажатие клавиши Enter или ^c в нажатие Control-C и т.п. Чтобы использовать этот режим в командах SendInput, SendPlay или SendEvent, напишите {Raw} в начале посылаемой строки, например: SendInput {Raw}abc.

Нормальный режим: В этом режиме нижеследующие символы интерпретируются как модификаторы (они модифицируют только идущую непосредственно за ними клавишу).

!: Посылает нажатие Alt. Например, команда Send This is text!a пошлёт «This is text» и затем комбинацию Alt+a. Замечание: в некоторых программах !A — не то же самое, что !a. Причина в том, что !A нажимает Alt+Shift+a, в то время как !a нажимает Alt+a. Если сомневаетесь, используйте нижний регистр.

+: Посылает нажатие Shift. Например, Send +abC пошлёт текст «AbC», а Send !+a пошлёт комбинацию Alt+Shift+a.

^: Посылает нажатие Control. Например, ^!a нажмёт Ctrl+Atl+a, Send ^{Home} пошлёт Ctrl+Home. Замечание: в некоторых программах ^A — не то же самое, что ^a, поскольку ^A посылает Ctrl+Shift+a, в то время как ^a посылает Ctrl+a. Если сомневаетесь, используйте нижний регистр.

#: Посылает нажатие Win, т.е. Send #e нажмёт клавишу Windows и, удерживая её, нажмёт клавишу «e».

SendInput и SendPlay [с версии 1.0.43]: SendInput и SendPlay используют тот же синтаксис, что и Send, но работают, как правило, быстрее и более надёжно. Кроме того они буферизуют физические нажатия на клавиши и кнопки мыши, которые происходят во время посылки, что не позволяет нажатиям пользователя смешиваться с теми, которые посылает скрипт. С помощью команды SendMode можно сделать команду Send синонимом SendInput или SendPlay. Более детальное описание каждого из режимов смотрите в разделах SendInput и SendPlay ниже.

SendEvent [с версии 1.0.43]: SendEvent использует для посылки тот же метод, что и команда Send в версиях до 1.0.43. Скорость посылки нажатий задаётся командой SetKeyDelay. По умолчанию, Send является синонимом SendEvent, но может быть сделана синонимом SendPlay или SendInput с помощью команды SendMode.

Имена клавиш. В списке ниже перечислены имена специальных клавиш, которые можно посылать (каждое имя должно заключаться в фигурные скобки).

Имя клавиши Результирующее нажатие
{F1} — {F24} Функциональные клавиши. Например, {F12} означает клавишу F12.
{!} !
{#} #
{+} +
{^} ^
{{} {
{}} }
{Enter} ENTER на основной клавиатуре
{Escape} или {Esc} ESCAPE
{Space} Пробел (такое обозначение нужно только для пробелов в начале или конце строки, пробелы в середине могут быть обычными)
{Tab} TAB
{Backspace} или {BS} Backspace
{Delete} или {Del} Delete
{Insert} или {Ins} Insert
{Up} Стрелка вверх на основной клавиатуре
{Down} Стрелка вниз на основной клавиатуре
{Left} Стрелка влево на основной клавиатуре
{Right} Стрелка вправо на основной клавиатуре
{Home} Home на основной клавиатуре
{End} End на основной клавиатуре
{PgUp} Page Up на основной клавиатуре
{PgDn} Page Down на основной клавиатуре
   
{CapsLock} CapsLock (использование команды SetCapsLockState более надёжно в NT/2k/XP)
{ScrollLock} ScrollLock (см. также SetScrollLockState)
{NumLock} NumLock (см. также SetNumLockState)
   
{Control} или {Ctrl} CONTROL (посылается код нейтральной виртуальной клавиши и левый сканкод)
{LControl} или {LCtrl} Левый CONTROL (то же, что CONTROL в Win9x, но в NT/2k/XP будет послан код левой виртуальной клавиши)
{RControl} или {RCtrl} Правый CONTROL
{Control Down} или {Ctrl Down} Нажимает и удерживает CONTROL пока не будет послан {Ctrl Up}. XP/2000/NT: Чтобы удерживать конкретно левый или правый Control, используйте {LCtrl Down} и {LCtrl Up}, {RCtrl Down} и {RCtrl Up}.
   
{Alt} ALT (посылается код нейтральной виртуальной клавиши и левый сканкод)
{LAlt} Левый ALT (то же, что ALT в Win9x, но в NT/2k/XP посылается код левой виртуальной клавиши)
{RAlt} Правый ALT (или AltGr, в зависимости от раскладки клавиатуры)
{Alt Down} Нажимает и удерживает ALT пока не будет послан {Alt Up}. XP/2000/NT: Чтобы удерживать конкретно левый или правый Alt, используйте {LAlt Down} и {LAlt Up}, {RAlt Down} и {RAlt Up}.
   
{Shift} SHIFT (посылает код нейтральной виртуальной клавиши и левый сканкод)
{LShift} Левый SHIFT (то же, что SHIFT в Win9x, но в NT/2k/XP посылается код левой виртуальной клавиши)
{RShift} Правый SHIFT
{Shift Down} Нажимает и удерживает SHIFT пока не будет послан {Shift Up}. XP/2000/NT: Чтобы удерживать конкретно левый или правый Shift, используйте {LShift Down} и {LShift Up}, {RShift Down} и {RShift Up}.
   
{LWin} Левая клавиша Windows
{RWin} Правая клавиша Windows
{LWin Down} Нажимает и удерживает левую клавишу Windows пока не будет послан {LWin Up}
{RWin Down} Нажимает и удерживает правую клавишу Windows пока не будет послан {RWin Up}
   
{AppsKey} Клавиша контекстного меню
{Sleep} Клавиша SLEEP
{ASC nnnnn} Посылает комбинацию Alt с кодом символа (набираемого на цифровой клавиатуре), которая может быть использована для генерации символов, которые не существуют на клавиатуре. Чтобы сгенерировать символы ASCII, используйте коды от 1 до 255. Для символов ANSI (стандарт для большинства языков) используйте коды от 128 до 255, но добавьте в начало 0, например {Asc 0133}.

Для символов Unicode указывайте коды от 256 до 65535 (без нуля в начале). Однако это поддерживается не всеми приложениями. Поэтому для большей совместимости и упрощения посылки длинных строк в Unicode используйте команду Transform Unicode.

{vkXX}
{scYYY}
{vkXXscYYY}
Посылает нажатие, которое имеет код виртуальной клавиши XX и сканкод YYY. Например: Send {vkFFsc159}. Если sc- или vk-часть опущена, вместо неё посылается наиболее подходящее значение.

Значения XX и YYY шестнадцатеричные и обычно могут быть определены через пункт меню View — Key history в главном окне скрипта (это окно открывается через пункт Open в меню значка в трее). См. также раздел «Специальные клавиши» на странице «Список клавиш и кнопок мыши/джойстика».

   
{Numpad0} — {Numpad9} Цифры на цифровой (дополнительной) клавиатуре. Например, {Numpad5} — это цифра 5.
{NumpadDot} Точка на цифровой клавиатуре.
{NumpadEnter} Enter на цифровой клавиатуре.
{NumpadMult} Умножение на цифровой клавиатуре.
{NumpadDiv} Деление на цифровой клавиатуре.
{NumpadAdd} Плюс на цифровой клавиатуре.
{NumpadSub} Минус на цифровой клавиатуре.
   
{NumpadDel} Delete на цифровой клавиатуре.
{NumpadIns} Insert на цифровой клавиатуре.
{NumpadClear} Clear на цифровой клавиатуре (обычно это клавиша ‘5’, когда выключен NumLock).
{NumpadUp} Стрелка вверх на цифровой клавиатуре.
{NumpadDown} Стрелка вниз на цифровой клавиатуре.
{NumpadLeft} Стрелка влево на цифровой клавиатуре.
{NumpadRight} Стрелка вправо на цифровой клавиатуре.
{NumpadHome} Home на цифровой клавиатуре.
{NumpadEnd} End на цифровой клавиатуре.
{NumpadPgUp} Page Up на цифровой клавиатуре.
{NumpadPgDn} Page Down на цифровой клавиатуре.
   
{Browser_Back} 2000/XP/Vista+: Выбор кнопки «Назад» в браузере.
{Browser_Forward} 2000/XP/Vista+: Выбор кнопки «Вперед» в браузере.
{Browser_Refresh} 2000/XP/Vista+: Выбор кнопки «Обновить» в браузере.
{Browser_Stop} 2000/XP/Vista+: Выбор кнопки «Остановить» в браузере.
{Browser_Search} 2000/XP/Vista+: Выбор кнопки «Поиск» в браузере.
{Browser_Favorites} 2000/XP/Vista+: Выбор кнопки «Избранное» в браузере.
{Browser_Home} 2000/XP/Vista+: Запустить браузер и перейти на домашнюю страницу.
{Volume_Mute} 2000/XP/Vista+: Выключить/включить главный регулятор звука. Обычно эквивалентно команде SoundSet, +1, , mute
{Volume_Down} 2000/XP/Vista+: Уменьшить громкость на главном регуляторе. Обычно эквивалентно SoundSet -5
{Volume_Up} 2000/XP/Vista+: Увеличить громкость на главном регуляторе. Обычно эквивалентно SoundSet +5
{Media_Next} 2000/XP/Vista+: Выбор следующего трека в медиа-проигрывателе.
{Media_Prev} 2000/XP/Vista+: Выбор предыдущего трека в медиа-проигрывателе.
{Media_Stop} 2000/XP/Vista+: Остановка медиа-проигрывателя.
{Media_Play_Pause} 2000/XP/Vista+: Пауза/продолжение в медиа-проигрывателе.
{Launch_Mail} 2000/XP/Vista+: Запуск приложения электронной почты.
{Launch_Media} 2000/XP/Vista+: Запуск медиа-проигрывателя.
{Launch_App1} 2000/XP/Vista+: Запуск пользовательского приложения 1.
{Launch_App2} 2000/XP/Vista+: Запуск пользовательского приложения 2.
   
{PrintScreen} PrintScreen
{CtrlBreak} Ctrl+Break
{Pause} Pause
   
{Click [Options]}
[с версии 1.0.43]
Посылается щелчок мыши, при этом доступны те же опции, что и для команды Click. Например, {Click} щёлкнет один раз левой кнопкой в текущей позиции указателя, а {Click 100, 200} щёлкнет в точке с координатами 100, 200 (основываясь на CoordMode). Чтобы переместить мышь без щелчка, поставьте 0 после координат; например, {Click 100, 200, 0}. Паузу между щелчками задаёт SetMouseDelay (не SetKeyDelay).
{WheelDown}, {WheelUp}, {LButton}, {RButton}, {MButton}, {XButton1}, {XButton2} Посылается событие кнопки или колеса мыши в текущей позиции указателя (изменение позиции и другие возможности смотрите в описании {Click} выше. Задержку между щелчками задаёт SetMouseDelay.
{Blind} Когда {Blind} стоит первым в посылаемой строке, клавиши Alt/Control/Shift/Win, находящиеся в нажатом состоянии, не будут отпущены перед посылкой строки. Например, комбинация +s::Send {Blind}abc пошлёт ABC, а не abc, поскольку пользователь держит нажатым Shift.

{Blind} также влечёт за собой игнорирование SetStoreCapslockMode, т.е. состояние CapsLock не будет изменено. Наконец, при использовании {Blind} не посылаются дополнительные нажатия Control. Эти нажатия предотвращают: 1) активацию Главного меню во время нажатий LWin/RWin; 2) активацию строки меню окна при посылке Alt.

Режим Blind внутренне используется при переназначении клавиш. Например, переназначение a::b будет выдавать: 1) «b», когда вы нажмёте «a»; 2) «B» при нажатии «A» (в верхнем регистре); 3) Control-B при нажатии Control-A.

{Blind} не поддерживается командами SendRaw и ControlSendRaw, а также не полностью поддерживается командой SendPlay, особенно когда дело касается клавиш-модификаторов (Control, Alt, Shift, Win).

{Raw}
[с версии 1.0.43]
Посылает строку буквально как она есть, т.е. не преобразует {Enter} в нажатие клавиши Enter, ^c в нажатие Control-C и т.п. Действие {Raw} распространяется на ту часть строки, которая следует после него.

Повтор или удержание клавиши

Чтобы повторить нажатие несколько раз, заключите в фигурные скобки имя клавиши и число повторов. Например:

Send {DEL 4} ; Нажать Delete 4 раза.
Send {S 30} ; Послать 30 S в верхнем регистре.
Send +{TAB 4} ; Нажать Shift-Tab 4 раза.

Чтобы удерживать нажатой или отпустить клавишу, поместите в фигурные скобки её имя и слово Down (вниз) или Up (вверх). Например:

Send {b down}{b up}
Send {TAB down}{TAB up}
Send {Up down} ; Нажать клавишу «Стрелка вверх».
Sleep 1000 ; Держать её нажатой 1 секунду.
Send {Up up} ; Отпустить.

Когда клавиша удерживается вышеописанным методом, не происходит её автоповтор, как это было бы при физическом удержании (причина в том, что автоповтор является возможностью драйвера/оборудования). Однако для симуляции автоповтора можно использовать Loop. Следующий пример посылает 20 нажатий Tab:

Loop 20
{
Send {Tab down} ; Автоповтор состоит из цепочки событий Down (без Up).
Sleep 30 ; Пауза в миллисекундах между нажатиями (либо используйте SetKeyDelay).
}
Send {Tab up} ; Отпустить клавишу.

Вместо Down также можно использовать DownTemp. Эффект будет тот же, за исключением клавиш-модификаторов (Control/Shift/Alt/Win). В последнем случае DownTemp сообщает следующим за ним посылающим командам, что модификаторы не являются постоянно нажатыми, т.е. они могут отпускаться, если это нужно. Например, если за командой Send {Control DownTemp} следует команда Send a, ею будет послано обычное нажатие «а», а не комбинация Control-A.

Общие замечания

В добавок к буквам от A до Z, также поддерживаются следующие буквы и символы (однако, если кодовая страница вашей системы отлична от 1252 [США и Западная Европа], этот список может быть иным):

€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿

ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ

BlockInput в сравнении с SendInput/SendPlay: Хотя команда BlockInput может быть использована для защиты симулируемых скриптом нажатий от прерывания физическими нажатиями, производимыми пользователем, для этой цели часто лучше использовать SendInput или SendPlay. Их преимущество в том, что они не отбрасывают то, что печатает пользователь во время посылки; его нажатия запоминаются и посылаются позже.

Если нужно послать большое количество нажатий, их можно поместить в секцию продолжения, чтобы улучшить читабельность скрипта.

Поскольку операционная система не позволяет симуляцию комбинации CTRL-ALT-DELETE, команды вроде ^!{Delete} работать не будут.

SendInput [с версии 1.0.43]

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

В отличие от других методов, SendInput имеет ограничение со стороны операционной системы на количество посылаемых символов — не более 5000. Это число может варьироваться в зависимости от версии операционной системы и настроек производительности. Символы и события сверх этого лимита не посылаются.

Замечание: SendInput игнорирует SetKeyDelay, поскольку операционная система не поддерживает задержки для этого режима. Однако когда SendInput сбрасывается в SendEvent при условиях, описанных ниже, он использует SetKeyDelay -1, 0 (исключение: если задержки для SendEvent были установлены как «-1,-1», то используется эта настройка). Если SendInput сбрасывается в SendPlay, он использует его задержки.

Если какой-то другой скрипт (не тот, где выполняется SendInput) установил низкоуровневый хук клавиатуры, SendInput автоматически переключается в SendEvent (или в SendPlay, если действует команда SendMode InputThenPlay). Это делается потому, что присутствие внешнего хука сводит на нет все преимущества SendInput, делая его хуже как SendPlay, так и SendEvent. Однако поскольку SendInput не способен обнаруживать низкоуровневые хуки, установленные другими программами, а только AutoHotkey с версии 1.0.43, в этих случаях он не будет переключаться, что сделает его менее надёжным, чем SendPlay/Event.

Когда SendInput посылает щелчки мыши способами вроде {Click}, и действует команда CoordMode Mouse, Relative (настройка по умолчанию), координаты щелчков будут относительны к окну, которое было активным в момент начала посылки. Поэтому, если SendInput в процессе посылки намеренно активирует другое окно (например, через Alt-Tab), координаты последующих щелчков будут неверными, поскольку они останутся относительными к прежнему окну, а не к новому.

SendPlay [с версии 1.0.43]

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

Из трёх режимов посылки, SendPlay самый необычный, так как он не симулирует нажатия и щелчки как таковые. Вместо этого он создаёт последовательность событий (сообщений), которые идут напрямую активному окну (наподобие ControlSend, но на более низком уровне).

Как и у SendInput, нажатия SendPlay не смешиваются с теми, что производит пользователь. Нажатия пользователя запоминаются и посылаются позже.

Хотя SendPlay значительно медленнее SendInput, он обычно быстрее, чем традиционный SendEvent (даже с задержкой -1).

SendPlay неспособен вызывать срабатывание системных горячих клавиш, использующих клавиши Windows (LWin и RWin). Например, он не может вызвать Главное меню или открыть диалог «Выполнить» через Win-R.

Клавиши Windows (LWin и RWin) автоматически блокируются во время SendPlay, если установлен хук клавиатуры. Это предотвращает появление Главного меню, если пользователь случайно нажмёт клавишу Windows во время посылки. Другие клавиши не нуждаются в такой блокировке, поскольку операционная система буферизует их нажатия до момента окончания SendPlay.

SendPlay не использует стандартные настройки SetKeyDelay и SetMouseDelay. По умолчанию, задержки у него отсутствуют вообще. Как их можно изменить, показано в примерах ниже:

SetKeyDelay, 0, 10, Play ; Учтите, что 0 и -1 — это одно и то же для SendPlay.
SetMouseDelay, 10, Play

SendPlay не может включать и выключать CapsLock, NumLock и ScrollLock. Также он не может изменить состояние клавиш, которое считывается через GetKeyState, разве только нажатия посылаются в какое-либо из окон самого скрипта. Даже в этом случае изменения состояний левых и правых клавиш-модификаторов (например, RControl) могут быть считаны только через их нейтральный вариант (например, Control). SendPlay также имеет и другие ограничения, о которых рассказано в описании команды SendMode.

В отличие от SendInput и SendEvent, пользователь может прервать работу SendPlay, нажав Control-Alt-Del или Control-Escape. Когда такое происходит, оставшиеся нажатия не посылаются, но скрипт продолжает выполняться, как если бы SendPlay завершился нормально.

Хотя SendPlay может посылать события LWin и RWin, но они посылаются в активное окно и не выполняют своей обычной функции в операционной системе. Чтобы обойти это, используйте SendEvent. Например, команда SendEvent #r вызовет диалог «Выполнить».

Примеры

; Примечание переводчика: посылка русских букв работает нормально,
; если принимающее окно переключено на русский язык.
Send Искренне ваш,{enter}Джон Смит ; Печатает подпись на двух строках.
Send !фс ; Выбор пункта Файл -> Сохранить (Alt+Ф и затем С).
Send {End}+{Left 4} ; Перейти в конец текста, затем послать
; 4 нажатия Shift+Стрелка влево.
SendInput {Raw}Длинная последовательность символов, посылаемая без интерпретации.

Автор перевода: YMP

Настоящее имя переводчика: Юрий Попов

Список клавиш и кнопок мыши/джойстика

Мышь (работает только с Windows NT/2000/XP)

LButton — левая кнопка мыши

RButton — правая кнопка мыши

MButton — средняя кнопка мыши (или колесо)

WheelDown — поворот колеса мыши «вниз»

WheelUp — поворот колеса мыши «вверх»

Поддерживается только Windows 2000/XP:

XButton1 — четвертая кнопка мыши, боковая

XButton2 — пятая кнопка мыши, боковая

Клавиатура

Примечание: названия буквенных и цифровых клавиш точно такие же, как и сами символы этих клавиш. То есть, клавиша «b» записывается как b, а клавиша «5» как 5.

Space — пробел

Tab

Enter (или Return)

Escape (или Esc)

Backspace (или BS)

Delete (или Del)

Insert (или Ins)

Home

End

PgUp

PgDn

Up

Down

Left

Right

ScrollLock

CapsLock

NumLock

NumpadDiv — слэш «/»

NumpadMult — звездочка «*»

NumpadAdd — плюс «+»

NumpadSub — минус «-«

NumpadEnter — клавиша «Numpad-Enter»

Следующие названия клавиш используются, когда Numlock выключен:

NumpadDel

NumpadIns

NumpadClear — та же кнопка, что и Numpad5 на клавиатуре

NumpadUp

NumpadDown

NumpadLeft

NumpadRight

NumpadHome

NumpadEnd

NumpadPgUp

NumpadPgDn

Эти названия клавиш используются при включенном Numlock’e:

Numpad0

Numpad1

Numpad2

Numpad3

Numpad4

Numpad5

Numpad6

Numpad7

Numpad8

Numpad9

NumpadDot — «Numpad-точка»

С F1 по F24 — двенадцать или более функциональных клавиш, на большинстве клавиатур представлены в самом верхнем ряду.

AppsKey — клавиша, вызывающая контекстное меню файла/программы, как при правом клике мышкой.

LWin — левая клавиша «Windows»

RWin — правая клавиша «Windows»

Control (или Ctrl)

Alt

Shift

Примечание: в большинстве случаев работа со следующими шестью клавишами не поддерживается под Windows 95/98/Me. Используйте в этом случае вариант их записи, приведенный выше, вместо следующего:

LControl (или LCtrl) — левый «Сontrol»

RControl (или RCtrl) — правый «Сontrol»

LShift

RShift

LAlt — левый «Alt»

RAlt — правый «Alt». Примечание: если на вашей клавиатуре вместо клавиши RAlt сделана клавиша AltGr, вы можете использовать следующую запись данной клавиши: <^>! Также заметим, что клавишу AltGr можно записать как сочетание клавиш «LControl & RAlt::».

PrintScreen

CtrlBreak

Pause

Break

Help — довольно редкая клавиша, присутствует далеко не на всех клавиатурах. И работает совсем не как F1.

Sleep — предупреждаем, что клавиша «Sleep» на некоторых клавиатурах не работает под этой записью.

Клавиши расширенных функций Мультимедийных и Интернет-клавиатур:

Browser_Back

Browser_Forward

Browser_Refresh

Browser_Stop

Browser_Search

Browser_Favorites

Browser_Home

Volume_Mute

Volume_Down

Volume_Up

Media_Next

Media_Prev

Media_Stop

Media_Play_Pause

Launch_Mail

Launch_Media

Launch_App1

Launch_App2

Запись вида SCnnn, где nnn — это сканкод клавиши, позволяет нам работать с остальными клавишами, не упоминавшимися выше. Подробнее об этом — см. ниже.

Возможна запись VKnn, где nn является шестнадцатиричным виртуальным кодом клавиши. Несмотря на то, что этот редко используемый метод поддерживается всеми версиями программы, только с версии 1.0.38.02 и выше для некоторых типов горячих клавиш реализовано предотвращение отслеживания их функцией «keyboard hook» (обработчик клавиатурных прерываний). Например, следующая комбинация клавиш не использует обработчик клавиатурных прерываний (keyboard hook), и как следствие может быть запущена нажатием как клавиши Home, так и NumpadHome:

^VK24::MsgBox Вы нажали Home или NumpadHome`, удерживая клавишу Control.

Джойстик

Joy1 — Joy32: кнопки джойстика. Для удобства определения номеров кнопок вашего джойстика был создан специальный тест-скрипт (см. ссылку в оригинале статьи). Обратите внимание, что такие префиксы, как ^ (control) и + (shift) здесь не поддерживаются (тем не менее, команда GetKeyState может использоваться). Также обратите внимание, что нажатия клавиш джойстика всегда обращены напрямую в активное окно, поддерживающее приём таких сигналов.

Несмотря на то, что следующие управляющие элементы джойстика не могут использоваться как горячие клавиши, их можно использовать при помощи команды GetKeyState:

JoyX, JoyY, и JoyZ: где X (горизонтальная), Y (вертикальная), и Z (высота/глубина) — оси координат джойстика.

JoyR: руль джойстика или 4-ая ось джойстика.

JoyU и JoyV: 5-ая и 6-ая оси джойстика.

JoyPOV: the point-of-view (hat) control (POV control, «шляпка» или «переключатель видов»; например, вид глазами игрока).

JoyName: название джойстика.

JoyButtons: количество кнопок, поддерживаемых джойстиком (не всегда точное).

JoyAxes: количество направлений, поддерживаемых джойстиком.

JoyInfo: генерирует строку, состоящую из нуля или более знаков, иллюстрирующих возможности джойстика: Z (имеется Z направление), R (имеется R направление), U (имеется U направление), V (имеется V направление), P (имеется POV control), D (POV control имеет ограниченное количество дискретных/промежуточных настроек), C (POV control передает непрерывные/точные данные). Пример строки: ZRUVPD.

Несколько джойстиков: если вы используете несколько джойстиков одновременно, то для более точной адресации команды используйте при записи номер джойстика перед именем клавиши джойстика. Например запись 2joy1 будет обозначать первую кнопку второго джойстика.

Примечание: если у вас возникли проблемы с определением скриптами вашего джойстика, вы можете попробовать изменить номер джойстика с 1 на что-нибудь другое, даже несмотря на то, что к компьютеру у вас подключен всего один. Неизвестно, по каким мистическим причинам, но иногда это вместе с использованием нашего тестового скрипта даёт положительный результат.

Использование джойстика как мыши: специальный скрипт превращает ваш джойстик в мышь (см. ссылку в оригинале статьи).

Дистанционные пульты управления

Получение сигналов от дистанционных пультов управления с помощью специального клиентского скрипта WinLIRC — см. ссылку в оригинале статьи.

Специальные клавиши

Если ваши клавиатура или мышь имеют клавиши, не перечисленные выше, вы всё равно имеете возможность использовать их в качестве горячих клавиш, используя следующий метод (необходимы Windows NT/2000/XP или выше):

1. Вначале убедитесь, что у вас проинсталлирован обработчик клавиатурных прерываний (keyboard hook) — #InstallKeybdHook.

2. Запускаем этот скрипт, и затем двойным кликом по его иконке в системном трее открываем его главное окно.

3. Затем нажимаем ту самую клавишу, которую пытаемся определить.

4. Далее открываем меню окошка скрипта «View — Key history and script info» и прокручиваем записи до самого низа.

5. Где-то внизу этого лога должны быть записи по нажатию-отпусканию нашей искомой клавиши. Сам лог обновляется нажатием клавиши F5. Примечание: если после нажатия искомой клавиши никаких записей в логе не появилось, значит такая клавиша не распознаётся данной программой. В этом случае вы не можете использовать данную клавишу как горячую, т.к. либо драйвер вашей клавиатуры, либо сама её «железная» составляющая даёт сигнал слишком низкого уровня, недоступного для AutoHotkey. В случае со «злобными» драйверами, вы можете попробовать либо перенастроить сами «родные» драйвера, либо заменить их на другие, более дружественые, например такие, как дефолтные клавиатурные драйвера Windows.

6. Если ваша клавиша успешно определилась, обратите внимание на трехзначное шестнадцатеричное число во второй колонке лога (например, 159).

7. Теперь, чтобы использовать данную клавишу как горячую, следуйте данному примеру:

SC159:: ; Замените 159 на индекс вашей клавиши.

MsgBox, Вы нажали клавишу %A_ThisHotKey%

Return

Как альтернативный способ или в добавление к описанному выше: для переназначения какой-либо клавиши в нашу «искомую» клавишу, используйте запись вида #c::Send {vkFFsc159}. Замените 159 на индекс вашей клавиши, определённый вышеописанным методом. При необходимости замените буквы FF на те, что отображены в первой колонке лога «View-Key history» (код вашей виртуальной клавиши).

© Dmitrij_Medvedev

Send / SendRaw / SendInput / SendPlay / SendEvent: Send Keys & Clicks

Sends simulated keystrokes and mouse clicks to the active window.

Send Keys
SendRaw Keys
SendInput Keys
SendPlay Keys
SendEvent Keys

Parameters

Keys

The sequence of keys to send. As with other commands, the comma in front of the first parameter is optional.

Raw modeSendRaw or {Raw}: The characters ^+!#{} are interpreted literally rather than translating {Enter} to an ENTER keystroke, ^c to Control-C, etc. To use raw mode with SendInput, SendPlay, SendEvent, or ControlSend, write {Raw} as the first item in the string; for example: SendInput {Raw}abc.

Raw mode does not affect the interpretation of escape sequences, variable references and expressions. For example, SendRaw, ``100`% sends the string `100%. When using ControlSend, it is also necessary to escape literal commas (`,).

Text mode{Text} [v1.1.27+]: Similar to 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. Text mode can be combined with Blind mode to avoid releasing any modifier keys: Send {Blind}{Text}your text. However, some applications require that the modifier keys be released.

`n, `r and `r`n are all translated to a single Enter keystroke, unlike normal mode and Raw mode, which translate `r`n to two Enter keystrokes. `t is translated to Tab and `b to Backspace, but all other characters are sent without translation.

Normal mode: When not in Raw mode or Text mode, the following symbols have special meaning: !+^#{}

The modifiers !+^# affect only the very next key. To send the corresponding modifier key on its own, enclose the key name in braces. To just press (hold down) or release the key, follow the key name with the word «down» or «up» as shown below.

Symbol Key Press Release Examples
! {Alt} {Alt down} {Alt up} Send !a presses ALT+a
+ {Shift} {Shift down} {Shift up} Send +abC sends the text «AbC»
Send !+a presses ALT+SHIFT+a
^ {Ctrl} {Ctrl down} {Ctrl up} Send ^{Home} presses CONTROL+HOME
# {LWin}
{RWin}
{LWin down}
{RWin down}
{LWin up}
{RWin up}
Send #e holds down the Windows key and then presses the letter «e»
Symbol Meaning
{ }

Braces are used to enclose key names and other options, and to send special characters literally. For example, {Tab} is the Tab key and {!} is a literal exclamation mark.

[v1.1.27+]: 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.

Note: As capital letters are produced by sending the SHIFT key, 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.

SendInput and SendPlay [v1.0.43+]: SendInput and SendPlay use the same syntax as Send but are generally faster and more reliable. In addition, they buffer 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 or SendPlay. For more details about each mode, see SendInput and SendPlay below.

SendEvent [v1.0.43+]: SendEvent sends keystrokes using the same method as the pre-1.0.43 Send command. The rate at which keystrokes are sent is determined by SetKeyDelay. By default, Send is synonymous SendEvent; but it can be made a synonym for SendInput or SendPlay via SendMode.

Key Names: The following table lists the special keys that can be sent (each key name must be enclosed in braces):

   
{F1} — {F24} Function keys. For example: {F12} is the F12 key.
{!} !
{#} #
{+} +
{^} ^
{{} {
{}} }
{Enter} ENTER key on the main keyboard
{Escape} or {Esc} ESCAPE
{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} Delete
{Insert} or {Ins} Insert
{Up} Up-arrow key on main keyboard
{Down} Down-arrow down key on main keyboard
{Left} Left-arrow key on main keyboard
{Right} Right-arrow key on main keyboard
{Home} Home key on main keyboard
{End} End key on main keyboard
{PgUp} Page-up key on main keyboard
{PgDn} Page-down key on main keyboard
   
{CapsLock} CapsLock (using SetCapsLockState is more reliable on Win 2k/XP).
Sending {CapsLock} might require SetStoreCapslockMode Off beforehand.
{ScrollLock} ScrollLock (see also: SetScrollLockState)
{NumLock} NumLock (see also: SetNumLockState)
   
{Control} or {Ctrl} CONTROL (technical info: sends the neutral virtual key but the left scan code)
{LControl} or {LCtrl} Left CONTROL key (technical info: sends the left virtual key rather than the neutral one)
{RControl} or {RCtrl} Right CONTROL key
{Control Down} or {Ctrl Down} Holds the CONTROL key down until {Ctrl Up} is sent. To hold down the left or right key instead, use {RCtrl Down} and {RCtrl Up}.
   
{Alt} ALT (technical info: sends the neutral virtual key but the left scan code)
{LAlt} Left ALT key (technical info: sends the left virtual key rather than the neutral one)
{RAlt} Right ALT key (or AltGr, depending on keyboard layout)
{Alt Down} Holds the ALT key down until {Alt Up} is sent. To hold down the left or right key instead, use {RAlt Down} and {RAlt Up}.
   
{Shift} SHIFT (technical info: sends the neutral virtual key but the left scan code)
{LShift} Left SHIFT key (technical info: sends the left virtual key rather than the neutral one)
{RShift} Right SHIFT key
{Shift Down} Holds the SHIFT key down until {Shift Up} is sent. To hold down the left or right key instead, use {RShift Down} and {RShift Up}.
   
{LWin} Left Windows key
{RWin} Right Windows key
{LWin Down} Holds the left Windows key down until {LWin Up} is sent
{RWin Down} Holds the right Windows key down until {RWin Up} is sent
   
{AppsKey} Windows App key (invokes the right-click or context menu)
{Sleep} Computer SLEEP key.
{ASC nnnnn}

Sends an ALT+nnnnn keypad combination, which can be used to generate special characters that don’t exist on the keyboard. To generate ASCII characters, specify a number between 1 and 255. To generate ANSI characters (standard in most languages), specify a number between 128 and 255, but precede it with a leading zero, e.g. {Asc 0133}.

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}

[AHK_L 24+]: Sends a Unicode character where nnnn is the hexadecimal value of the character excluding the 0x prefix. This typically isn’t needed in Unicode versions of AutoHotkey, where Send and ControlSend automatically support Unicode text.

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

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

Warning: Combining vk and sc in this manner is valid only with Send. Prior to [v1.1.27], hotkeys permitted but ignored any non-hexadecimal characters following XX.

   
{Numpad0} — {Numpad9} Numpad digit keys (as seen when Numlock is ON). For example: {Numpad5} is the digit 5.
{NumpadDot} Numpad Period (as seen when Numlock is ON).
{NumpadEnter} Enter key on keypad
{NumpadMult} Numpad Multiply
{NumpadDiv} Numpad Divide
{NumpadAdd} Numpad Add
{NumpadSub} Numpad Subtract
   
{NumpadDel} Delete key on keypad (this key and the following Numpad keys are used when Numlock is OFF)
{NumpadIns} Insert key on keypad
{NumpadClear} Clear key on keypad (usually the ‘5’ key when Numlock is OFF).
{NumpadUp} Up-arrow key on keypad
{NumpadDown} Down-arrow key on keypad
{NumpadLeft} Left-arrow key on keypad
{NumpadRight} Right-arrow key on keypad
{NumpadHome} Home key on keypad
{NumpadEnd} End key on keypad
{NumpadPgUp} Page-up key on keypad
{NumpadPgDn} Page-down key 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 SoundSet, +1, , mute.
{Volume_Down} Reduce the master volume. Usually equivalent to SoundSet -5.
{Volume_Up} Increase the master volume. Usually equivalent to SoundSet +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} Print Screen
{CtrlBreak} Ctrl+break
{Pause} Pause
   
{Click [Options]}
[v1.0.43+]
Sends a mouse click using the same options available in the Click command. For example, {Click} would click the left mouse button once at the mouse cursor’s current position, and {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: {Click 100, 200, 0}. The delay between mouse clicks is determined by SetMouseDelay (not SetKeyDelay).
{WheelDown}, {WheelUp}, {WheelLeft}, {WheelRight}, {LButton}, {RButton}, {MButton}, {XButton1}, {XButton2} 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. WheelLeft/Right require [v1.0.48+], but have no effect on operating systems older than Windows Vista.
{Blind}

When {Blind} is the first item in the string, the program avoids releasing Alt/Control/Shift/Win if they started out in the down position. For example, the hotkey +s::Send {Blind}abc would send ABC rather than abc because the user is holding down the Shift key.

{Blind} also causes SetStoreCapslockMode to be ignored; that is, the state of Capslock is not changed. Finally, {Blind} omits the extra Control keystrokes that would otherwise be sent; such keystrokes prevent: 1) Start Menu appearance during LWin/RWin keystrokes; 2) menu bar activation during Alt keystrokes.

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) Control-B when you type Control-A.

{Blind} is not supported by SendRaw and ControlSendRaw. Furthermore, it is not completely supported by SendPlay, especially when dealing with the modifier keys (Control, Alt, Shift, and Win).

{Raw}
[v1.0.43+]
Enables Raw mode, which causes the following characters to be interpreted literally: ^+!#{}. Although the string {Raw} need not occur at the beginning of the string, once specified, it stays in effect for the remainder of the string.
{Text}
[v1.1.27+]
Enables Text mode, which sends a stream of characters rather than keystrokes. Like Raw mode, Text mode causes the following characters to be interpreted literally: ^+!#{}. Although the string {Text} need not occur at the beginning of the string, once specified, it stays in effect for the remainder of the string.

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, 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 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 modifer 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, Send {Control DownTemp} followed later by Send a 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.

[v1.1.27+]: 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 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, Send {µ up} has no effect on most layouts, and Send {µ down} is equivalent to Send µ.

Characters vs. keys: By default, characters are sent by first translating them to keystrokes. If this translation is not possible (that is, if the current keyboard layout does not contain a key or key combination which produces that character), the character is sent by one of following fallback methods:

  • SendEvent and SendInput use SendInput() with the KEYEVENTF_UNICODE flag. [v1.1.27+]: 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 Alt+nnnnn 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.

[v1.1.27+]: 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 Raw mode is in effect, it is sent as a character. For example, Send {Raw}Regards sends the expected text, even though pressing the «r» key (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.
  • 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, ^c and {Ctrl down}c{Ctrl up} activate the standard Ctrl+C shortcut and {c} is equivalent to {vk43}.

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

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

When sending a large number of keystrokes, a continuation section 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 Send ^!{Delete} 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.

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 SendEvent under the conditions described below, it uses SetKeyDelay -1, 0 (unless SendEvent’s KeyDelay is -1,-1, in which case -1,-1 is used). When SendInput reverts to SendPlay, it uses SendPlay’s KeyDelay.

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

When SendInput sends mouse clicks by means such as {Click}, and CoordMode Mouse, Relative 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.

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

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.

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

Although SendPlay is considerably slower than SendInput, it is usually faster than the traditional SendEvent mode (even when KeyDelay is -1).

The Windows keys (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 a Windows key 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 the Capslock, Numlock, or Scroll-lock keys. 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.

Unlike SendInput and SendEvent, the user may interrupt a SendPlay by pressing Control-Alt-Del or Control-Escape. 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 SendEvent. For example, SendEvent #r would show the Start Menu’s Run dialog.

Related

SendMode, SetKeyDelay, SetStoreCapslockMode, Escape sequences (e.g. `%), ControlSend, BlockInput, Hotstrings, WinActivate

Examples

Send Sincerely,{enter}John Smith  ; Types a two-line signature.
Send !fs ; Select the File->Save menu (Alt+F followed by S).
Send {End}+{Left 4} ; Jump to the end of the text then send four shift+left-arrow keystrokes.
SendInput {Raw}A long series of raw characters sent via the fastest method (SendInput).


Download Article


Download Article

  • Installing AutoHotkey
  • |

  • Creating a Script
  • |

  • Creating a Hotkey
  • |

  • Creating a Hotstring
  • |

  • Launching Apps or Websites

This wikiHow teaches you how to use AutoHotkey on a Windows computer. AutoHotkey is a free Windows scripting language that allows you to program different actions with various keyboard shortcuts. The following steps will show you how to install AutoHotkey as well as program a few basic scripts to enter text, run programs, and open websites using simple keyboard shortcuts.

  1. Image titled 9830772 1

    1

    Go to https://autohotkey.com in a web browser. Using your preferred web browser, go to official AutoHotkey website.

  2. Image titled 9830772 2

    2

    Click Download. It’s the green button in the center of the page.

    Advertisement

  3. Image titled 9830772 3

    3

    Click Download AutoHotkey Installer. It’s the blue button at the top of the page. This will start the download of the AutoHotkey installer.

  4. Image titled 9830772 4

    4

    Run the installation file. Double-click the installation file you just downloaded to start the installer.

    • By default, all your downloaded files can be found in your Downloads folder.
  5. Image titled 9830772 5

    5

    Click Express Installation. It’s the first option in the AutoHotkey Setup wizard. This will install AutoHotkey on your computer with the default configuration.

    • When it’s finished installing you can click «Run AutoHotkey» to launch some of the documentation about AutoHotkey.
  6. Advertisement

  1. Image titled 9830772 6

    1

    Right-click your desktop. When you right-click on any blank part of your desktop, this opens a drop-down menu.

  2. Image titled 9830772 7

    2

    Hover the mouse over New. When you place the mouse cursor over «New» you will see a list of programs you can create a new file for.

  3. Image titled 9830772 8

    3

    Click AutoHotkey Script. This will create a new AutoHotkey script on your desktop. It will have an image of a white page with a red «H» on it.

  4. Image titled 9830772 9

    4

    Rename the AutoHotkey file. By default, the new document will be named «NewAutoHotkeyScript.ahk» and it will be highlighted, allowing you type a new name for your script.

    • Be sure not to erase the file extension of «.ahk» at the end. Your file must end with the «.ahk» file extension or else it won’t work with AutoHotkey.
  5. Image titled 9830772 10

    5

    Right-click your new script. This will open a drop-down menu with additional options for the file.

  6. Image titled 9830772 11

    6

    Click Edit Script. It’s the third option from the top. This will launch the AutoHotkey script in Notepad. This is where you will write the programming to create your first AutoHotkey script.

    • There is some code and text already inserted into the first few lines of every new AHK script, you can ignore this and leave it alone for now.
  7. Advertisement

  1. Image titled 9830772 12

    1

    On a new line, type the code for the keyboard shortcut you want to assign. For example, if you want to assign a command that does something when you press the key combination of Ctrl+E, you would type ^e. Each lowercase letter represents its own key, while special keys have their own symbols:

    • + = Shift
    • ^ = Ctrl
    • ! = Alt
    • # = Win (Windows key)
    • Click here for a complete list of key commands.
  2. Image titled 9830772 13

    2

    Type two colons after the keys you assigned. Any key or key combination you typed needs to be followed by ::. So in our example, the first line of our code would look like:

    • Image titled 9830772 14

      3

      Press Enter to go to the next line and press Tab to indent. You’ll type the command for what will happen with then hotkey is pressed on the line below the two colons. You can indent the line by pressing «Tab» or by typing several spaces

      • You don’t have to indent the command line but it will keep your code organized and easy to read if you have errors later.
    • Image titled 9830772 15

      4

      Type Send, and then type a message. The Send command will automatically type a message when a Hotkey is triggered. Anything you type after the comma will be typed automatically when you press the assigned Hotkey. For our example, if you wanted to include the message «wikiHow is awesome!» your code would look like:

        ^e::
            Send, wikiHow is awesome{!}
        
      • Special characters, like the exclamation mark, must be enclosed in braces { } so it isn’t confused with the symbol for the «Alt» key.
    • Image titled 9830772 16

      5

      Press Enter to go the next line and type Return. The Return command denotes the end of a command and stops the code from going to the lines below.[1]
      Your finished code should look like:

        ^e::
            Send, wikiHow is awesome{!}
        Return
        
    • Image titled 9830772 17

      6

      Save your script. Click «File» in the menu bar at the top of Notepad and click «Save» in the drop-down menu. This will save the code you’ve added to the script file.

      • You can close Notepad once your work has been saved.
    • Image titled 9830772 18

      7

      Run the script. Double-click the script file on your desktop to run the script. You’ll see a green AutoHotkey icon appear in your system tray on the bottom-right of your screen. This indicates that an AutoHotkey script is active.

    • Image titled 9830772 19

      8

      Test your Hotkey. Open a new word processing app or any app you can type text and press your Hotkey combo. In our example, if you press Ctrl+E you’ll see the text «wikiHow is awesome!» instantly appear.

    • Advertisement

    1. Image titled 9830772 20

      1

      Open your script or create a new one. You can open the script you were working on earlier and add a new command to it or create a new script from scratch.

      • Right-click the script and select «Edit Script» to edit the previous script.
      • Right-click the desktop and go to «New,» then select «Auto Hotkey Script.»
    2. Image titled 9830772 21

      2

      Go to a new line and type two colons. A Hotstring command starts with :: at the beginning.

      • A Hotstring can take a word or phrase you type and replace it with a different word or phrase.
    3. Image titled 9830772 22

      3

      Type the letters, word, or phrase you want to replace. For example, you can create a Hotstring so that every time you type the acronym «btw» it would automatically change it to «By the way,» so you didn’t have to type it all out. In that example, so far your code would look like:

      • Image titled 9830772 23

        4

        Type two more colons again. This will separate the end of the message you want to replace from the words or you want to replace it with. Using our example, the code would look like:

        • Image titled 9830772 24

          5

          Type the message you want to replace it with. The message you type after the second pair of colons will automatically replace the first message in between the two sets of colons. In our example, the code would look like:

          • Hotstrings don’t need a «Return» command and the end because they are self-contained on one line of a script
        • Image titled 9830772 25

          6

          Save and run the script to test it out. Just like before, save your work by clicking «File» and «Save»—then double-click the script to run it. Then open any app or program you can type in to test it out. When you type the letters «btw» onto any page, it should immediately be replaced with «By the way,» in the text field.

        • Advertisement

        1. Image titled 9830772 26

          1

          Open your script or create a new one. You can open the script you were working on earlier and add a new command to it or create a new script from scratch.

          • Right-click the script and select «Edit Script» to edit the previous script.
          • Right-click the desktop and go to «New,» then select «Auto Hotkey Script.»
        2. Image titled 9830772 27

          2

          On a new line, type the code for the Hotkeys you want to assign. For example, if you wanted to open the wikiHow website whenever you pressed they keys Wind+W, you would type the code #w because «#» is the symbol for the Windows key and «w» is the code for the W key. In that example, the code would look like:

          • Click here for a complete list of key symbols if you want to use a different key combination for your Hotkey.
        3. Image titled 9830772 28

          3

          Type the two colons, then go to the next line and indent. Immediately after typing the code for the keyboard shortcut, type two colons :: and then press Enter to go to the next line. Indent the line using several spaces or the Tab key.

          • You don’t have to indent the command line but it will keep your code organized and easy to read if you have errors later.
        4. Image titled 9830772 29

          4

          Type Run,. The Run command can be used to launch any program, application or website. Type Run, with the comma at the end and Auto Hotkey will look for the name or location of any program or website listed after the comma. In our example, the code so far would look like:

        5. Image titled 9830772 30

          5

          Type the full location of any program on your computer or type any website’s full URL. For example, if you wanted your Hotkey to launch Internet Explorer, you would type C:Program Filesinternet exploreriexplore.exe after the Run command. In our example, since we want to launch the wikiHow website, our code would look like:

          #w::
              Run, https://wikihow.com
          
        6. Image titled 9830772 31

          6

          Press Enter to go the next line and type Return. The Return command denotes the end of a command and stops the code from going to the lines below. In our example. your finished code should look like:

          #w::
              Run, https://wikihow.com
          Return
          
        7. Image titled 9830772 32

          7

          Save and run the script to test it out. Just like before, save your work by clicking «File» and «Save»—then double-click the script to run it. If you followed our example, whenever you press the key combination of Win+W, the wikiHow website will open in your default browser!

        8. Advertisement

        Ask a Question

        200 characters left

        Include your email address to get a message when this question is answered.

        Submit

        Advertisement

        Thanks for submitting a tip for review!

        References

        About This Article

        Article SummaryX

        1. Install AutoHotkey from https://www.autohotkey.com.
        2. Right-click the desktop and click New.
        3. Click AutoHotkey Script.
        4. Right-click the script icon and select Edit Script.

        5. Enter the code for the keyboard shortcut followed by two colons.
        6. Press Enter.
        7. Type «Send» followed by the word(s) or command.
        8. Press Enter.
        9. Type «Return» and save the file.
        10. Double-click the script to run it.

        Did this summary help you?

        Thanks to all authors for creating a page that has been read 51,050 times.

        Is this article up to date?


        Download Article


        Download Article

        • Installing AutoHotkey
        • |

        • Creating a Script
        • |

        • Creating a Hotkey
        • |

        • Creating a Hotstring
        • |

        • Launching Apps or Websites

        This wikiHow teaches you how to use AutoHotkey on a Windows computer. AutoHotkey is a free Windows scripting language that allows you to program different actions with various keyboard shortcuts. The following steps will show you how to install AutoHotkey as well as program a few basic scripts to enter text, run programs, and open websites using simple keyboard shortcuts.

        1. Image titled 9830772 1

          1

          Go to https://autohotkey.com in a web browser. Using your preferred web browser, go to official AutoHotkey website.

        2. Image titled 9830772 2

          2

          Click Download. It’s the green button in the center of the page.

          Advertisement

        3. Image titled 9830772 3

          3

          Click Download AutoHotkey Installer. It’s the blue button at the top of the page. This will start the download of the AutoHotkey installer.

        4. Image titled 9830772 4

          4

          Run the installation file. Double-click the installation file you just downloaded to start the installer.

          • By default, all your downloaded files can be found in your Downloads folder.
        5. Image titled 9830772 5

          5

          Click Express Installation. It’s the first option in the AutoHotkey Setup wizard. This will install AutoHotkey on your computer with the default configuration.

          • When it’s finished installing you can click «Run AutoHotkey» to launch some of the documentation about AutoHotkey.
        6. Advertisement

        1. Image titled 9830772 6

          1

          Right-click your desktop. When you right-click on any blank part of your desktop, this opens a drop-down menu.

        2. Image titled 9830772 7

          2

          Hover the mouse over New. When you place the mouse cursor over «New» you will see a list of programs you can create a new file for.

        3. Image titled 9830772 8

          3

          Click AutoHotkey Script. This will create a new AutoHotkey script on your desktop. It will have an image of a white page with a red «H» on it.

        4. Image titled 9830772 9

          4

          Rename the AutoHotkey file. By default, the new document will be named «NewAutoHotkeyScript.ahk» and it will be highlighted, allowing you type a new name for your script.

          • Be sure not to erase the file extension of «.ahk» at the end. Your file must end with the «.ahk» file extension or else it won’t work with AutoHotkey.
        5. Image titled 9830772 10

          5

          Right-click your new script. This will open a drop-down menu with additional options for the file.

        6. Image titled 9830772 11

          6

          Click Edit Script. It’s the third option from the top. This will launch the AutoHotkey script in Notepad. This is where you will write the programming to create your first AutoHotkey script.

          • There is some code and text already inserted into the first few lines of every new AHK script, you can ignore this and leave it alone for now.
        7. Advertisement

        1. Image titled 9830772 12

          1

          On a new line, type the code for the keyboard shortcut you want to assign. For example, if you want to assign a command that does something when you press the key combination of Ctrl+E, you would type ^e. Each lowercase letter represents its own key, while special keys have their own symbols:

          • + = Shift
          • ^ = Ctrl
          • ! = Alt
          • # = Win (Windows key)
          • Click here for a complete list of key commands.
        2. Image titled 9830772 13

          2

          Type two colons after the keys you assigned. Any key or key combination you typed needs to be followed by ::. So in our example, the first line of our code would look like:

          • Image titled 9830772 14

            3

            Press Enter to go to the next line and press Tab to indent. You’ll type the command for what will happen with then hotkey is pressed on the line below the two colons. You can indent the line by pressing «Tab» or by typing several spaces

            • You don’t have to indent the command line but it will keep your code organized and easy to read if you have errors later.
          • Image titled 9830772 15

            4

            Type Send, and then type a message. The Send command will automatically type a message when a Hotkey is triggered. Anything you type after the comma will be typed automatically when you press the assigned Hotkey. For our example, if you wanted to include the message «wikiHow is awesome!» your code would look like:

              ^e::
                  Send, wikiHow is awesome{!}
              
            • Special characters, like the exclamation mark, must be enclosed in braces { } so it isn’t confused with the symbol for the «Alt» key.
          • Image titled 9830772 16

            5

            Press Enter to go the next line and type Return. The Return command denotes the end of a command and stops the code from going to the lines below.[1]
            Your finished code should look like:

              ^e::
                  Send, wikiHow is awesome{!}
              Return
              
          • Image titled 9830772 17

            6

            Save your script. Click «File» in the menu bar at the top of Notepad and click «Save» in the drop-down menu. This will save the code you’ve added to the script file.

            • You can close Notepad once your work has been saved.
          • Image titled 9830772 18

            7

            Run the script. Double-click the script file on your desktop to run the script. You’ll see a green AutoHotkey icon appear in your system tray on the bottom-right of your screen. This indicates that an AutoHotkey script is active.

          • Image titled 9830772 19

            8

            Test your Hotkey. Open a new word processing app or any app you can type text and press your Hotkey combo. In our example, if you press Ctrl+E you’ll see the text «wikiHow is awesome!» instantly appear.

          • Advertisement

          1. Image titled 9830772 20

            1

            Open your script or create a new one. You can open the script you were working on earlier and add a new command to it or create a new script from scratch.

            • Right-click the script and select «Edit Script» to edit the previous script.
            • Right-click the desktop and go to «New,» then select «Auto Hotkey Script.»
          2. Image titled 9830772 21

            2

            Go to a new line and type two colons. A Hotstring command starts with :: at the beginning.

            • A Hotstring can take a word or phrase you type and replace it with a different word or phrase.
          3. Image titled 9830772 22

            3

            Type the letters, word, or phrase you want to replace. For example, you can create a Hotstring so that every time you type the acronym «btw» it would automatically change it to «By the way,» so you didn’t have to type it all out. In that example, so far your code would look like:

            • Image titled 9830772 23

              4

              Type two more colons again. This will separate the end of the message you want to replace from the words or you want to replace it with. Using our example, the code would look like:

              • Image titled 9830772 24

                5

                Type the message you want to replace it with. The message you type after the second pair of colons will automatically replace the first message in between the two sets of colons. In our example, the code would look like:

                • Hotstrings don’t need a «Return» command and the end because they are self-contained on one line of a script
              • Image titled 9830772 25

                6

                Save and run the script to test it out. Just like before, save your work by clicking «File» and «Save»—then double-click the script to run it. Then open any app or program you can type in to test it out. When you type the letters «btw» onto any page, it should immediately be replaced with «By the way,» in the text field.

              • Advertisement

              1. Image titled 9830772 26

                1

                Open your script or create a new one. You can open the script you were working on earlier and add a new command to it or create a new script from scratch.

                • Right-click the script and select «Edit Script» to edit the previous script.
                • Right-click the desktop and go to «New,» then select «Auto Hotkey Script.»
              2. Image titled 9830772 27

                2

                On a new line, type the code for the Hotkeys you want to assign. For example, if you wanted to open the wikiHow website whenever you pressed they keys Wind+W, you would type the code #w because «#» is the symbol for the Windows key and «w» is the code for the W key. In that example, the code would look like:

                • Click here for a complete list of key symbols if you want to use a different key combination for your Hotkey.
              3. Image titled 9830772 28

                3

                Type the two colons, then go to the next line and indent. Immediately after typing the code for the keyboard shortcut, type two colons :: and then press Enter to go to the next line. Indent the line using several spaces or the Tab key.

                • You don’t have to indent the command line but it will keep your code organized and easy to read if you have errors later.
              4. Image titled 9830772 29

                4

                Type Run,. The Run command can be used to launch any program, application or website. Type Run, with the comma at the end and Auto Hotkey will look for the name or location of any program or website listed after the comma. In our example, the code so far would look like:

              5. Image titled 9830772 30

                5

                Type the full location of any program on your computer or type any website’s full URL. For example, if you wanted your Hotkey to launch Internet Explorer, you would type C:Program Filesinternet exploreriexplore.exe after the Run command. In our example, since we want to launch the wikiHow website, our code would look like:

                #w::
                    Run, https://wikihow.com
                
              6. Image titled 9830772 31

                6

                Press Enter to go the next line and type Return. The Return command denotes the end of a command and stops the code from going to the lines below. In our example. your finished code should look like:

                #w::
                    Run, https://wikihow.com
                Return
                
              7. Image titled 9830772 32

                7

                Save and run the script to test it out. Just like before, save your work by clicking «File» and «Save»—then double-click the script to run it. If you followed our example, whenever you press the key combination of Win+W, the wikiHow website will open in your default browser!

              8. Advertisement

              Ask a Question

              200 characters left

              Include your email address to get a message when this question is answered.

              Submit

              Advertisement

              Thanks for submitting a tip for review!

              References

              About This Article

              Article SummaryX

              1. Install AutoHotkey from https://www.autohotkey.com.
              2. Right-click the desktop and click New.
              3. Click AutoHotkey Script.
              4. Right-click the script icon and select Edit Script.

              5. Enter the code for the keyboard shortcut followed by two colons.
              6. Press Enter.
              7. Type «Send» followed by the word(s) or command.
              8. Press Enter.
              9. Type «Return» and save the file.
              10. Double-click the script to run it.

              Did this summary help you?

              Thanks to all authors for creating a page that has been read 51,050 times.

              Is this article up to date?

              First we’ll cover the basic Autohotkey hotkey syntax. Which is arguably already pretty confusing for
              newcomers in and by itself.

              But we don’t stop there as after adding more and more hotkeys, it will also become harder and harder
              to think of new key combinations that are somehow still memorable. There is only so much
              you can do with the # (Windows) key etc.

              Time for some creative hotkey combinations! ‘Advanced Hotkeys’ covers code snippets on
              how to run different scripts on single, double or triple key presses as well as how to
              differentiate between long(ish) key presses or mouse clicks. And more…

              Example

              ; Single line hotkey
              ^#D::MsgBox Pressed Control + Win + D (%A_ThisHotKey%)
              
              ; Control + Win + C: Multi line script
              ^#C::
              Run, notepad.exe
              WinWait, Untitled - Notepad, , 3
              Send, Dear sir,{enter}{enter}
              Return
              

              Basic Syntax

              Keyboard

              Shorthand Full Desc
              + Shift  
              ^ Control or Ctrl  
              # Win Windows
              ! Alt  
              <# LWin Left Windows
              +> RShift Right Shift
              <^>! AltGr  
                AppsKey Menu key
                CapsLock  

              Others:

              • F[1-24], Tab, Space, Enter/Return, Backspace/BS
              • Left, Up, Down, Right
              • Esc, Ins, Delete/Del, Home, End, PgUp, PgDn
              • PrintScreen, ScrollLock, CtrlBreak
              • Sleep, Pause

              Numpad:

              • Numlock ON: Numpad[0-9],
              • Numlock OFF: NumpadIns, NumpadEnd, NumpadMult, NumpadEnter, …

              Multimedia:

              • Browser_Stop, Media_Next, Volume_Up, Launch_App2, …

              Mouse:

              • LButton, RButton, MButton
              • XButton1 (Browser_Back), XButton2 (Browser_Forward)
              • WheelUp, WheelDown, WheelLeft, WheelRight

              Joystick:

              • JoyX, JoyPOV, JoyInfo, …

              JoystickTest: A simple script
              for determining the exact mapping of your joystick.

              Find the full KeyList here.
              If your keyboard has keys that are not in the full keylist,
              it might still be possible to map them to a script.

              You can also let Autohotkey itself do the figuring out for you. Its builtin command
              KeyHistory opens a window where you can figure out which is which.

              Native function

              Prefix a hotkey with ~ to not block the native function.

              #IfWinActive, ahk_class CabinetWClass
              ; Control + Shift + 6: Details View in Windows Explorer
              ; Resize columns so that filenames are completely visible
              ~^+6::Send, {Control Down}{NumpadAdd}{Control Up}
              #IfWinActive
              

              Custom combinations

              To combine keys that do not have a shorthand use &.
              Keys on the left side of such custom combinations lose their native function.
              They are called prefix keys.

              Example: Search google for text on the clipboard by pressing Capslock and X.

              Capslock & X::Run, http://www.google.com/search?q=%clipboard%
              

              Other

              Key Down and Up
              Add UP to a hotkey combination to run the script on key release rather than on keypress.

              AppsKey::ToolTip Press < or > to cycle through tabs.
              AppsKey Up::ToolTip
              ~AppsKey & <::Send ^+{tab}
              ~AppsKey & >::Send ^{tab}
              

              Wildcard
              * acts as a key modifier wildcard.

              *#c::Msgbox Triggered by Win+C, Shift+Win+C, Ctrl+Win+C, etc
              

              Resending
              $ is necessary when you need to send the same hotkey and not execute your script again.

              $#e::
              ; Send Control + C => Copy text
              Send, ^c
              ClipWait, 1
              fileExists := FileExist(clipboard)
              if (fileExists = "D") {
                  ; Open explorer in path on clipboard
                  Run % "explorer.exe /root," clipboard
              
              } else if (fileExists) {
                  ; Open explorer with file selected
                  Run % "explorer.exe /select," clipboard
              
              } else {
                  ; No path on clipboard, just open explorer
                  Send #e
              }
              Return
              

              Advanced Hotkeys

              Creating more advanced hotkey combinations.

              Context sensitive hotkeys

              Control in which applications a hotkey is (not) active with the
              keywords
              IfWinActive,
              IfWinExist, IfWinNotActive and IfWinNotExist.

              #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") and true
              WheelUp::Send {Volume_Up}     ; Wheel over taskbar: increase/decrease volume.
              WheelDown::Send {Volume_Down} ;
              
              MouseIsOver(WinTitle) {
                  MouseGetPos,,, Win
                  return WinExist(WinTitle . " ahk_id " . Win)
              }
              #If
              
              
              $^p::
              IfWinActive ahk_class Notepad
                  return  ; i.e. do nothing, which causes Control-P to do nothing in Notepad.
              
              Send ^p
              return
              

              Find out the ahk_class of a program with Window Spy (AU3_Spy.exe)
              which comes bundled with Autohotkey itself.

              Combining 2 hotkeys

              Check if a hotkey combination is pressed twice

              ~Esc::
              ; Esc twice to close an application
              If (A_PriorHotKey = A_ThisHotKey and A_TimeSincePriorHotkey < 500)
                  WinClose
              Return
              

              Gotcha: the A_PriorHotkey will only hold values of combinations that are also defined
              as a hotkey. The value of A_PriorHotkey will be exactly as the hotkey is defined.

              Follow a hotkey up with an additional keypress

              ; AltGr + C: Change the case of the selected text
              ; Follow up with (U)PPER, l(ower) or T(itle)
              <^>!c::
              clipboard =
              Send, ^c
              ClipWait, 1
              Input keyPressed, I L1
              if (keyPressed = "u") {
                  StringUpper toUpperCase, clipboard
                  Send %toUpperCase%
              } else if (keyPressed = "l") {
                  StringLower toLowerCase, clipboard
                  Send %toLowerCase%
              } else if (keyPressed = "p" or keyPressed = "t") {
                  StringUpper toTitleCase, clipboard, T
                  Send %toTitleCase%
              }
              return
              

              Input option L1 is the maximum allowed length. (L1 -> L5)

              Double, triple and long key presses

              #c::
              DoubleClickTime := DllCall("GetDoubleClickTime") ; in milliseconds
              
              ; Wait for 'c' to be released
              KeyWait, c
              if (A_TimeSinceThisHotkey > DoubleClickTime) {
                  Msgbox Longpress
                  return
              }
              
              ; Wait for 'c' to be pressed down again (option "d")
              ; But timeout after T0.5 seconds (If DoubleClickTime is 500)
              KeyWait, c, % "d T"DoubleClickTime/1000
              If ! Errorlevel
                  Msgbox Doublepress
              else
                  Msgbox Singlepress
              Return
              

              KeyWait docs
              or more info on the forum.

              Long middle mouse click with GetKeyState

              ~MButton::
              HowLong = 0
              Loop
              {
                  HowLong++
                  Sleep, 10
                  GetKeyState, MButton, MButton, P
                  IfEqual, MButton, U, Break
              }
              IfLess, HowLong, 20, Return
              
              ; Do stuff when middle mouse button was pressed longer than 20ms
              

              Triple, quadruple etc keypresses

              ; Example #3: Detection of 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:
              #j::
              if winc_presses > 0 ; SetTimer already started, so we log the keypress instead.
              {
                  winc_presses += 1
                  return
              }
              ; Otherwise, this is the first press of a new series. Set count to 1 and start
              ; the timer:
              winc_presses = 1
              SetTimer, KeyWinC, -400 ; Wait for more presses within a 400 millisecond window.
              return
              
              KeyWinC:
              if winc_presses = 1 ; The key was pressed once.
              {
                  Run, c:  ; Open a folder.
              }
              else if winc_presses = 2 ; The key was pressed twice.
              {
                  Run, c:windows  ; Open a different folder.
              }
              else if winc_presses > 2
              {
                  MsgBox, Three or more clicks detected.
              }
              ; Regardless of which action above was triggered, reset the count to
              ; prepare for the next series of presses:
              winc_presses = 0
              return
              

              Morse hotkeys

              The forum thread on hold patterns.

              Morse(timeout = 400) {
                 tout := timeout/1000
                 key := RegExReplace(A_ThisHotKey,"[*~$#+!^]")
                 Loop {
                    t := A_TickCount
                    KeyWait %key%
                    Pattern .= A_TickCount-t > timeout
                    KeyWait %key%,DT%tout%
                    If (ErrorLevel)
                       Return Pattern
                 }
              }
              
              ; Use Backspace
              BS::MsgBox % "Morse press pattern " Morse()
              
              ; Alt + Z
              !z::
              p := Morse()
              If (p = "0")
                MsgBox Short press
              Else If (p = "00")
                MsgBox Two short presses
              Else If (p = "01")
                MsgBox Short+Long press
              Else
                MsgBox Press pattern %p%
              Return
              

              Other

              Waiting for something

              Wait for something to happen with SetTimer

              ; Example #2: Wait for a certain window to appear and then alert the user:
              #Persistent
              SetTimer, Alert1, 500
              return
              
              Alert1:
              IfWinNotExist, Video Conversion, Process Complete
                  return
              
              ; Otherwise:
              SetTimer, Alert1, Off  ; i.e. the timer turns itself off here.
              SplashTextOn, , , The video conversion is finished.
              Sleep, 3000
              SplashTextOff
              return
              

              Suspension

              ; Toggle script suspension
              ^#s:: ; Control + Win + S
              Suspend
              Msgbox % "Script is now " (A_IsSuspended ? "suspended" : "running")
              Return
              

              The Pause keyword would halt the current thread
              while Suspend stops all hotkeys for triggering.

              Start a script with Suspend, Permit to have that hotkey still trigger
              even while the script is suspended.

              Понравилась статья? Поделить с друзьями:
            • Как написать 999 римскими цифрами
            • Как написать 966
            • Как написать 95000 прописью
            • Как написать 928
            • Как написать 926