Autohotkey

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.

Описание и возможности

Итак, что же это за приложение и для чего оно нужно? АвтоХоткей – это специальная утилита, которая воспроизводит заранее написанные скрипты или как еще их называют бинды. Рассмотрим основные и дополнительные возможности ПО, для того чтобы вы поняли его назначение:

  • Какой-либо горячей кнопкой или кликом мыши вы можете запустить заранее запрограммированный макрос, который, в свою очередь, выполнит целую серию событий.
  • На любые кнопки клавиатуры, игрового джойстика или мыши мы можем назначить отдельные макросы. При этом поддерживается не только обычный, но и двойной клик.
  • Собственный скриптовый язык позволяет, например, создать функционал для автоматической замены введенного текста.
  • Поддерживается переназначение клавиш на клавиатуре, мыши или игровом контролере.
  • Любой скрипт, который написал пользователь, может быть преобразован в обычной EXE-файл. Это позволит запускать его уже без участия программы AutoHotkey.

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

Commands

Feature Description
FileEncoding Sets the default encoding for FileRead, FileReadLine, Loop Read, FileAppend, and FileOpen().See also:
Gui See below.
IniRead/Write/Delete Read, write or delete entire sections, or retrieve a list of all section names.
Sets or removes a menu item’s icon.
Run were made to the way parameters are parsed.
Sends a Unicode character. Unicode characters may be used directly in Unicode builds.
SendLevel Controls which artificial keyboard and mouse events are ignored by hotkeys and hotstrings.
SetFormat, IntegerFast, h|H Set lower-case or upper-case hexadecimal format.
SetRegView, RegView Allows registry commands in a 32-bit script to access the 64-bit registry view and vice versa.
Perform code page or HTML transformations.
Retrieves the full path and name of the process that owns a given window.
Npm

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.

Custom Combinations

You can define a custom combination of two keys (except joystick buttons) by using » & » between them. In the below example, you would hold down Numpad0 then press the second key to trigger the hotkey:

Numpad0 & Numpad1::MsgBox You pressed Numpad1 while holding down Numpad0.
Numpad0 & Numpad2::Run Notepad

The prefix key loses its native function: In the above example, Numpad0 becomes a prefix key; but this also causes Numpad0 to lose its original/native function when it is pressed by itself. To avoid this, a script may configure Numpad0 to perform a new action such as one of the following:

Numpad0::WinMaximize A   ; Maximize the active/foreground window.
Numpad0::Send {Numpad0}  ; Make the release of Numpad0 produce a Numpad0 keystroke. See comment below.

Fire on release: The presence of one of the above custom combination hotkeys causes the release of Numpad0 to perform the indicated action, but only if you did not press any other keys while Numpad0 was being held down. : This behaviour can be avoided by applying the to either hotkey.

Modifiers: Unlike a normal hotkey, custom combinations act as though they have the modifier by default. For example, will activate even if Ctrl or Alt is held down when 1 and 2 are pressed, whereas would be activated only by Ctrl+1 and not Ctrl+Alt+1.

For standard modifier keys, normal hotkeys typically work as well or better than «custom» combinations. For example, is recommended over .

Combinations of three or more keys are not supported. Combinations which your keyboard hardware supports can usually be detected by using #If and , but the results may be inconsistent. For example:

; Press AppsKey and Alt in any order, then slash (/).
#if GetKeyState("AppsKey", "P")
Alt & /::MsgBox Hotkey activated.

; If the keys are swapped, Alt must be pressed first (use one at a time):
#if GetKeyState("Alt", "P")
AppsKey & /::MsgBox Hotkey activated.

;  & \::
#if GetKeyState("")
\::MsgBox

Keyboard hook: Custom combinations involving keyboard keys always use the keyboard hook, as do any hotkeys which use the prefix key as a suffix. For example, causes to always use the hook.

О языке

