Autohotkey script showcase

Moving the Mouse Cursor via the Keyboard

The keyboard can be used to move the mouse cursor as demonstrated by the fully-featured . Since that script offers smooth cursor movement, acceleration, and other features, it is the recommended approach if you plan to do a lot of mousing with the keyboard. By contrast, the following example is a simpler demonstration:

*#up::MouseMove, 0, -10, 0, R  ; Win+UpArrow hotkey => Move cursor upward
*#Down::MouseMove, 0, 10, 0, R  ; Win+DownArrow => Move cursor downward
*#Left::MouseMove, -10, 0, 0, R  ; Win+LeftArrow => Move cursor to the left
*#Right::MouseMove, 10, 0, 0, R  ; Win+RightArrow => Move cursor to the right

*<#RCtrl::  ; LeftWin + RightControl => Left-click (hold down Control/Shift to Control-Click or Shift-Click).
SendEvent {Blind}{LButton down}
KeyWait RCtrl  ; Prevents keyboard auto-repeat from repeating the mouse click.
SendEvent {Blind}{LButton up}
return

*<#AppsKey::  ; LeftWin + AppsKey => Right-click
SendEvent {Blind}{RButton down}
KeyWait AppsKey  ; Prevents keyboard auto-repeat from repeating the mouse click.
SendEvent {Blind}{RButton up}
return

5 — Commands vs. Functions()

AutoHotkey has two main types of things used by the scripter to create code: Commands and functions.

A list of all commands and built-in functions can be found here.

Commands

You can tell what a command is by looking at its syntax (the way it looks). Commands do not use parentheses around the parameters like functions do. So a command would look like this:

Command, Parameter1, Parameter2, Parameter3

When using commands, you cannot squish other commands onto the same line as a previous command (exception: IfEqual). You cannot put commands inside the parameters of other commands. For example:

MsgBox, Hello Run, notepad.exe   ; Wrong
MsgBox, Hello, Run, notepad.exe  ; Wrong

MsgBox, Hello      ; Correct
Run, notepad.exe

need

You can do math in parameters if you force an expression with a single , but that will not be covered.

Functions

As stated above, functions are different because they use parentheses. A typical function looks like:

Function(Parameter1, Parameter2, Parameter3)

Functions have a few main differences:

  1. You can do math in them:
    SubStr(37 * 12, 1, 2)
    SubStr(A_Hour - 12, 2)
  2. Variables do not need to be wrapped in percent signs:
    SubStr(A_Now, 7, 2)
  3. Functions can go inside of functions:
    SubStr(A_AhkPath, InStr(A_AhkPath, "AutoHotkey"))
  4. Text needs to be wrapped in quotes:
    SubStr("I'm scripting, awesome!", 16)

A function usually return a value differently than a command does. Commands need an OutputVar parameter, functions do not. The most common way assigning the value of a function to a variable is like so:

MyVar := SubStr("I'm scripting, awesome!", 16)

This isn’t the only way, but the most common. You are using to store the return value of the function that is to the right of the operator. See Functions for more details.

In short:

; These are commands:
MsgBox, This is some text.
StringReplace, Output, Input, AutoHotkey, AutoHotKey, All
SendInput, This is awesome{!}{!}{!}

; These are functions:
SubStr("I'm scripting, awesome!", 16)
FileExist(VariableContainingPath)
Output := SubStr("I'm scripting, awesome!", 16)

a. Code blocks

Code blocks are lines of code surrounded by little curly brackets ( and ). They group a section of code together so that AutoHotkey knows it’s one big family and that it needs to stay together. They are most often used with functions and control flow statements such as If and Loop. Without them, only the first line in the block is called.

In the following code, both lines are run only if MyVar equals 5:

if (MyVar = 5)
{
    MsgBox, MyVar equals %MyVar%!!
    ExitApp
}

In the following code, the message box is only shown if MyVar equals 5. The script will always exit, even if MyVar is not 5:

if (MyVar = 5)
    MsgBox, MyVar equals %MyVar%!!
    ExitApp

This is perfectly fine since the if-statement only had one line of code associated with it. It’s exactly the same as above, but I outdented the second line so we know it’s separated from the if-statement:

if (MyVar = 5)
    MsgBox, MyVar equals %MyVar%!!
MsgBox, We are now 'outside' of the if-statement. We did not need curly brackets since there was only one line below it.

Improvements to Icon Support

Unusual Sizes

