Autohotkey beginner tutorial by tidbit

Установка AutoHotkey

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

Теперь только что установленная программа обрабатывает выполнение сценариев, которые вы пишете на языке AutoHotkey, но у вас еще нет запущенных сценариев! Чтобы создать новый, убедитесь, что AutoHotkey запущен (откройте меню «Пуск» и введите AutoHotkey запустить программу), затем щелкните правой кнопкой мыши в любом месте на рабочем столе или в любом другом удобном месте и выберите New> AutoHotkey Script. Назовите это что-нибудь полезное и убедитесь, что файл заканчивается .АХК, или это не будет работать правильно.

Если вы собираетесь писать несколько сценариев для AutoHotkey, неплохо бы обновить ваш текстовый редактор из мягкого блокнота

, Notepad ++ — отличный бесплатный вариант, который рекомендуется для этой цели

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

Теперь, когда у вас есть программное обеспечение для запуска сценариев, вы можете загрузить код, написанный другими, для автоматизации всех видов задач. Чтобы сохранить скрипт, просто загрузите его как .АХК файл и сохранить его, где вы хотите.

Возможно, вы захотите, чтобы некоторые из этих сценариев запускались сразу после загрузки компьютера, поэтому вам не нужно каждый раз запускать их вручную. Для этого скопируйте и вставьте .АХК файлы в папку «Автозагрузка», набрав оболочка: запуск в меню «Пуск» или перейдя по следующему адресу:

Это обеспечит их запуск сразу после запуска, поэтому вы не пытаетесь использовать комбинации клавиш и ничего не получаете!

Script File Codepage [AHK_L 51+]

In order for non-ASCII characters to be read correctly from file, the encoding used when the file was saved (typically by the text editor) must match what AutoHotkey uses when it reads the file. If it does not match, characters will be decoded incorrectly. AutoHotkey uses the following rules to decide which encoding to use:

  • If the file begins with a UTF-8 or UTF-16 (LE) byte order mark, the appropriate codepage is used and the switch is ignored.
  • If the switch is passed on the command-line, codepage n is used. For a list of possible values, see Code Page Identifiers.

    Note: The «Default to UTF-8» option in the AutoHotkey installer adds to the command line for all scripts launched via the shell (Explorer).

  • In all other cases, the system default ANSI codepage is used.

Note that this applies only to script files loaded by AutoHotkey, not to file I/O within the script itself. FileEncoding controls the default encoding of files read or written by the script, while IniRead and IniWrite always deal in UTF-16 or ANSI.

As all text is converted (where necessary) to the , characters which are invalid or don’t exist in the native codepage are replaced with a placeholder: ANSI ‘?’ or Unicode ‘�’. In Unicode builds, this should only occur if there are encoding errors in the script file or the codepages used to save and load the file don’t match.

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

; Uncomment the appropriate line below or leave them all commented to
;   reset to the default of the current build.  Modify as necessary:
; codepage := 0        ; System default ANSI codepage
; codepage := 65001    ; UTF-8
; codepage := 1200     ; UTF-16
; codepage := 1252     ; ANSI Latin 1; Western European (Windows)
if (codepage != "")
    codepage := " /CP" . codepage
