Аутохотки — autohotkey последняя версия 1.0.44.07

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

При необходимости вы можете сделать так, чтобы программа автоматически нажимала специальные клавиши, такие как «Ctrl», «Shift» и «Alt». К примеру, используя команду «Send ^с!{tab}», вы делаете так, чтобы программа использовала автоматическую вставку, а потом сразу же переключалась на другое окно.

Символ «^» в данном случае указывает программе использовать сначала клавишу «Ctrl», в то время как «!» представляет собой клавишу «Alt». Соответственно, команда «{tab}», как и говорилось выше, дает программе установку использовать кнопку «Tab». Чтобы не вызвать никаких проблем и конфликтов в процессе работы программы, вам следует использовать кириллицу, так как клавиши будут чаще всего совпадать с нынешней раскладкой клавиатуры.

Более подробно ознакомиться со списком специальных символов вы сможете непосредственно через меню «Справка» в самой программе.

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

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

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

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.

Special modes

The following modes affect the interpretation of the characters in Keys or the behavior of key-sending commands such as Send, SendInput, SendPlay, SendEvent and ControlSend. These modes must be specified as in Keys, where x is either Raw, Text, or Blind. For example, .

Raw mode

The Raw mode can be either enabled with , SendRaw or ControlSendRaw, which causes all subsequent characters, including the special characters , to be interpreted literally rather than translating to Enter, to Ctrl+C, etc. For example, both and send instead of Tab.

The Raw mode does not affect the interpretation of escape sequences, and . For example, sends the string . When using ControlSend, it is also necessary to escape literal commas ().

Text mode

The Text mode can be enabled with , which is similar to the Raw mode, except that no attempt is made to translate characters (other than , , and ) to keycodes; instead, the 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. This mode can be combined with the Blind mode to avoid releasing any modifier keys: . However, some applications require that the modifier keys be released.

, and are all translated to a single Enter, unlike the default behavior and Raw mode, which translate to two Enter. is translated to Tab and to Backspace, but all other characters are sent without translation.

: Like the Blind mode, the Text mode ignores SetStoreCapsLockMode (that is, the state of CapsLock is not changed) and does not . This is because the Text mode typically does not depend on the state of CapsLock and cannot trigger the system Win+L hotkey. However, this only applies when Keys begins with or .

Blind mode

The Blind mode can be enabled with , which gives the script more control by disabling a number of things that are normally done automatically to make things work as expected. must be the first item in the string to enable the Blind mode. It has the following effects:

  • The Blind mode avoids releasing the modifier keys (Alt, Ctrl, Shift, and Win) if they started out in the down position. For example, the hotkey would send ABC rather than abc because the user is holding down Shift.
  • Modifier keys are restored differently to allow a Send to turn off a hotkey’s modifiers even if the user is still physically holding them down. For example, automatically pushes Ctrl back down if the user is still physically holding Ctrl, whereas allows Ctrl to be logically up even though it is physically down.
  • SetStoreCapsLockMode is ignored; that is, the state of CapsLock is not changed.
  • Menu masking is disabled. That is, Send omits the extra keystrokes that would otherwise be sent in order to prevent: 1) Start Menu appearance during Win keystrokes (LWin/RWin); 2) menu bar activation during Alt keystrokes. However, the Blind mode does not prevent masking performed by the keyboard hook following activation of a hook hotkey.
  • Send does not wait for Win to be released even if the text contains an L keystroke. This would normally be done to prevent Send from triggering the system «lock workstation» hotkey (Win+L). See for details.

The Blind mode is used internally when remapping a key. For example, the remapping would produce: 1) «b» when you type «a»; 2) uppercase «B» when you type uppercase «A»; and 3) Ctrl+B when you type Ctrl+A.

is not supported by SendRaw or ControlSendRaw; use instead.

The Blind mode is not completely supported by , especially when dealing with the modifier keys (Ctrl, Alt, Shift, and Win).

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