Возможности языка включают:

  • Совместимость с Windows XP / / Vista / / / 2008 R2 / / 8.1 / 2012 /
  • Версия для 64-битных систем.
  • Поддержка Юникода.
  • Запуск консольных приложений и доступ к стандартным потокам ввода-вывода.
  • Запуск программ от имени другого пользователя.
  • Компиляция скрипта в EXE файл.
  • Включение файлов в скомпилированный файл, которые можно извлекать при запуске.
  • Сжатие и защита исполняемого файла от декомпиляции.
  • Создание графических интерфейсов GUI, информационных сообщений, форм ввода информации.
  • Вызов функций из динамических библиотек и функций Windows API.
  • Работа с реестром Windows, буфером обмена, файлами (чтение, изменение, копирование, удаление).
  • Работа с объектами COM (Сomponent object modelling).
  • Перехват и эмуляция клавиатурных нажатий и кликов мышки.
  • Работа с окнами (особенно легко работать с графическими элементами из Windows): передвижение, скрытие, отображение, изменение размера, активизация, закрытие. К окнам можно обращаться по их заголовку, отображаемому тексту, размеру, расположению, классу, по внутренним дескрипторам (handle) Win32 API, определяемым с помощью входящей в комплект поставки утилиты WindowSpy.
  • Получение информации и взаимодействие с элементами управления (особенно стандартными): поле редактирования, переключатель, список, кнопки, статусная строка и т. д., в том числе неактивными.
  • Интернет: чтение HTML кода страниц и скачивание файлов, работа с FTP, отправка E-mail сообщений, работа с базами данных MySQL и SQLite.
  • Работа с протоколами TCP и UDP.
  • Автоматизация работы в браузерах: Internet Explorer, Opera, Firefox, Google Chrome.
  • Обычные элементы высокоуровневого языка, такие как работа с циклами, функциями и переменными.
  • Огромное количество функций для работы с текстом (как со строками и массивами данных, так и с отдельными символами), в том числе с регулярными выражениями в стиле Perl (используется библиотека PCRE).
  • Работа со звуком и музыкой.
  • Работа со сложными математическими, геометрическими и физическими расчётами (например, с тригонометрическими функциями).
  • Простой синтаксис.
  • AutoHotkey_H — объединённая версия в виде COM и DLL, позволяющая использовать возможности AHK в программах, написанных на других языках.
  • Оптимизация и автоматизация монотонных действий (удаление, перемещение временных файлов, очистка кэш-данных, скачивание файлов).

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

Для AutoHotkey существует интегрированная среда разработки под названием SciTE4AutoHotkey, основанный на бесплатном редакторе SciTE. Компилятор, вспомогательные утилиты и справочные материалы полностью интегрированы, что делает редактор стандартным окружением для разработчиков, использующих AHK. Компилятор AHK и среда разработки SciTE легко устанавливаются и в дополнительной настройке не нуждается.

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

Популярное использование AutoHotkey:

  • Разработка утилит для Microsoft Windows.
  • Мониторинг веб-сайтов, сетей.
  • Дефрагментация дисков и резервное копирование.
  • Переназначение клавиш, глобально или у отдельных программ
  • Управление мышкой с помощью клавиатуры или джойстика
  • Слежение за системой, автоматическое выполнение некоторых действий по желанию пользователя.
  • Создание ботов/читов/помощников/биндерам к играм. Боты позволяют автоматизировать некоторые действия в играх, в результате пользователь может быстрее добиться нужного результата.

Для упрощения разработки графических интерфейсов существует визуальный редактор SmartGUI Creator.

Исходный код AutoHotkey всех версий на языке С++ доступен для загрузки на GitHub.

Текущая версия языка доступна для скачивания на официальном сайте проекта, также как и предыдущие релизы.

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.

Mouse Wheel Hotkeys

Hotkeys that fire upon turning the mouse wheel are supported via the key names WheelDown and WheelUp. Here are some examples of mouse wheel hotkeys:

MButton & WheelDown::MsgBox You turned the mouse wheel down while holding down the middle button.
^!WheelUp::MsgBox You rotated the wheel up while holding down Control+Alt.

: WheelLeft and WheelRight are also supported, but have no effect on operating systems older than Windows Vista. Some mice have a single wheel which can be scrolled up and down or tilted left and right. Generally in those cases, WheelLeft or WheelRight signals are sent repeatedly while the wheel is held to one side, to simulate continuous scrolling. This typically causes the hotkeys to execute repeatedly.

: The built-in variable A_EventInfo contains the amount by which the wheel was turned, which is typically 1. However, A_EventInfo can be greater or less than 1 under the following circumstances:

  • If the mouse hardware reports distances of less than one notch, A_EventInfo may contain 0;
  • If the wheel is being turned quickly (depending on type of mouse), A_EventInfo may be greater than 1. A hotkey like the following can help analyze your mouse: .

Some of the most useful hotkeys for the mouse wheel involve alternate modes of scrolling a window’s text. For example, the following pair of hotkeys scrolls horizontally instead of vertically when you turn the wheel while holding down the left Ctrl:

~LControl & WheelUp::  ; Scroll left.
ControlGetFocus, fcontrol, A
Loop 2  ; <-- Increase this value to scroll faster.
    SendMessage, 0x0114, 0, 0, %fcontrol%, A  ; 0x0114 is WM_HSCROLL and the 0 after it is SB_LINELEFT.
return

~LControl & WheelDown::  ; Scroll right.
ControlGetFocus, fcontrol, A
Loop 2  ; <-- Increase this value to scroll faster.
    SendMessage, 0x0114, 1, 0, %fcontrol%, A  ; 0x0114 is WM_HSCROLL and the 1 after it is SB_LINERIGHT.
return

Finally, since mouse wheel hotkeys generate only down-events (never up-events), they cannot be used as .

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

Variables

