Краткое руководство по autohotkey для начинающих
Содержание:
- Language Syntax
- Создать скрипт AutoHotkey с нуля
- General Remarks
- Скачать AutoHotkey
- Описание и возможности
- Long Replacements
- Dynamically Calling a Function
- Error Handling
- Parameters
- Вставка специальных символов
- Учебное пособие по AutoHotkey
- AutoHotkey Tutorial
- Joystick
- Examples
- Control Flow
- Run as Administrator [AHK_L 57+]:
- Remarks
Language Syntax
When are quotation marks used with commands and their parameters?
Double quotes («) have special meaning only within . In all other places, they are treated literally as if they were normal characters. However, when a script launches a program or document, the operating system usually requires quotes around any command-line parameter that contains spaces, such as in this example: .
When exactly are variable names enclosed in percent signs?
Variable names are always enclosed in percent signs except in cases illustrated in bold below:
- In parameters that are input or output variables:
- On the left side of an assignment:
- On the left side of traditional (non-expression) if-statements:
- Everywhere in . For example:
If (Var1 <> Var2) Var1 := Var2 + 100
For further explanation of how percent signs are used, see and . Percent signs can also have other meanings:
- The causes a command parameter to be interpreted as an expression.
- Escaped percent signs () and percent signs in have no special meaning (they are interpreted as literal percent signs).
When should percent signs and commas be escaped?
Literal percent signs must be escaped by preceding them with an accent/backtick. For example: Literal commas must also be escaped () except when used in MsgBox or the last parameter of any command (in which case the accent is permitted but not necessary).
When commas or percent signs are enclosed in quotes within an , the accent is permitted but not necessary. For example: .
Создать скрипт AutoHotkey с нуля
До сих пор вы использовали сценарии других людей. Теперь давайте создадим простой эскиз с нуля, который возьмет все, что есть в нашем буфере обмена, и выполнит поиск в нем с помощью Duck Duck Go. Щелкните правой кнопкой мыши на рабочем столе Windows и выберите New> AutoHotkey Script, Кроме того, вы можете использовать любой текстовый редактор или IDE на ваш выбор
Текстовые редакторы против IDE: какой из них лучше для программистов?
Текстовые редакторы против IDE: какой из них лучше для программистов?Выбор между расширенной IDE и более простым текстовым редактором может быть трудным. Мы предлагаем некоторую информацию, чтобы помочь вам принять это решение.
Прочитайте больше
и введите следующее:
#s ссылается на ярлык для запуска сценария. Символ хеша относится к Ключ Windows, означающий, что Win + S наш выбранный ярлык. Этот ярлык зарезервирован для функции поиска Windows 10. В этом случае мы переопределяем его, то есть поиск DuckDuckGo произойдет на его месте. Если вы используете ярлык поиска Windows, замените его другой буквой.
Бежать Команда является одним из мульти-инструментов AutoHotkeys. Согласно документации откроется «Документ, URL, исполняемый файл (.exe, .com, .bat и т. Д.), Ярлык (.lnk) или системный глагол…». В этом случае AutoHotkey откроет URL в браузер по умолчанию.
Наконец, ? Д =% буфер% part — это команда для добавления URL с содержимым буфера обмена Windows.
General Remarks
Characters vs. keys: By default, characters are sent by first translating them to keystrokes. If this translation is not possible (that is, if the current keyboard layout does not contain a key or key combination which produces that character), the character is sent by one of following fallback methods:
- SendEvent and SendInput use SendInput() with the . : ANSI builds of AutoHotkey convert the character to Unicode before sending it. Prior to v1.1.27, ANSI builds used the Alt+nnnnn method.
- SendPlay uses the method, which produces Unicode only if supported by the target application.
- ControlSend posts a WM_CHAR message.
Note: Characters sent using any of the above methods usually do not trigger keyboard shortcuts or hotkeys.
: For characters in the range a-z or A-Z (plain ASCII letters), each character which does not exist in the current keyboard layout may be sent either as a character or as the corresponding virtual keycode (vk41-vk5A):
- If a naked letter is sent (that is, without modifiers or braces), or if mode is in effect, it is sent as a character. For example, sends the expected text, even though pressing R (vk52) produces some other character (such as К on the Russian layout). can be omitted in this case, unless a modifier key was put into effect by a prior Send.
- If one or more modifier keys have been put into effect by the Send command, or if the letter is wrapped in braces, it is sent as a keycode (modified with Shift if the letter is upper-case). This allows the script to easily activate standard keyboard shortcuts. For example, and activate the standard Ctrl+C shortcut and is equivalent to .
If the letter exists in the current keyboard layout, it is always sent as whichever keycode the layout associates with that letter (unless the is used, in which case the character is sent by other means). In other words, the section above is only relevant for non-Latin based layouts such as Russian.
Modifier State: When Send is required to change the state of the Win or Alt modifier keys (such as if the user was holding one of those keys), it may inject additional keystrokes (Ctrl by default) to prevent the Start menu or window menu from appearing. For details, see #MenuMaskKey.
BlockInput Compared to SendInput/SendPlay: Although the BlockInput command can be used to prevent any keystrokes physically typed by the user from disrupting the flow of simulated keystrokes, it is often better to use or so that keystrokes and mouse clicks become uninterruptible. This is because unlike BlockInput, SendInput/Play does not discard what the user types during the send; instead, such keystrokes are buffered and sent afterward.
When sending a large number of keystrokes, a can be used to improve readability and maintainability.
Since the operating system does not allow simulation of the Ctrl+Alt+Del combination, doing something like will have no effect.
Send may have no effect on Windows Vista or later if the active window is running with administrative privileges and the script is not. This is due to a security mechanism called User Interface Privilege Isolation.
Скачать AutoHotkey
Там представлено несколько несколько версий, разберёмся в них:
- AutoHotkey 1.1.* — это актуальная версия, которая активно разрабатывается. Ранее была известна как AutoHotkey_L.
- AutoHotkey 1.0.* — развитие этой версии остановлено несколько лет назад, ранее была известна как AutoHotkey Basic, Classic, Vanilla.
- AutoHotkey 2.0-a* — альфа выпуск новой версии AutoHotkey v2.
Ветка AutoHotkey 2.0-a* является работоспособной, но в ней поменялся синтаксис языка по этой причине большинство готовых скриптов, которые вы можете найти в Интернете, в ней работать не будут.
То есть скачиваем версию AutoHotkey 1.1.*. Если вы хотите скачать установщик, то нажмите на кнопку «Download AutoHotkey Installer». Для скачивания портативной версии нажмите «Download AutoHotkey .zip».
Скачайте установщик, им проще пользоваться, чем портативной версией.
Описание и возможности
Итак, что же это за приложение и для чего оно нужно? АвтоХоткей – это специальная утилита, которая воспроизводит заранее написанные скрипты или как еще их называют бинды. Рассмотрим основные и дополнительные возможности ПО, для того чтобы вы поняли его назначение:
- Какой-либо горячей кнопкой или кликом мыши вы можете запустить заранее запрограммированный макрос, который, в свою очередь, выполнит целую серию событий.
- На любые кнопки клавиатуры, игрового джойстика или мыши мы можем назначить отдельные макросы. При этом поддерживается не только обычный, но и двойной клик.
- Собственный скриптовый язык позволяет, например, создать функционал для автоматической замены введенного текста.
- Поддерживается переназначение клавиш на клавиатуре, мыши или игровом контролере.
- Любой скрипт, который написал пользователь, может быть преобразован в обычной EXE-файл. Это позволит запускать его уже без участия программы AutoHotkey.
Утилита, о которой рассказывается ниже, обладает и другими возможностями. Подробнее познакомиться с ними можно при помощи и прикрепленного в конце странички обучающего видео.
Long Replacements
Hotstrings that produce a large amount of replacement text can be made more readable and maintainable by using a . For example:
::text1:: ( Any text between the top and bottom parentheses is treated literally, including commas and percent signs. By default, the hard carriage return (Enter) between the previous line and this one is also preserved. By default, the indentation (tab) to the left of this line is preserved. )
See for how to change these default behaviors. The presence of a continuation section also causes the hotstring to default to . The only way to override this special default is to specify the in each hotstring that has a continuation section (e.g. ).
Dynamically Calling a Function
: A function (even a ) may be called dynamically via percent signs. For example, would call the function whose name is contained in Var. Similarly, would call Func1() or Func2(), etc., depending on the current value of A_Index.
: Var in can contain a function name or a function object. If the function does not exist, the ‘s __Call meta-function is invoked instead.
If the function cannot be called due to one of the reasons below, the evaluation of the expression containing the call stops silently and prematurely, which may lead to inconsistent results:
- Calling a nonexistent function, which can be avoided by using . Except for , the called function’s must exist explicitly in the script by means such as #Include or a non-dynamic call to a .
- Passing too few parameters, which can be avoided by checking ‘s return value (which is the number of mandatory parameters plus one). : Note that passing too many parameters is tolerated; each extra parameter is fully evaluated (including any calls to functions) and then discarded.
Finally, a dynamic call to a function is slightly slower than a normal call because normal calls are resolved (looked up) before the script begins running.
Error Handling
: This command is able to throw an exception on failure. For more information, see .
ErrorLevel is changed only when: 1) the first parameter is IfWinActive/Exist, in which case it is set to 1 if there was a problem or 0 otherwise; or 2) the word UseErrorLevel is present in the Options parameter.
: If the first parameter is «If», an exception is thrown if the second parameter is invalid or a memory allocation fails. ErrorLevel is not set in those cases, but is still set to 0 on success.
Error | Description |
---|---|
1 | The Label parameter specifies a nonexistent label name. |
2 | The KeyName parameter specifies one or more keys that are either not recognized or not supported by the current keyboard layout/language. |
3 | Unsupported prefix key. For example, using the mouse wheel as a prefix in a hotkey such as is not supported. |
4 | The KeyName parameter is not suitable for use with the actions. A combination of (at most) two keys is required. For example: . |
5 | The command attempted to modify a nonexistent hotkey. |
6 | The command attempted to modify a nonexistent of an existing hotkey. To solve this, use to set the criteria to match those of the hotkey to be modified. |
98 | Creating this hotkey would exceed the limit of hotkeys per script (however, each hotkey can have an unlimited number of , and there is no limit to the number of hotstrings). The limit was raised from 700 to 1000 in , and to 32762 in . |
99 | Out of memory. This is very rare and usually happens only when the operating system has become unstable. |
Tip: The UseErrorLevel option can be used to test for the existence of a hotkey variant. For example:
Hotkey, ^!p,, UseErrorLevel if ErrorLevel in 5,6 MsgBox The hotkey does not exist or it has no variant for the current IfWin criteria.
Parameters
- Keys
-
The sequence of keys to send. As with other commands, the comma in front of the first parameter is optional.
By default (that is, if neither SendRaw nor the or is used), the characters have a special meaning. The characters represent the modifier keys Ctrl, Shift, Alt and Win. They affect only the very next key. To send the corresponding modifier key on its own, enclose the key name in braces. To just press (hold down) or release the key, follow the key name with the word «down» or «up» as shown below.
Symbol Key Press Release Examples ^ {Ctrl} {Ctrl down} {Ctrl up} presses Ctrl+Home + {Shift} {Shift down} {Shift up} sends the text «AbC» presses Alt+Shift+A ! {Alt} {Alt down} {Alt up} presses Alt+A # {LWin}{RWin} {LWin down}{RWin down} {LWin up}{RWin up} holds down Win and then presses E Note: As capital letters are produced by sending Shift, produces a different effect in some programs than . For example, presses Alt+Shift+A and presses Alt+A. If in doubt, use lowercase.
The characters are used to enclose , and to send special characters literally. For example, is Tab and is a literal exclamation mark.
: Enclosing a plain ASCII letter (a-z or A-Z) in braces forces it to be sent as the corresponding virtual keycode, even if the character does not exist on the current keyboard layout. In other words, produces the letter «a» while may or may not produce «a», depending on the keyboard layout. For details, see the .
Вставка специальных символов
Хотя на клавиатуре присутствуют некоторые символы, такие как «@» или «№», существует множество других, набирать которые довольно утомительно, в особенности если приходится иметь с ними дело каждый день. Написав всего одну строку кода AHK, вы сможете легко вставлять их без поиска кодов с «Alt» или копирования с интернет-ресурсов.
Используйте шаблон кода, представленный ниже, чтобы назначать горячие клавиши для нужных вам символов. Слева находится комбинация, сам символ заключен в фигурные скобки. К примеру, чтобы при нажатии сочетания клавиш «Alt» + «Й» выводился символ торговой марки, понадобится такой код:
!й::SendInput {}
Список обозначений AutoHotkey:
^ для «CTRL»; ! для «ALT»; # для «Windows»; + для «Shift».
Учебное пособие по AutoHotkey
Прежде всего, вам нужно загрузить AutoHotKey и установить его на свой компьютер. Его значок программы будет находиться в системном трее, откуда вы можете управлять всеми вашими сценариями. Вы также можете приостановить AutoHotkey здесь в течение определенного периода времени или даже выйти, если вам не нужно запускать скрипты
Обратите внимание, что при выходе из приложения в системном лотке ваши скрипты не будут работать
Когда вы устанавливаете программу AutoHotKey, вы получаете возможность видеть образцы сценариев в «Блокноте». Это говорит SHOW README. Если вы установите флажок и нажмите Завершить после установки, откроется окно справки Windows, в котором вы найдете подробные инструкции по использованию программы.
ВАЖНО: Создание сценариев в «Блокноте» и сохраните их с расширением .AHK, чтобы они работали. Выберите «ВСЕ ФАЙЛЫ» в разделе «Тип» (второй раскрывающийся список ниже «Текстовое поле имени файла»)
Он показывает *. * В соответствующем текстовом поле, и там вам нужно ввести AHK вместо TXT. Если вы сохраняете как TXT, сценарий не будет работать.
Как использовать скрипты AutoHotkey
Ниже приведен краткий учебник по использованию AutoHotkey.
Специальные клавиши (CTRL, ALT, SHIFT, WINDOWS KEY)
Когда вы создаете скрипты, вы назначаете их клавишам. В большинстве случаев вам необходимо назначить их комбинации специальных клавиш, за которыми следуют обычные клавиши. Специальные клавиши в этом отношении — WINDOWS KEY, CTRL, SHIFT и ALT. Вы можете использовать один или несколько специальных клавиш для назначения ваших скриптов. Например, вы можете назначить скрипт CTRL + SHIFT + S. В этом случае вам нужно ввести специальные ключи в формате, предоставленном AutoHotKeys.
CTRL представлен символом ^
SHIFT представлен +
ALT представлен символом!
Ключ Windows представлен #
:: part заканчивает комбинацию горячих клавиш и сценарий следует
Для начала вам сначала нужно ввести специальную комбинацию клавиш, которая активирует скрипт вы создали. Например, если вы хотите назначить CTRL + SHIFT + S для запуска Google, ваш скрипт будет выглядеть следующим образом:
^ + S :: Запустить google.com
Специальные слова или команды
Чтобы запустить программы или веб-сайта, используйте RUN . Например, если вы создаете следующее:
! ^ F :: Запустить блокнот
С помощью приведенного выше сценария, когда вы нажимаете ALT + SHIFT + F, запускается Блокнот. RUN — это ключевое слово, которое помогает запускать программу или запускать веб-сайт. В следующем примере показано, как горячая клавиша открывает Google в вашей программе по умолчанию, а затем запускает «Блокнот».
^ + E :: Запустить google.com Запустить Notepad Return
Все четыре строки выше — это один скрипт, который активируется с помощью CTRL + SHIFT + E. Слово RETURN — это еще одно ключевое слово, которое указывает конец скрипта, когда вы используете несколько строк. Всякий раз, когда вы создаете скрипт с несколькими строками, вы должны использовать RETURN в конце скрипта, чтобы AutoHotKey знал, что скрипт заканчивается здесь.
Вы можете добавить столько команд, которые вы хотите, в один файл AHK, но помните использовать RETURN в конце последнего скрипта в файле AHK. Вы должны запустить файл AHK, дважды щелкнув его, прежде чем вы сможете использовать скрипты
Другим ключевым словом, которое стоит использовать, является SEND . Он посылает нажатия клавиш в оболочку, и вы можете использовать его для создания таких вещей, как подписи и т. Д. См. Следующий пример.
^! S :: Отправить приветствия {ENTER} Arun Kumar Return
В приведенном выше скрипте, когда я нажимаю CTRL + ALT + S, он вставляет С уважением , а затем клавишу Enter (для изменения строки), а затем вставьте Арун Кумар . В приведенном выше примере показано, как ввести ключ ENTER. Клавиша ENTER всегда включена внутри фигурных скобок {}.
Аналогично, если вы хотите ввести TAB, это должно быть {TAB}. Аналогично, клавиша пробела будет . Для ввода пробела вам не нужно использовать . Он автоматически примет в SPACE, когда вы вводите клавишу SPACE в скрипте, как в приведенном выше примере. В этом примере за Arun следует пробел, а затем Kumar .
Этот учебник не является исчерпывающим, но этого достаточно, чтобы вы начали с программы для создания коротких сценариев AutoHotKey.
Теперь читаем: Отображение глобальных горячих клавиш в Windows.
AutoHotkey Tutorial
As you install AutoHotKey program, you get an option to see sample scripts in Notepad. It says SHOW README. If you keep the box checked and click Finish after installation, a Windows Help Window is launched where you can find detailed instructions on how to use the program.
IMPORTANT: Create scripts in Notepad and save them with .AHK extension so that they work. Select ALL FILES under Type (the second drop down list below Filename Text Box). It shows *.* in the related text box and there, you have to enter AHK instead of TXT. If you save as TXT, the script will not work.
How to use AutoHotkey scripts
The following is a brief tutorial for using AutoHotkey.
Special Keys (CTRL, ALT, SHIFT, WINDOWS KEY)
When you create scripts, you assign them to keys. In most cases you have to assign them to a combination of special keys followed by regular keys. The special keys in this regard are WINDOWS KEY, CTRL, SHIFT and ALT. You can use one or more than one special keys to assign your scripts. For example, you might want to assign a script to CTRL + SHIFT + S. In that case you have to type the special keys in the format provided by AutoHotKeys.
CTRL is represented by ^
SHIFT is represented by +
ALT is represented by !
Windows Key is represented by #
:: part ends the hotkey combination and script follows
To begin, you first have to type the special key combination that will activate the script you created. For example, if you wish to assign CTRL + SHIFT + S to launch Google, your script will look like the following:
^+S:: Run google.com
Special Words or Commands
To launch a program or website, use RUN. For example if you create the following:
!^F:: Run Notepad
With the above script, when you press ALT+SHIFT+F, Notepad is launched. RUN is a keyword that helps you run a program or launch a website. Another example below shows you how a hotkey opens Google in your default program and then launches Notepad.
^+E:: Run google.com Run Notepad Return
All the four lines above are one script that is activated using CTRL+SHIFT+E. The word RETURN is another keyword that indicates end of script when you are using multiple lines. Whenever you create a script with more than one line, you should use RETURN at the end of the script so that AutoHotKey knows that the script ends here.
You can add as many commands you want into a single AHK file, but remember to use RETURN towards the end of last script in the AHK file. You have to launch the AHK file by double clicking it before you can use the scripts
Another keyword worth using is SEND. It sends keystrokes to the shell and you can use it create things like signatures etc. See the following example.
^!S:: Send Regards{ENTER}Arun Kumar Return
In the above script, when I press CTRL+ALT+S, it will paste Regards, followed by an Enter key (for line change) and then insert Arun Kumar. The above example shows you how to enter the ENTER key. The ENTER key is always included inside braces {}.
Similarly, if you wish to enter a TAB, it should be {TAB}. Likewise, space key will be . You need not use to enter a SPACE. It will automatically take in SPACE when you enter SPACE key in the script as in the above example. In the example, Arun is followed by a SPACE and then Kumar.
This tutorial is not comprehensive but is enough to get you started with the program to create short AutoHotKey scripts.
Now read: Display global hotkeys list in Windows.
Joystick
Joy1 through Joy32: The buttons of the joystick. To help determine the button numbers for your joystick, use this . Note that hotkey prefix symbols such as ^ (control) and + (shift) are not supported (though can be used as a substitute). Also note that the pressing of joystick buttons always «passes through» to the active window if that window is designed to detect the pressing of joystick buttons.
Although the following Joystick control names cannot be used as hotkeys, they can be used with :
- JoyX, JoyY, and JoyZ: The X (horizontal), Y (vertical), and Z (altitude/depth) axes of the joystick.
- JoyR: The rudder or 4th axis of the joystick.
- JoyU and JoyV: The 5th and 6th axes of the joystick.
- JoyPOV: The point-of-view (hat) control.
- JoyName: The name of the joystick or its driver.
- JoyButtons: The number of buttons supported by the joystick (not always accurate).
- JoyAxes: The number of axes supported by the joystick.
- JoyInfo: Provides a string consisting of zero or more of the following letters to indicate the joystick’s capabilities: Z (has Z axis), R (has R axis), U (has U axis), V (has V axis), P (has POV control), D (the POV control has a limited number of discrete/distinct settings), C (the POV control is continuous/fine). Example string: ZRUVPD
Multiple Joysticks: If the computer has more than one joystick and you want to use one beyond the first, include the joystick number (max 16) in front of the control name. For example, 2joy1 is the second joystick’s first button.
Note: If you have trouble getting a script to recognize your joystick, one person reported needing to specify a joystick number other than 1 even though only a single joystick was present. It is unclear how this situation arises or whether it is normal, but experimenting with the joystick number in the can help determine if this applies to your system.
See Also:
- Joystick remapping: Methods of sending keystrokes and mouse clicks with a joystick.
- : Using a joystick as a mouse.
Examples
Run is able to launch Windows system programs from any directory. Note that executable file extensions such as .exe can be omitted.
Run, notepad
Run is able to launch URLs:
The following opens an internet address in the user’s default web browser.
Run, https://www.google.com
Run, mailto:
The following does the same as above, plus the subject and body.
Run, mailto:?subject=This is the subject line&body=This is the message body's text.
Opens a document in a maximized application and displays a custom error message on failure.
Run, ReadMe.doc, , Max UseErrorLevel if (ErrorLevel = "ERROR") MsgBox The document could not be launched.
Runs the dir command in minimized state and stores the output in a text file. After that, the text file and its properties dialog will be opened.
#Persistent RunWait, %ComSpec% /c dir C:\ >>C:\DirTest.txt, , Min Run, C:\DirTest.txt Run, properties C:\DirTest.txt
Run is able to launch CLSIDs:
The following opens the recycle bin.
Run, ::{645ff040-5081-101b-9f08-00aa002f954e}
The following opens the «My Computer» directory.
Run, ::{20d04fe0-3aea-1069-a2d8-08002b30309d}
To run multiple commands consecutively, use «&&» between each.
Run, %ComSpec% /c dir /b > C:\list.txt && type C:\list.txt && pause
The following functions can be used to run a command and retrieve its output or to run multiple commands in one go and retrieve their output.
MsgBox % RunWaitOne("dir " A_ScriptDir) MsgBox % RunWaitMany(" ( echo Put your commands here, echo each one will be run, echo and you'll get the output. )") RunWaitOne(command) { ; WshShell object: http://msdn.microsoft.com/en-us/library/aew9yb99 shell := ComObjCreate("WScript.Shell") ; Execute a single command via cmd.exe exec := shell.Exec(ComSpec " /C " command) ; Read and return the command's output return exec.StdOut.ReadAll() } RunWaitMany(commands) { shell := ComObjCreate("WScript.Shell") ; Open cmd.exe with echoing of commands disabled exec := shell.Exec(ComSpec " /Q /K echo off") ; Send the commands to execute, separated by newline exec.StdIn.WriteLine(commands "`nexit") ; Always exit at the end! ; Read and return the output of all commands return exec.StdOut.ReadAll() }
Executes the given code as a new AutoHotkey process.
ExecScript(Script, Wait:=true) { shell := ComObjCreate("WScript.Shell") exec := shell.Exec("AutoHotkey.exe /ErrorStdOut *") exec.StdIn.Write(script) exec.StdIn.Close() if Wait return exec.StdOut.ReadAll() } ; Example: InputBox expr,, Enter an expression to evaluate as a new script.,,,,,,,, Asc("*") result := ExecScript("FileAppend % (" expr "), *") MsgBox % "Result: " result
Control Flow
Control flow is the order in which individual statements are executed. Normally statements are executed sequentially from top to bottom, but a control flow statement can override this, such as by specifying that statements should be executed repeatedly, or only if a certain condition is met.
- Statement
-
A statement is simply the smallest standalone element of the language that expresses some action to be carried out. In AutoHotkey, statements include commands, assignments, function calls and other expressions. However, directives, labels (including hotkeys and hotstrings), and declarations without assignments are not statements; they are processed when the program first starts up, before the script executes.
- Execute
-
Carry out, perform, evaluate, put into effect, etc. Execute basically has the same meaning as in non-programming speak.
- Body
-
The body of a control flow statement is the statement or group of statements to which it applies. For example, the body of an is executed only if a specific condition is met.
For example, consider this simple set of instructions:
- Open Notepad
- Wait for Notepad to appear on the screen
- Type «Hello, world!»
We take one step at a time, and when that step is finished, we move on to the next step. In the same way, control in a program or script usually flows from one statement to the next statement. But what if we want to type into an existing Notepad window? Consider this revised set of instructions:
- If Notepad is not running:
- Open Notepad
- Wait for Notepad to appear on the screen
- Otherwise:
- Activate Notepad
- Type «Hello, world!»
So we either open Notepad or activate Notepad depending on whether it is already running. #1 is a conditional statement, also known as an if statement; that is, we execute its body (#1.1 — #1.2) only if a condition is met. #2 is an else statement; we execute its body (#2.1) only if the condition of a previous if statement (#1) is not met. Depending on the condition, control flows one of two ways: #1 (if true) → #1.1 → #1.2 → #3; or #1 (if false) → #2 (else) → #2.1 → #3.
The instructions above can be translated into the code below:
if (not WinExist("ahk_class Notepad")) { Run Notepad WinWait ahk_class Notepad } else WinActivate ahk_class Notepad Send Hello`, world!
In our written instructions, we used indentation and numbering to group the statements. Scripts work a little differently. Although indentation makes code easier to read, in AutoHotkey it does not affect the grouping of statements. Instead, statements are grouped by enclosing them in braces, as shown above. This is called a block.
For details about syntax — that is, how to write or recognise control flow statements in AutoHotkey — see .
Run as Administrator [AHK_L 57+]:
For an executable file, the *RunAs verb is equivalent to selecting Run as administrator from the right-click menu of the file. For example, the following code attempts to restart the current script as admin:
full_command_line := DllCall("GetCommandLine", "str") if not (A_IsAdmin or RegExMatch(full_command_line, " /restart(?!\S)")) { try { if A_IsCompiled Run *RunAs "%A_ScriptFullPath%" /restart else Run *RunAs "%A_AhkPath%" /restart "%A_ScriptFullPath%" } ExitApp } MsgBox A_IsAdmin: %A_IsAdmin%`nCommand line: %full_command_line%
If the user cancels the UAC dialog or Run fails for some other reason, the script will simply exit.
Using ensures that a single instance prompt is not shown if the new instance of the script starts before ExitApp is called.
If UAC is disabled, *RunAs will launch the process without elevating it. Checking for in the command line ensures that the script does not enter a runaway loop in that case. Note that is a built-in switch, so is not included in the .
The example can be modified to fit the script’s needs:
- If the script absolutely requires admin rights, check A_IsAdmin a second time in case *RunAs failed to elevate the script (i.e. because UAC is disabled).
- To keep the script running even if the user cancels the UAC prompt, move ExitApp into the try block.
- To keep the script running even if it failed to restart (i.e. because the script file has been changed or deleted), remove ExitApp and use RunWait instead of Run. On success, causes the new instance to terminate the old one. On failure, the new instance exits and RunWait returns.
: If UAC is enabled, the AutoHotkey installer registers the RunAs verb for .ahk files, which allows to launch a script as admin with the default executable.
Remarks
The determines the of a hotkey upon which the Hotkey command will operate.
If the goal is to disable selected hotkeys or hotstrings automatically based on the type of window that is active, is usually less convenient than using #IfWinActive/Exist (or their dynamic counterparts «Hotkey IfWinActive/Exist» ).
Creating hotkeys via double-colon labels performs better than using the Hotkey command because the hotkeys can all be enabled as a batch when the script starts (rather than one by one). Therefore, it is best to use this command to create only those hotkeys whose key names are not known until after the script has started running. One such case is when a script’s hotkeys for various actions are configurable via an INI file.
A given label can be the target of more than one hotkey. If it is known that a label was called by a hotkey, you can determine which hotkey by checking the built-in variable .
If the script is suspended, newly added/enabled hotkeys will also be suspended until the suspension is turned off (unless they are exempt as described in the Suspend section).
The keyboard and/or mouse hooks will be installed or removed if justified by the changes made by this command.
Although the Hotkey command cannot directly enable or disable hotkeys in scripts other than its own, in most cases it can override them by creating or enabling the same hotkeys. Whether this works depends on a combination of factors: 1) Whether the hotkey to be overridden is a hook hotkey in the other script (non-hook hotkeys can always be overridden); 2) The fact that the most recently started script’s hotkeys generally take precedence over those in other scripts (therefore, if the script intending to override was started most recently, its override should always succeed); 3) Whether the enabling or creating of this hotkey will newly activate the keyboard or mouse hook (if so, the override will always succeed).
Once a script has at least one hotkey, it becomes persistent, meaning that ExitApp rather than Exit should be used to terminate it. Hotkey scripts are also automatically #SingleInstance unless has been specified.