Установка AutoHotkey

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

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

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

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

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

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

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

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

Special Keys

If your keyboard or mouse has a key not listed above, you might still be able to make it a hotkey by using the following steps:

  1. Ensure that at least one script is running that is using the keyboard hook. You can tell if a script has the keyboard hook by opening its main window and selecting «View->Key history» from the menu bar.
  2. Double-click that script’s tray icon to open its main window.
  3. Press one of the «mystery keys» on your keyboard.
  4. Select the menu item «View->Key history»
  5. Scroll down to the bottom of the page. Somewhere near the bottom are the key-down and key-up events for your key. NOTE: Some keys do not generate events and thus will not be visible here. If this is the case, you cannot directly make that particular key a hotkey because your keyboard driver or hardware handles it at a level too low for AutoHotkey to access. For possible solutions, see further below.
  6. If your key is detectable, make a note of the 3-digit hexadecimal value in the second column of the list (e.g. 159).
  7. To define this key as a hotkey, follow this example:
    SC159:: ; Replace 159 with your key's value.
    MsgBox, %A_ThisHotkey% was pressed.
    return

Reverse direction: To remap some other key to become a «mystery key», follow this example:

; Replace 159 with the value discovered above. Replace FF (if needed) with the
; key's virtual key, which can be discovered in the first column of the Key History screen.
#c::Send {vkFFsc159} ; See  for more details.

Alternate solutions: If your key or mouse button is not detectable by the Key History screen, one of the following might help:

  1. Reconfigure the software that came with your mouse or keyboard (sometimes accessible in the Control Panel or Start Menu) to have the «mystery key» send some other keystroke. Such a keystroke can then be defined as a hotkey in a script. For example, if you configure a mystery key to send Ctrl+F1, you can then indirectly make that key as a hotkey by using in a script.

  2. Try AHKHID. You can also try searching the forum for a keywords like , or .

  3. The following is a last resort and generally should be attempted only in desperation. This is because the chance of success is low and it may cause unwanted side-effects that are difficult to undo:
    Disable or remove any extra software that came with your keyboard or mouse or change its driver to a more standard one such as the one built into the OS. This assumes there is such a driver for your particular keyboard or mouse and that you can live without the features provided by its custom driver and software.

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.

1 — The Basics

Before we begin our journey, let me give some advice. Throughout this tutorial you will see a lot of text and a lot of code. For optimal learning power, it is advised that you read the text and try the code. Then, study the code. You can copy and paste most examples on this page. If you get confused, try reading the section again.

a. Downloading and installing AutoHotkey

Since you’re viewing this documentation locally, you’ve probably already installed AutoHotkey and can skip to section b.

Before learning to use AutoHotkey (AHK), you will need to download it. After downloading it, you may possibly need to install it. But that depends on the version you want. For this guide we will use the Installer since it is easiest to set up.

Text instructions:

  1. Go to the AutoHotkey Homepage: https://www.autohotkey.com/
  2. Click Download: https://www.autohotkey.com/download/ahk-install.exe
  3. During installation of AutoHotkey, you will be asked to choose from UNICODE or ANSI. In short, you would probably want to choose UNICODE. It has support for non-English letters and numbers (characters). Keep going until you see an Install button.
  4. Once done, great! Continue on to section b.

For a video instruction, watch
Install and Hello World on YouTube.

b. How to create a script

Once you have AutoHotkey installed, you will probably want it to do stuff. AutoHotkey is not magic, we all wish it was, but it is not. So we will need to tell it what to do. This process is called «Scripting».