Icon resources of any size supported by the operating system may be extracted from executable files. When multiple sized icon resources exist within an icon group, the most appropriate size is used. Prior to revision 17, an arbitrary icon resource was selected by the system, scaled to the system large icon size, then scaled back to the requested size.

Resource Identifiers

Negative icon numbers may be used to identify a group icon resource within an executable file. For example, the following sets the tray icon to the default icon used by ahk files:

Menu, Tray, Icon, %A_AhkPath%, -160

Short-circuit Boolean Evaluation

When AND, OR, and the are used within an , they short-circuit to enhance performance (regardless of whether any function calls are present). Short-circuiting operates by refusing to evaluate parts of an expression that cannot possibly affect its final result. To illustrate the concept, consider this example:

if (ColorName != "" AND not FindColor(ColorName))
    MsgBox %ColorName% could not be found.

In the example above, the FindColor() function never gets called if the ColorName variable is empty. This is because the left side of the AND would be false, and thus its right side would be incapable of making the final outcome true.

Because of this behavior, it’s important to realize that any side-effects produced by a function (such as altering a global variable’s contents) might never occur if that function is called on the right side of an AND or OR.

It should also be noted that short-circuit evaluation cascades into nested ANDs and ORs. For example, in the following expression, only the leftmost comparison occurs whenever ColorName is blank. This is because the left side would then be enough to determine the final answer with certainty:

if (ColorName = "" OR FindColor(ColorName, Region1) OR FindColor(ColorName, Region2))
    break   ; Nothing to search for, or a match was found.

As shown by the examples above, any expensive (time-consuming) functions should generally be called on the right side of an AND or OR to enhance performance. This technique can also be used to prevent a function from being called when one of its parameters would be passed a value it considers inappropriate, such as an empty string.

: The also short-circuits by not evaluating the losing branch.

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.

Скрипты 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:

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

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, в том числе о том, как улучшить Windows с помощью специальных скриптов AHK.

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

,

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

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

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

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

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

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

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

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

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.

Hotkeys, Hotstrings, and Remapping

How do I put my hotkeys and hotstrings into effect automatically every time I start my PC?

There are several ways to make a script (or any program) launch automatically every time you start your PC. The easiest is to place a shortcut to the script in the Startup folder:

  1. Find the script file, select it, and press Ctrl+C.
  2. Press Win+R to open the Run dialog, then enter and click OK or Enter. This will open the Startup folder for the current user. To instead open the folder for all users, enter (however, in that case you must be an administrator to proceed).
  3. Right click inside the window, and click «Paste Shortcut». The shortcut to the script should now be in the Startup folder.

I’m having trouble getting my mouse buttons working as hotkeys. Any advice?

The left and right mouse buttons should be assignable normally (for example, is the Win+LeftButton hotkey). Similarly, the middle button and the turning of the mouse wheel should be assignable normally except on mice whose drivers directly control those buttons.

The fourth button (XButton1) and the fifth button (XButton2) might be assignable if your mouse driver allows their clicks to be seen by the system. If they cannot be seen — or if your mouse has more than five buttons that you want to use — you can try configuring the software that came with the mouse (sometimes accessible in the Control Panel or Start Menu) to send a keystroke whenever you press one of these buttons. Such a keystroke can then be defined as a hotkey in a script. For example, if you configure the fourth button to send Ctrl+F1, you can then indirectly configure that button as a hotkey by using in a script.

If you have a five-button mouse whose fourth and fifth buttons cannot be seen, you can try changing your mouse driver to the default driver included with the OS. This assumes there is such a driver for your particular mouse and that you can live without the features provided by your mouse’s custom software.

How do I detect the double press of a key or button?

Use as follows:

~Ctrl::
    if (A_ThisHotkey = A_PriorHotkey && A_TimeSincePriorHotkey < 200)
        MsgBox double-press
return

How can a hotkey or hotstring be made exclusive to certain program(s)? In other words, I want a certain key to act as it normally does except when a specific window is active.

The preferred method is #IfWinActive. For example:

#IfWinActive, ahk_class Notepad
^a::MsgBox You pressed Control-A while Notepad is active.

How can a prefix key be made to perform its native function rather than doing nothing?

Consider the following example, which makes Numpad0 into a prefix key:

Numpad0 & Numpad1::MsgBox, You pressed Numpad1 while holding down Numpad0.

