Что такое ahk и для чего его используют? как скачать и установить этот язык программирования?

6 — Variables

Variables are like little post-it notes that hold some information. They can be used to store text, numbers, data from functions and commands or even mathematical equations. Without them, programming and scripting would be much more tedious.

Variables can be assigned a few ways. We’ll cover the most common forms. Please pay attention to the equal sign ().

Legacy text assignment
MyVar = Text

This is the simplest form for a variable, a legacy assignment. Simply type in your text and done.

Legacy variable assignment
MyVar = %MyVar2%

Same as above, but you are assigning a value of a variable to another variable.

Legacy mixed assignment
MyVar = %MyVar2% some text %MyVar3%.

A combination of the two legacy assignments above.

Expression text assignment
MyVar := "Text"

This is an expression assignment, due to the before the . Any text needs to be in quotes.

Expression variable assignment
MyVar := MyVar2

In expression mode, variables do not need percent signs.

Expression number assignment
MyVar := 6 + 8 / 3 * 2 - Sqrt(9)

Thanks to expressions, you can do math!

Expression mixed assignment
MyVar := "The value of 5 + " MyVar2 " is: " 5 + MyVar2

A combination of the three expression assignments above.

Equal signs (=) with a symbol in front of it such as etc. are called assignment operators and always require an expression.

a. When to use percents

One of the most common issues with AutoHotkey involving variables is when to use the percent signs (%). Hopefully this will clear some confusion.

When to use percent signs:

  • When you are using commands (see above), except when the parameter is OutputVar or InputVar.
  • When you are assigning a value to a variable using the legacy mode (an equal sign with no symbol in front of it).

When not to use percent signs:

  • In parameters that are input or output variables. For example:
  • On the left side of an assignment:
  • On the left side of legacy (non-expression) if-statements:
  • Everywhere in expressions. For example:
      if (Var1 != Var2)
      Var1 := Var2 + 100

b. Getting user input

Sometimes you want to have the user to choose the value of stuff. There are several ways of doing this, but the simplest way is InputBox. Here is a simple example on how to ask the user a couple of questions and doing some stuff with what was entered:

InputBox, OutputVar, Question 1, What is your first name?
if (OutputVar = "Bill")
    MsgBox, That's an awesome name`, %OutputVar%.

InputBox, OutputVar2, Question 2, Do you like AutoHotkey?
if (OutputVar2 = "yes")
    MsgBox, Thank you for answering %OutputVar2%`, %OutputVar%! We will become great friends.
else
    MsgBox, %OutputVar%`, That makes me sad.

c. Other Examples?

MsgBox, 4,, Would you like to continue?
IfMsgBox, No
    return  ; If No, stop the code from going further.
MsgBox, You pressed YES.  ; Otherwise, the user picked yes.
; Some examples showing when to use percents and when not:
Var = Text  ; Assign some text to a variable (legacy).
Number := 6  ; Assign a number to a variable (expression).
Var2 = %Var%  ; Assign a variable to another (legacy).
Var3 := Var  ; Assign a variable to another (expression).
Var4 .= Var  ; Append a variable to the end of another (expression).
Var5 += Number  ; Add the value of a variable to another (expression).
Var5 -= Number  ; Subtract the value of a variable from another (expression).
Var6 := SubStr(Var, 2, 2)  ; Variable inside a function. This is always an expression.
Var7 = %Var% Text  ; Assigns a variable to another with some extra text (legacy).
Var8 := Var " Text"  ; Assigns a variable to another with some extra text (expression).
MsgBox, %Var%  ; Variable inside a command. 
StringSplit, Var, Var, x  ; Variable inside a command that uses InputVar and OutputVar.
if (Number = 6)  ; Whenever an IF has parentheses, it'll be an expression. So no percent signs.
if (Var != Number)  ; Whenever an IF has parentheses, it'll be an expression. So no percent signs.
if Number = 6  ; Without parentheses, the IF is legacy. However, only variables on the 'right side' need percent signs. 
if Var1 < %Var2%  ; Without parentheses, the IF is legacy. However, only variables on the 'right side' need percent signs.

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!

Remapping via the Registry’s «Scancode Map»

Advantages:

  • Registry remapping is generally more pure and effective than . For example, it works in a broader variety of games, it has no known , and it is capable of firing AutoHotkey’s hook hotkeys (whereas AutoHotkey’s remapping requires a ).
  • If you choose to make the registry entries manually (explained below), absolutely no external software is needed to remap your keyboard. Even if you use KeyTweak to make the registry entries for you, KeyTweak does not need to stay running all the time (unlike AutoHotkey).

Disadvantages:

  • Registry remapping is relatively permanent: a reboot is required to undo the changes or put new ones into effect.
  • Its effect is global: it cannot create remappings specific to a particular user, application, or locale.
  • It cannot send keystrokes that are modified by Shift, Ctrl, Alt, or AltGr. For example, it cannot remap a lowercase character to an uppercase one.
  • It supports only the keyboard (AutoHotkey has and some limited joystick remapping).

How to Apply Changes to the Registry: There are at least two methods to remap keys via the registry:

  1. Use a program like KeyTweak (freeware) to visually remap your keys. It will change the registry for you.
  2. Remap keys manually by creating a .reg file (plain text) and loading it into the registry. This is demonstrated at

Context-sensitive Hotkeys

The directives #IfWinActive/Exist and #If can be used to make a hotkey perform a different action (or none at all) depending on a specific condition. For example:

#IfWinActive, ahk_class Notepad
^a::MsgBox You pressed Ctrl-A while Notepad is active. Pressing Ctrl-A in any other window will pass the Ctrl-A keystroke to that window.
#c::MsgBox You pressed Win-C while Notepad is active.

#IfWinActive
#c::MsgBox You pressed Win-C while any window except Notepad is active.

#If MouseIsOver("ahk_class Shell_TrayWnd") ; For MouseIsOver, see .
WheelUp::Send {Volume_Up}     ; Wheel over taskbar: increase/decrease volume.
WheelDown::Send {Volume_Down} ;

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.

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 .

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.

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.

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

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

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.

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

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.

Автоматизируйте ваши повторяющиеся задачи с помощью AutoHotkey

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

Умение создавать собственные сценарии AutoHotkey также является отличным навыком, хотя стоит проверить руководство по сочетанию клавиш Windows Ultimate.

Сочетания клавиш Windows 101: полное руководство

Сочетания клавиш Windows 101: полное руководствоСочетания клавиш могут сэкономить часы времени. Освойте универсальные сочетания клавиш Windows, приемы клавиатуры для конкретных программ и несколько других советов, чтобы ускорить вашу работу.
Прочитайте больше
чтобы увидеть, если ярлык, который вы хотите сделать, уже существует!

Узнайте больше о: AutoHotkey, компьютерная автоматизация, сочетания клавиш.

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

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

Adblock
detector