Text instructions:

  1. Right-Click on your desktop.
  2. Find «New» in the menu.
  3. Click «AutoHotkey Script» inside the «New» menu.
  4. Give the script a new name. It must end with a .ahk extension. For example: MyScript.ahk
  5. Find the newly created file on your desktop and right-click it.
  6. Click «Edit Script».
  7. A window should have popped up, probably Notepad. If so, SUCCESS!

    So now that you have created a script, we need to add stuff into the file. For a list of all built-in commands, function and variables, see .

    Here is a very basic script containing a hotkey which types text using the Send command when the hotkey is pressed:

    ^j::
    Send, My First Script
    return

    We will get more in-depth later on. Until then, here’s an explanation of the above code:

    • The first line: is the hotkey. means Ctrl, is the letter J. Anything to the left of are the keys you need to press.
    • The second line: is how you send keystrokes. is the command, anything after the comma (,) will be typed.
    • The third line: . This will become your best friend. It literally stops code from going any further, to the lines below. This will prevent many issues when you start having a lot of stuff in your scripts.
  8. Save the File.
  9. Double-click the file/icon in the desktop to run it. Open notepad or (anything you can type in) and press Ctrl and J.
  10. Hip Hip Hooray! Your first script is done. Go get some reward snacks then return to reading the rest of this tutorial.

For a video instruction, watch Install and Hello World on YouTube.

c. You cannot merge commands

When you are making your code, you might have the urge to put several commands on the same line or inside of each other, don’t. we’ll talk about why it doesn’t work as you might expect and what you can do instead.

d. How to find the help file on your computer

There are a few ways to do this, I’ll assume you have it installed to the default locations:

Method 1:

  1. Find the Start menu or Start Orb on your screen, usually in the lower left.
  2. Click Programs or All Programs.
  3. Find AutoHotkey in the list.
  4. You should then see AutoHotkey Help File. Click it.
  5. Done!

Method 2:

  1. Go to your desktop.
  2. Find My Computer or Computer. Open it.
  3. Go into your harddrive that contains AutoHotkey. Probably C:\ drive.
  4. Search within all Program Files folders for AutoHotkey.
  5. Look for AutoHotkey.chm or a file that says AutoHotkey and has a yellow question mark on it.
  6. Done!

4 — Running Programs & Websites

mspaint.exe, calc.exe, script.ahkRunhttps://www.autohotkey.com/

; Run a program. Note that most programs will require a FULL file path:
Run, %A_ProgramFiles%\Some_Program\Program.exe

; Run a website:
Run, https://www.autohotkey.com

There are some other advanced features as well, such as command line parameters and CLSID. If you want to learn more about that stuff, visit the Run page.

Here are a few more samples:

; Several programs do not need a full path, such as Windows-standard programs:
Run, notepad.exe
Run, mspaint.exe

; Run the "My Documents" folder using a :
Run, %A_MyDocuments%

; Run some websites:
Run, https://www.autohotkey.com
Run, https://www.google.com

For more in-depth information and examples, check out the Run page.

SendInput [v1.0.43+]

SendInput is generally the preferred method to send keystrokes and mouse clicks because of its superior speed and reliability. Under most conditions, SendInput is nearly instantaneous, even when sending long strings. Since SendInput is so fast, it is also more reliable because there is less opportunity for some other window to pop up unexpectedly and intercept the keystrokes. Reliability is further improved by the fact that anything the user types during a SendInput is postponed until afterward.

Unlike the other sending modes, the operating system limits SendInput to about 5000 characters (this may vary depending on the operating system’s version and performance settings). Characters and events beyond this limit are not sent.

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

If a script other than the one executing SendInput has a low-level keyboard hook installed, SendInput automatically reverts to (or if is in effect). This is done because the presence of an external hook disables all of SendInput’s advantages, making it inferior to both SendPlay and SendEvent. However, since SendInput is unable to detect a low-level hook in programs other than , it will not revert in these cases, making it less reliable than SendPlay/Event.

When SendInput sends mouse clicks by means such as , and is in effect (the default), every click will be relative to the window that was active at the start of the send. Therefore, if SendInput intentionally activates another window (by means such as alt-tab), the coordinates of subsequent clicks within the same command will be wrong because they will still be relative to the old window rather than the new one.

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.

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.

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.

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

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

Adblock
detector