Now, to make Numpad0 send a real Numpad0 keystroke whenever it wasn’t used to launch a hotkey such as the above, add the following hotkey:

 $Numpad0::Send, {Numpad0}

The $ prefix is needed to prevent a warning dialog about an infinite loop (since the hotkey «sends itself»). In addition, the above action occurs at the time the key is released.

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 .

Installer Options

To silently install AutoHotkey into the default directory (which is the same directory displayed by non-silent mode), pass the parameter /S to the installer. For example:

AutoHotkey110800_Install.exe /S

A directory other than the default may be specified via the /D parameter (in the absence of /S, this changes the default directory displayed by the installer). For example:

AutoHotkey110800_Install.exe /S /D=C:\Program Files\AutoHotkey

Version: If AutoHotkey was previously installed, the installer automatically detects which version of AutoHotkey.exe to set as the default. Otherwise, the default is Unicode 32-bit or Unicode 64-bit depending on whether the OS is 64-bit. To override which version of AutoHotkey.exe is set as the default, pass one of the following switches:

  • or : ANSI 32-bit.
  • or : Unicode 64-bit (only valid on 64-bit systems).
  • : Unicode 32-bit.

For example, the following installs silently and sets ANSI 32-bit as the default:

AutoHotkey110800_Install.exe /S /A32

Uninstall: To silently uninstall AutoHotkey, pass the parameter to Installer.ahk. For example:

"C:\Program Files\AutoHotkey\AutoHotkey.exe" "C:\Program Files\AutoHotkey\Installer.ahk" /Uninstall

For AutoHotkey versions older than 1.1.08.00, use . For example:

"C:\Program Files\AutoHotkey\uninst.exe" /S

Note: Installer.ahk must be run as admin to work correctly.

Extract: Later versions of the installer include a link in the bottom-right corner to extract setup files without installing. If this function is present, the switch can be used to invoke it from the command line. For example:

AutoHotkey110903_Install.exe /D=F:\AutoHotkey /E

Restart scripts : In silent install/uninstall mode, running scripts are closed automatically, where necessary. Pass the switch to automatically reload these scripts using whichever EXE they were running on, without command line args. Setup will attempt to launch the scripts via Explorer, so they do not run as administrator if UAC is enabled.

Taskbar buttons : On Windows 7 and later, taskbar buttons for multiple scripts are automatically grouped together or combined into one button by default. The Separate taskbar buttons option disables this by registering each AutoHotkey executable as a .

: For command-line installations, specify or to enable the option and to disable it.

Run with UI Access

The installer GUI has an option «Add ‘Run with UI Access’ to context menus». This context menu option provides a workaround for common by allowing the script to automate administrative programs — without the script running as admin. To achieve this, the installer does the following:

  • Copies AutoHotkeyA32.exe, AutoHotkeyU32.exe and (if present) AutoHotkeyU64.exe to AutoHotkey*_UIA.exe.
  • Sets the uiAccess attribute in each UIA file’s embedded manifest.
  • Creates a self-signed digital certificate named «AutoHotkey» and signs each UIA file.
  • Registers the context menu option to run the appropriate exe file.

If any these UIA files are present before installation, the installer will automatically update them even if the UI Access option is not enabled.

For command-line installations, specify or to enable the option and to disable it. By default, the installer will enable the option if UAC is enabled and the UI Access context menu option was present before installation.

Scripts which need to run other scripts with UI access can simply Run the appropriate UIA.exe file with the normal .

Known limitations:

  • UIA is only effective if the file is in a trusted location; i.e. a Program Files sub-directory.
  • UIA.exe files created on one computer cannot run on other computers without first installing the digital certificate which was used to sign them.
  • UIA.exe files cannot be started via CreateProcess due to security restrictions. ShellExecute can be used instead. Run tries both.
  • UIA.exe files cannot be modified, as it would invalidate the file’s digital signature.
  • Because UIA programs run at a different «integrity level» than other programs, they can only access objects registered by other UIA programs. For example, will fail because Word is not marked for UI Access.
  • The script’s own windows can’t be automated by non-UIA programs/scripts for security reasons.
  • Running a non-UIA script which uses a mouse hook (even as simple as ) may prevent all mouse hotkeys from working when the mouse is pointing at a window owned by a UIA script, even hotkeys implemented by the UIA script itself. A workaround is to ensure UIA scripts are loaded last.

For more details, see Enable interaction with administrative programs on the archive forum.

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

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.

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.

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
Добавить комментарий

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

Adblock
detector