Feature Description
A_Is64bitOS Contains 1 (true) if the OS is 64-bit or 0 (false) if it is 32-bit.
A_IsUnicode In Unicode builds, this variable contains 1 (true). In ANSI builds it is not defined, so is effectively false.
A_FileEncoding Contains the default encoding for various commands; see FileEncoding.
A_OSVersion Supports Windows 7 and Windows 8; see .
A_PriorKey The name of the last key which was pressed prior to the most recent key-press or key-release …
A_PtrSize Contains the size of a pointer, in bytes. This is either 4 (32-bit) or 8 (64-bit).
A_RegView The current registry view as set by SetRegView.
A_ScriptHwnd The unique ID (HWND/handle) of the script’s hidden main window.

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.

Установка AutoHotkey

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

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

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

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

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

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

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

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

Сила AutoHotkey

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

У вас не должно возникнуть проблем с использованием AHK! Мы писали о том, как это может помочь вам более эффективно играть в Path of Exile

и, скорее всего, это может помочь с вашей любимой игрой. Не геймер? Объедините это с существующими ярлыками Microsoft Office

и вы будете более продуктивны, чем когда-либо прежде!

Какие ваши любимые варианты использования AutoHotkey? Поделитесь своими любимыми сценариями с нами ниже, чтобы расширить список!

Имидж Кредит: проведение стоматологического оборудования FabrikaSimf через Shutterstock

Create a Script

There are a couple of common ways to create a script file:

  • In Notepad (or a of your choice), save a file with the filename extension. On some systems you may need to enclose the name in quotes to ensure the editor does not add another extension (such as .txt).

    Be sure to save the file as UTF-8 with BOM if it will contain non-ASCII characters. For details, see the .

  • In Explorer, right-click in empty space in the folder where you want to save the script, then select New and AutoHotkey Script. You can then type a name for the script (taking care not to erase the extension if it is visible).

See Scripting Language for details about how to write a script.

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.

The title of this 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 is equivalent to the expression .

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

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

Introduction and Simple Examples

A function is similar to a subroutine (Gosub) except that it can accept parameters (inputs) from its caller. In addition, a function may optionally return a value to its caller. Consider the following simple function that accepts two numbers and returns their sum:

Add(x, y)
{
    return x + y   ; "Return" expects an .
}

The above is known as a function definition because it creates a function named «Add» (not case sensitive) and establishes that anyone who calls it must provide exactly two parameters (x and y). To call the function, assign its result to a variable with the := operator. For example:

Var := Add(2, 3)  ; The number 5 will be stored in Var.

Also, a function may be called without storing its return value:

Add(2, 3)

But in this case, any value returned by the function is discarded; so unless the function produces some effect other than its return value, the call would serve no purpose.

Since a function call is an , any variable names in its parameter list should not be enclosed in percent signs. By contrast, literal strings should be enclosed in double quotes. For example:

if (MyVar, "fox")
    MsgBox The variable MyVar contains the word fox.

Finally, functions may be called in the parameters of any command (except OutputVar and InputVar parameters such as those of StringLen). However, parameters that do not support must use the «% » prefix as in this example:

MsgBox % "The answer is: " . Add(3, 2)

The «% » prefix is also permitted in parameters that natively support expressions, but it is simply ignored.

Functions

Feature Description
ComObj… —ComObjActiveComObjEnwrap/UnwrapComObjParameterComObjType Retrieves a registered COM object.Wraps/unwraps a COM object.Wraps a value and type to pass as a parameter.Retrieves a COM object’s type information.
ComObjArray Creates a SAFEARRAY for use with COM.
ComObjConnect Connects a COM object’s event sources to functions with a given prefix.
ComObjCreate Creates a COM object.
ComObjError Enables or disables notification of COM errors.
ComObjFlags Retrieves or changes flags which control a COM wrapper object’s behaviour.
ComObjGet Returns a reference to an object provided by a COM component.
ComObjQuery Queries a COM object for an interface or service.
ComObjType Retrieves type information from a COM object.
ComObjValue Retrieves the value or pointer stored in a COM wrapper object.
Creates an exception object for Throw (also provides limited access to the call stack).
FileOpen Provides object-oriented file I/O.
Func Retrieves a to a function.
GetKeyName/VK/SC Retrieves the name or text, virtual key code or scan code of a key.
InStr Searches for a given occurrence of a string, from the left or the right.
IsByRef Determines whether a ByRef parameter was supplied with a variable.
IsObject Determines whether a value is an object.
StrPut / StrGet Copies a string to or from a memory address, optional converting it between code pages.
Trim Trims certain characters from the beginning and/or end of a string.
RegEx (?CNum:Func) Calls a function during evaluation of a regex pattern.
New «local library» and .
Functions may accept a variable number of parameters via an array.
Static variables can now be initialized using any expression.
Добавить комментарий

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

Adblock
detector