cmd="%A_AhkPath%"%codepage% "`%1" `%*
key=AutoHotkeyScript\Shell\Open\Command
if A_IsAdmin    ; Set for all users.
    RegWrite, REG_SZ, HKCR, %key%,, %cmd%
else            ; Set for current user only.
    RegWrite, REG_SZ, HKCU, Software\Classes\%key%,, %cmd%

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

Optional Parameters

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

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

The following function has its Z parameter marked optional:

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

When the caller passes three parameters to the function above, Z’s default value is ignored. But when the caller passes only two parameters, Z automatically receives the value 0.

It is not possible to have optional parameters isolated in the middle of the parameter list. In other words, all parameters that lie to the right of the first optional parameter must also be marked optional. : Optional parameters may be omitted from the middle of the parameter list when calling the function, as shown below. For dynamic function calls and method calls, this requires .

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

: also support default values; for example: . Whenever the caller omits such a parameter, the function creates a local variable to contain the default value; in other words, the function behaves as though the keyword «ByRef» is absent.

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.

Send variants

Send: By default, Send is synonymous with SendEvent; but it can be made a synonym for SendInput or SendPlay via SendMode.

SendRaw: Similar to Send, except that all characters in Keys are interpreted and sent literally. See for details.

SendInput and SendPlay : 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 and below.

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

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

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

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

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

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

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

Although a library file generally contains only a single function of the same name as its filename, it may also contain private functions and subroutines that are called only by it. However, such functions should have fairly distinct names because they will still be in the global namespace; that is, they will be callable from anywhere in the script.

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

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

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

Parameters

When a function is defined, its parameters are listed in parentheses next to its name (there must be no spaces between its name and the open-parenthesis). If a function does not accept any parameters, leave the parentheses empty; for example: .

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

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

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

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

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

When passing large strings to a function, ByRef enhances performance and conserves memory by avoiding the need to make a copy of the string. Similarly, using ByRef to send a long string back to the caller usually performs better than something like .

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

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

Known limitations:

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

The Top of the Script (the Auto-execute Section)

After the script has been loaded, it begins executing at the top line, continuing until a Return, Exit, hotkey/hotstring label, or the physical end of the script is encountered (whichever comes first). This top portion of the script is referred to as the auto-execute section.

Note: While the script’s first hotkey/hotstring label has the same effect as return, other hotkeys and labels do not.

If the script is not persistent, it will terminate after the auto-execute section has completed. Otherwise, it will stay running in an idle state, responding to events such as hotkeys, hotstrings, , custom menu items, and timers. A script is automatically persistent if it contains hotkeys, hotstrings, OnMessage() or GUI, and in a few other cases. The #Persistent directive can also be used to explicitly make the script persistent.

Every thread launched by a hotkey, hotstring, menu item, , or timer starts off fresh with the default values for the following attributes as set in the auto-execute section. If unset, the standard defaults will apply (as documented on each of the following pages): AutoTrim, CoordMode, Critical, DetectHiddenText, DetectHiddenWindows, FileEncoding, ListLines, SendLevel, SendMode, SetBatchLines, SetControlDelay, SetDefaultMouseSpeed, SetFormat, SetKeyDelay, SetMouseDelay, SetRegView, SetStoreCapsLockMode, SetTitleMatchMode, SetWinDelay, StringCaseSense, and Thread.

If the auto-execute section takes a long time to complete (or never completes), the default values for the above settings will be put into effect after 100 milliseconds. When the auto-execute section finally completes (if ever), the defaults are updated again to be those that were in effect at the end of the auto-execute section. Thus, it’s usually best to make any desired changes to the defaults at the top of scripts that contain hotkeys, hotstrings, timers, or custom menu items. Also note that each thread retains its own collection of the above settings. Changes made to those settings will not affect other threads.

Return, Exit, and General Remarks

If the flow of execution within a function reaches the function’s closing brace prior to encountering a Return, the function ends and returns a blank value (empty string) to its caller. A blank value is also returned whenever the function explicitly omits Return’s parameter.

When a function uses the Exit command to terminate the current thread, its caller does not receive a return value at all. For example, the statement would leave unchanged if exits. The same thing happens if a function causes a runtime error such as running a nonexistent file (when is not in effect).

A function may alter the value of ErrorLevel for the purpose of returning an extra value that is easy to remember.

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

Since calling a function does not start a new thread, any changes made by a function to settings such as SendMode and SetTitleMatchMode will go into effect for its caller too.

The caller of a function may pass a nonexistent variable or array element to it, which is useful when the function expects the corresponding parameter to be . For example, calling would create the variable automatically as a or global (depending on whether the caller is inside a function and whether it has the in effect).

When used inside a function, ListVars displays a function’s along with their contents. This can help debug a script.

Hotkey Tips and Remarks

Each numpad key can be made to launch two different hotkey subroutines depending on the state of NumLock. Alternatively, a numpad key can be made to launch the same subroutine regardless of the state. For example:

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

If the is used with a even once, it changes the behavior of that prefix key for all combinations. For example, in both of the below hotkeys, the active window will receive all right-clicks even though only one of the definitions contains a tilde:

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

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

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

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

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

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

^!s::Send {Delete}

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

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

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

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

One common use for hotkeys is to start and stop a repeating action, such as a series of keystrokes or mouse clicks. For an example of this, see .

Finally, each script is quasi multi-threaded, which allows a new hotkey to be launched even when a previous hotkey subroutine is still running. For example, new hotkeys can be launched even while a message box is being displayed by the current hotkey.

Run arbitrary AutoHotkey scripts

from ahk import AHK

ahk = AHK()

ahk_script = 'Run Notepad'
ahk.run_script(ahk_script, blocking=False)

Communicating data from ahk to Python

If you’re writing your own ahk scripts to use with this library, you can use with the parameter to get data from your ahk script into Python.

Suppose you have a script like so

#Persistent
data := "Hello Data!"
FileAppend, %data%, * ; send data var to stdout
ExitApp
result = ahk.run_script(my_script)
print(result)  # Hello Data!

If your autohotkey returns something that can’t be decoded, add the keyword argument in which case you’ll get back a object where stdout (and stderr) will be bytes and you can handle it however you choose.

result = ahk.run_script(my_script, decode=False)
print(result.stdout)  # b'Hello Data!'

Имитируем клики мышкой

С кликами мышкой работать несколько сложнее, чем с использованием клавиатуры, так как здесь помимо кнопок есть еще и определенное месторасположение курсора, которое нужно указывать. В связи с этим пользователь сначала должен определить координаты X и Y того места на экране, куда должно отправляться созданное событие. Делается это при помощи встроенной в программу утилиты под названием Active Window Info.

1. Для начала вам следует запустить саму программу из трея на заранее открытом скрипте. Также вы можете просто кликнуть меню «Пуск», выбрать «Все программы» и там в меню «AutoHotKey» выбрать «Active Window Info». Сразу стоит сказать о том, что данное окно будет автоматически располагаться поверх остальных, что требуется для удобства работы с утилитой.

2. Запустите подопытное окно программы. Для этого нужно кликнуть по заголовку или же использовать стандартную комбинацию клавиш «Alt+Tab».

3. Перемещайте курсор в то место, где нужно будет осуществлять нужное вам событие, после чего посмотрите уже в окно Active Window Info. Теперь записывайте координаты, которые показаны в окне этой программы (их можно найти в строчке «On Screen» или же в строке «In Active Window») в зависимости от того, какая область конкретно на данный момент вас интересует.

Стоит отметить тот факт, что у пользователей Windows XP есть возможность использования комбинации клавиш «Shift+Alt+Tab», при помощи которой окно Window Spy замораживается, а пользователь переходит к нему для копирования нужных цифр.

4. Ставьте полученные вами координаты в скрипте после команды «MouseClick», при этом вставлять нужно только через запятую и после того, как будет обозначена кнопка мыши.

Выглядеть все это может примерно так:

В данном случае «MouseClick» – это команда, которая предназначается для щелчков мыши при помощи AutoHotKey, но для ее нормальной работы нужно будет задать также три параметра через запятую. Первый указывает кнопку мыши (можно писать Left или Right целиком, а можно просто использовать буквы L и R. M указывает на необходимость клика по скроллу). Остальные параметры представляют собой координаты X и Y того места на экране, в которое нужно будет кликнуть.

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

Помимо всего прочего, программа может использоваться для перетаскивания мышью каких-либо объектов, что осуществляется при использовании команды «MouseClickDrag». В этой команде уже нужно будет вводить сразу пять параметров, первый из которых представляет собой клик нужной кнопкой мыши, второй и третий включают в себя стартовые координаты, а четвертый и пятый – последние, то есть то место, где мышка должна быть отпущена.

Команда может выглядеть примерно следующим образом:

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

Скрипты AutoHotKey для CS:GO

Bhop

Bhop (распрыжка) — это крутой скрипт для отработки упражнений, когда вы освоите его, подумайте о распрыжке с колесом прокрутки.

F11 для включения и отключения. Кнопка End дял полного отключения.

VAC вас НИКОГДА не обнаружит.

Autofire

Autofire не очень практичен для конкурентного игрового процесса, но с DM и Casual это интересно.

Они безопасны для VAC, но их не рекомендуется использовать в конкурентных состязаниях или на пользовательских серверах, их обнаруживает пользовательский античит.

Чтобы поставить скрипт на паузу нажмите F6.

Ultimate CS:GO Multiscript

Это НЕ чит, он не будет вводить или делать что-либо с CS:GO, он просто симулирует события мыши/клавиатуры.

Характеристики

  • Удивительный графический интерфейс для быстрого и простого отображения.
  • Авто-купить оружие, можно настроить в графическом интерфейсе
  • Burst, 1x Tap, 2x режима огня
  • Rapid Fire (Autofire) для ваших пистолетов/ружей
  • Вертикальный контроль отдачи (в сочетании с автопожаром для пистолета Norecoil)
  • Bhop (распрыжка)
  • Медленный авто огонь для Deagles
  • Авто нож для лучших ножевых комбо!

Горячие кнопки

  • На цифровом блоке клавиатуры 1-3: Выберите пресет для автоматической покупки
  • На цифровом блоке клавиатуры 4: авто огонь
  • На цифровом блоке клавиатуры 5: авто нож
  • На цифровом блоке клавиатуры 6: одно нажатие = взрыв, удерживайте мышь для спрея с катушкой
  • На цифровом блоке клавиатуры 7-9: 1x Tap, 2x Tap, Взрыв
  • Правый Ctrl: режим огня по умолчанию
  • Правый Alt: переключить «без отдачи»
  • CapsLock: переключить Bhop (раскрыжка)
  • Правый Shift: сделать norecoil (без отдачи) непротиворечивым (только для cz auto)

Пролистните до Code: и разверните Spoiler:

Скрипт длинный, поэтому убедитесь, что полностью скопировали его.

Написание собственных сценариев

В прошлом мы уже много рассказывали об AutoHotkey, в том числе о том, как улучшить Windows с помощью специальных скриптов AHK.

— поэтому я буду кратко о его использовании здесь. Если вы только начинаете работать с AHK, вы, вероятно, больше всего выиграете от расширения текста

,

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

Вы отправляете несколько раз в день? Как часто вы вводите свой адрес электронной почты при входе на веб-сайты и тому подобное? Вместо того, чтобы тратить время на ввод этих элементов каждый раз, настройте расширение текста и сделайте его более продуктивным.

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

Все довольно просто: введите две двоеточия, а затем текст горячей клавиши. После еще двух двоеточий введите фразу для расширения. Итак, если вы хотите, чтобы при наборе «@@» автоматически расширялся ваш адрес электронной почты, сценарий был бы:

Возможностей здесь много — вы можете сделать горячую клавишу CTRL + ALT + C выплевывать консервированные сообщения электронной почты, которые вы вводите несколько раз в день, или любое количество других задач, имеющих отношение к вашей работе:

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

Хотите, чтобы кнопка «Вставка» была ярлыком для «Копировать»? Вы можете сделать это!

Проверьте учебники AutoHotkey для получения дополнительной информации.

Introduction and Simple Examples

Hotkeys are sometimes referred to as shortcut keys because of their ability to easily trigger an action (such as launching a program or keyboard macro). In the following example, the hotkey Win+N is configured to launch Notepad. The pound sign stands for Win, which is known as a modifier key:

#n::
Run Notepad
return

In the final line above, serves to finish the hotkey. However, if a hotkey needs to execute only a single line, that line can be listed to the right of the double-colon. In other words, the is implicit:

#n::Run Notepad

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

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

Mouse

General Buttons

Name Description
LButton The left mouse button when used with Send, but the primary mouse button when used with hotkeys. In other words, if the user has swapped the buttons via system settings, is physically activated by clicking the right mouse button, but performs the same as physically clicking the left button. To always perform a logical left click, use or .
RButton The right mouse button when used with Send, but the secondary mouse button when used with hotkeys. In other words, if the user has swapped the buttons via system settings, is physically activated by clicking the left mouse button, but performs the same as physically clicking the right button. To always perform a logical right click, use or .
MButton Middle or wheel mouse button

Advanced Buttons

Name Description
XButton1 4th mouse button. Typically performs the same function as Browser_Back.
XButton2 5th mouse button. Typically performs the same function as Browser_Forward.

Wheel

Name Description
WheelDown Turn the wheel downward (toward you).
WheelUp Turn the wheel upward (away from you).
WheelLeftWheelRight

: Scroll to the left or right.

Requires Windows Vista or later. These can be with some (but not all) mice which have a second wheel or support tilting the wheel to either side. In some cases, software bundled with the mouse must instead be used to control this feature. Regardless of the particular mouse, Send and Click can be used to scroll horizontally in programs which support it.

Other Features

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

Overriding Explorer’s hotkeys: Windows’ built-in hotkeys such as Win+E (#e) and Win+R (#r) can be individually overridden simply by assigning them to an action in the script. See the override page for details.

Substitutes for Alt-Tab: Hotkeys can provide an alternate means of alt-tabbing. For example, the following two hotkeys allow you to alt-tab with your right hand:

RControl & RShift::AltTab  ; Hold down right-control then press right-shift repeatedly to move forward.
RControl & Enter::ShiftAltTab  ; Without even having to release right-control, press Enter to reverse direction.

For more details, see .

Основные возможности

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

Плюсы и минусы

Плюсы:

  • автоматический запуск практически любых операций на ПК;
  • встроенный скриптовый язык;
  • переназначение любых клавиш;
  • поддержка разных устройств для вывода.

Минусы:

некоторые сложности в освоении.

Похожие программы

Auto-Clicker. Программа для запоминания и последующего воспроизведения всех действий компьютерной мыши. Записанные действия в ней можно повторять произвольное количество раз, настраивая скорость их воспроизведения.

Macro Recorder. Приложение, которое может автоматизировать все рутинные процессы на компьютере. С его помощью можно создавать макросы, которые будут самостоятельно запускать необходимые программы, выполнять клики мышкой, вводить текст и т. д.

Как пользоваться приложением

Для того чтобы с помощью программы назначить автоматическое выполнение какого-либо действия, нужно создать скрипт. Он представляет собой всплывающее окно с пометкой «Я рогалег». С этой целью используем команду MsgBox, которую можно вызвать любым текстом. Надпись и команду необходимо вписать в любой текстовый редактор, так как сама программа как такового отдельного окна не имеет. Далее сохраняем файл, обязательно указав для него расширение «ahk». Скрипт будет выполнен при нажатии на него двойным щелчком.

Выполнение скрипта

При запуске скрипта появится значок «Autohotkey». Нажав на него правой кнопкой, вы сможете выбрать необходимые команды.

Выбор команд

Код, который должен автоматически выполняться при запуске скрипта, помещается вверху файла. Идентификаторы нужно указывать для горячих клавиш.
Рассмотрим, как это действует, на примере назначения автоматического запуска блокнота Notepad++ при нажатии определенных клавиш.
Для начала набираем «#n:: Run notepad++» и сохраняем файл. Дважды щелкаем по нему и набираем команду «Win+n». В области уведомления появится значок, а программа будет запущена при нажатии указанной комбинации клавиш.
В команде значок «#n» определяет кнопки, «::» — разделяет обозначения самих клавиш от команд. Остальные базовые кнопки обозначаются таким образом:

Обозначения кнопок

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

Main Window

The script’s main window is usually hidden, but can be shown via the or one of the commands listed below to gain access to information useful for debugging the script. Items under the View menu control what the main window displays:

  • Lines most recently executed — See ListLines.
  • Variables and their contents — See ListVars.
  • Hotkeys and their methods — See ListHotkeys.
  • Key history and script info — See KeyHistory.

Known issue: Keyboard shortcuts for menu items do not work while the script is displaying a message box or other dialog.

The built-in variable contains the unique ID (HWND) of the script’s main window.

Closing this window with WinClose (even from another script) causes the script to exit, but most other methods just hide the window and leave the script running.

Minimizing the main window causes it to automatically be hidden. This is done to prevent any owned windows (such as GUI windows or certain dialog windows) from automatically being minimized, but also has the effect of hiding the main window’s taskbar button. To instead allow the main window to be minimized normally, override the default handling with OnMessage. For example:

; This prevents the main window from hiding on minimize:
OnMessage(0x0112, Func("PreventAutoMinimize")) ; WM_SYSCOMMAND = 0x0112
OnMessage(0x0005, Func("PreventAutoMinimize")) ; WM_SIZE = 0x0005
; This prevents owned GUI windows (but not dialogs) from automatically minimizing:
OnMessage(0x0018, Func("PreventAutoMinimize"))

PreventAutoMinimize(wParam, lParam, uMsg, hwnd) {
    if (uMsg = 0x0112 && wParam = 0xF020 && hwnd = A_ScriptHwnd) { ; SC_MINIMIZE = 0xF020
        WinMinimize
        return 0 ; Prevent main window from hiding.
    }
    if (uMsg = 0x0005 && wParam = 1 && hwnd = A_ScriptHwnd) ; SIZE_MINIMIZED = 1
        return 0 ; Prevent main window from hiding.
    if (uMsg = 0x0018 && lParam = 1) ; SW_PARENTCLOSING = 1
        return 0 ; Prevent owned window from minimizing.
}

Main Window Title

The title of the script’s main window is used by the #SingleInstance and Reload mechanisms to identify other instances of the same script. Changing the title prevents the script from being identified as such. The default title depends on how the script was loaded:

Loaded From Title Expression Example
.ahk file E:\My Script.ahk — AutoHotkey v1.1.33.09
Main resource (compiled script) E:\My Script.exe
Any other resource E:\My AutoHotkey.exe — *BUILTIN-TOOL.AHK

The following code illustrates how the default title could be determined by the script itself (but the actual title can be retrieved with WinGetTitle):

title := A_ScriptFullPath
if !A_IsCompiled
    title .= " - AutoHotkey v" A_AhkVersion
; For the correct result, this must be evaluated by the resource being executed,
; not an #include (unless the #include was merged into the script by Ahk2Exe):
else if SubStr(A_LineFile, 1, 1) = "*" && A_LineFile != "*#1"
    title .= " - " A_LineFile
Добавить комментарий

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

Adblock
detector