Autohotkey
Содержание:
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.
Ending Characters
Unless the is in effect, you must type an ending character after a hotstring’s abbreviation to trigger it. Ending characters initially consist of the following: -()[]{}’:;»/\,.?!`n `t (note that `n is Enter, `t is Tab, and there is a plain space between `n and `t). This set of characters can be changed by editing the following example, which sets the new ending characters for all hotstrings, not just the ones beneath it:
#Hotstring EndChars -()[]{}:;'"/\,.?!`n `t
: The ending characters can be changed while the script is running by calling the Hotstring function as demonstrated below:
Hotstring("EndChars", "-()[]{}:;")
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.
8 — Other Helpful Goodies
We have reached the end of our journey, my good friend. I hope you have learned something. But before we go, here are some other things that I think you should know. Enjoy!
a. The mysterious square brackets
Throughout the documentation, you will see these two symbols ( and ) surrounding code in the yellow syntax box at the top of almost all pages. Anything inside of these brackets are OPTIONAL. Meaning the stuff inside can be left out if you don’t need them. When writing your code, it is very important to NOT type the square brackets in your code.
On the ControlGetText page you will see this:
ControlGetText, OutputVar , Control, WinTitle, WinText, ExcludeTitle, ExcludeText
So you could simply do this if you wanted:
ControlGetText, OutputVar
Or add in some more details:
ControlGetText, OutputVar, Control, WinTitle
What if you wanted to use ExcludeTitle but not fill in WinText or WinTitle? Simple!
ControlGetText, OutputVar, Control,,, ExcludeTitle
Please note that you cannot IGNORE parameters, but you can leave them blank. If you were to ignore , it would look like this and cause issues:
ControlGetText, OutputVar, Control, ExcludeTitle
b. Finding your AHK version
Run this code to see your AHK version:
MsgBox, %A_AhkVersion%
Or look for «AutoHotkey Help File» or «AutoHotkey.chm» in the start menu or your installation directory.
c. Trial and Error
Trial and Error is a very common and effective way of learning. Instead of asking for help on every little thing, sometimes spending some time alone (sometimes hours or days) and trying to get something to work will help you learn faster.
If you try something and it gives you an error, study that error. Then try to fix your code. Then try running it again. If you still get an error, modify your code some more. Keep trying and failing until your code fails no more. You will learn a lot this way by reading the documentation, reading errors and learning what works and what doesn’t. Try, fail, try, fail, try, try, try, fail, fail, succeed!
This is how a lot of «pros» have learned. But don’t be afraid to ask for help, we don’t bite (hard). Learning takes time, the «pros» you encounter did not learn to be masters in just a few hours or days.
«If at first you don’t succeed, try, try, try again.» — Hickson, William E.
d. Indentation
This stuff (indentation) is very important! Your code will run perfectly fine without it, but it will be a major headache for you and other to read your code. Small code (25 lines or less) will probably be fine to read without indentation, but it’ll soon get sloppy. It’s best you learn to indent ASAP. Indentation has no set style, but it’s best to keep everything consistent.
«What is indentation?» you ask? It’s simply spacing to break up your code so you can see what belongs to what. People usually use 3 or 4 spaces or 1 tab per «level».
Not indented:
if (car = "old")
{
MsgBox, The car is really old.
if (wheels = "flat")
{
MsgBox, This car is not safe to drive.
return
}
else
{
MsgBox, Be careful! This old car will be dangerous to drive.
}
}
else
{
MsgBox, My`, what a shiny new vehicle you have there.
}
Indented:
if (car = "old")
{
MsgBox, The car is really old.
if (wheels = "flat")
{
MsgBox, This car is not safe to drive.
return
}
else
{
MsgBox, Be careful! This old car will be dangerous to drive.
}
}
else
{
MsgBox, My`, what a shiny new vehicle you have there.
}
See Wikipedia’s Indentation style page for various styles and examples. Choose what you like or learn to indent how you think it’s easiest to read.
e. Asking for Help
Before you ask, try doing some research yourself or try to code it yourself. If that did not yield results that satisfy you, read below.
- Don’t be afraid to ask for help, even the smartest people ask others for help.
- Don’t be afraid to show what you tried, even if you think it’s silly.
- Post anything you have tried.
- Pretend everyone but you is a doorknob and knows nothing. Give as much information as you can to educate us doorknobs at what you are trying to do. Help us help you.
- Be patient.
- Be polite.
- Be open.
- Be kind.
- Enjoy!
If you don’t get an answer right away, wait at least 1 day (24 hours) before asking for more help. We love to help, but we also do this for free on our own time. We might be at work, sleeping, gaming, with family or just too busy to help.
And while you wait for help, you can try learning and doing it yourself. It’s a good feeling, making something yourself without help.
Examples
Lists the key-value pairs of an object.
colours := ("red", 0xFF0000, "blue", 0x0000FF, "green", 0x00FF00)
; The above expression could be used directly in place of "colours" below:
for k, v in colours
s .= k "=" v "`n"
MsgBox % s
Lists all open Explorer and Internet Explorer windows, using the Shell object.
for window in ComObjCreate("Shell.Application").Windows
windows .= window.LocationName " :: " window.LocationURL "`n"
MsgBox % windows
Class: CEnumerator
Provides a generic enumerator object that can be used for iterating over numeric keys. The array must not be modified during iteration, otherwise the iterated range will be invalid.
It’s possible to define a custom MaxIndex() functions for array boundaries. If there are missing array members between 1 and max index, they will be iterated but will have a value of «». This means that real sparse arrays are not supported by this enumerator by design. Source: Suggestions on documentation improvements
/*
Class: CEnumerator
To make an object use this iterator, insert this function in the class definition:
_NewEnum()
{
return new CEnumerator(this)
}
*/
; Iterate over the enumerator
For k, v in Test
MsgBox %k%=%v%
; Test class for demonstrating usage
class Test
{
static Data :=
_NewEnum()
{
return new CEnumerator(this.Data)
}
}
class CEnumerator
{
__New(Object)
{
this.Object := Object
this.first := true
; Cache for speed. Useful if custom MaxIndex() functions have poor performance.
; In return, that means that no key-value pairs may be inserted during iteration or the range will become invalid.
this.ObjMaxIndex := Object.MaxIndex()
}
Next(ByRef key, ByRef value)
{
if (this.first)
{
this.Remove("first")
key := 1
}
else
key ++
if (key <= this.ObjMaxIndex)
value := this.Object
else
key := ""
return key != ""
}
}
Попробуйте это мгновенный убийца монитора
AutoHotkey также может отправлять системные команды. Если вы целый день работаете за компьютером, возможно, вы не будете активно его использовать, но не хотите его выключать. Этот скрипт мгновенно обрежет сигнал на экране, а не будет ждать, пока он истечет, или заставка сработает.
Скачать: monitor_sleep.ahk
После загрузки откройте скрипт и нажмите F1, Разбудите его снова, перемещая мышь или нажимая любую клавишу на клавиатуре. AutoHotkey может управлять многими элементами вашей системы аналогично этому, включая отправку команд выключения, открытия пользовательских проводников Windows и даже команд в командной строке.
Joystick
Joy1 through Joy32: The buttons of the joystick. To help determine the button numbers for your joystick, use this . Note that hotkey prefix symbols such as ^ (control) and + (shift) are not supported (though can be used as a substitute). Also note that the pressing of joystick buttons always «passes through» to the active window if that window is designed to detect the pressing of joystick buttons.
Although the following Joystick control names cannot be used as hotkeys, they can be used with :
- JoyX, JoyY, and JoyZ: The X (horizontal), Y (vertical), and Z (altitude/depth) axes of the joystick.
- JoyR: The rudder or 4th axis of the joystick.
- JoyU and JoyV: The 5th and 6th axes of the joystick.
- JoyPOV: The point-of-view (hat) control.
- JoyName: The name of the joystick or its driver.
- JoyButtons: The number of buttons supported by the joystick (not always accurate).
- JoyAxes: The number of axes supported by the joystick.
- JoyInfo: Provides a string consisting of zero or more of the following letters to indicate the joystick’s capabilities: Z (has Z axis), R (has R axis), U (has U axis), V (has V axis), P (has POV control), D (the POV control has a limited number of discrete/distinct settings), C (the POV control is continuous/fine). Example string: ZRUVPD
Multiple Joysticks: If the computer has more than one joystick and you want to use one beyond the first, include the joystick number (max 16) in front of the control name. For example, 2joy1 is the second joystick’s first button.
Note: If you have trouble getting a script to recognize your joystick, one person reported needing to specify a joystick number other than 1 even though only a single joystick was present. It is unclear how this situation arises or whether it is normal, but experimenting with the joystick number in the can help determine if this applies to your system.
See Also:
- Joystick remapping: Methods of sending keystrokes and mouse clicks with a joystick.
- : Using a joystick as a mouse.
Embedded Scripts [v1.1.34+]
Scripts may be embedded into a standard AutoHotkey .exe file by adding them as Win32 (RCDATA) resources. An embedded script can be specified on the command line or with #Include by writing an asterisk (*) followed by the resource name. For an integer ID, the resource name must be a hash sign (#) followed by a decimal number.
The program may automatically load script code from the following resources, if present in the file:
| ID | Spec | Usage |
|---|---|---|
| 1 | *#1 | This is the means by which a is created from an .exe file. This script is executed automatically and most command line switches are passed to the script instead of being interpreted by the program. External scripts and alternative embedded scripts can be executed by using the switch. |
| 2 | *#2 | If present, this script is automatically «included» before any script that the program loads, and before any file specified with . |
When the source of the main script is an embedded resource, the program acts in «compiled script» mode, with the exception that always contains the path of the current executable file (the same as ). For resources other than *#1, the resource specifier is included in to support #SingleInstance and Reload.
When referenced from code that came from an embedded resource, contains an asterisk (*) followed by the resource name.
Установка 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:
- 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.
- Double-click that script’s tray icon to open its main window.
- Press one of the «mystery keys» on your keyboard.
- Select the menu item «View->Key history»
- 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.
- If your key is detectable, make a note of the 3-digit hexadecimal value in the second column of the list (e.g. 159).
- 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:
-
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.
-
Try AHKHID. You can also try searching the forum for a keywords like , or .
-
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.
Long Replacements
Hotstrings that produce a large amount of replacement text can be made more readable and maintainable by using a . For example:
::text1::
(
Any text between the top and bottom parentheses is treated literally, including commas and percent signs.
By default, the hard carriage return (Enter) between the previous line and this one is also preserved.
By default, the indentation (tab) to the left of this line is preserved.
)
See for how to change these default behaviors. The presence of a continuation section also causes the hotstring to default to . The only way to override this special default is to specify the in each hotstring that has a continuation section (e.g. ).
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).
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.
Hotstring Helper
Andreas Borutta suggested the following script, which might be useful if you are a heavy user of hotstrings. By pressing Win+H (or another hotkey of your choice), the currently selected text can be turned into a hotstring. For example, if you have «by the way» selected in a word processor, pressing Win+H will prompt you for its abbreviation (e.g. btw) and then add the new hotstring to the script. It will then reload the script to activate the hotstring.
Note: The Hotstring function can be used to create new hotstrings without reloading. Take a look at the in the example section of the function’s page to see how this could be done.
#h:: ; Win+H hotkey
; Get the text currently selected. The clipboard is used instead of
; "ControlGet Selected" because it works in a greater variety of editors
; (namely word processors). Save the current clipboard contents to be
; restored later. Although this handles only plain text, it seems better
; than nothing:
AutoTrim Off ; Retain any leading and trailing whitespace on the clipboard.
ClipboardOld := ClipboardAll
Clipboard := "" ; Must start off blank for detection to work.
Send ^c
ClipWait 1
if ErrorLevel ; ClipWait timed out.
return
; Replace CRLF and/or LF with `n for use in a "send-raw" hotstring:
; The same is done for any other characters that might otherwise
; be a problem in raw mode:
StringReplace, Hotstring, Clipboard, ``, ````, All ; Do this replacement first to avoid interfering with the others below.
StringReplace, Hotstring, Hotstring, `r`n, ``r, All ; Using `r works better than `n in MS Word, etc.
StringReplace, Hotstring, Hotstring, `n, ``r, All
StringReplace, Hotstring, Hotstring, %A_Tab%, ``t, All
StringReplace, Hotstring, Hotstring, `;, ```;, All
Clipboard := ClipboardOld ; Restore previous contents of clipboard.
; This will move the input box's caret to a more friendly position:
SetTimer, MoveCaret, 10
; Show the input box, providing the default hotstring:
InputBox, Hotstring, New Hotstring, Type your abreviation at the indicated insertion point. You can also edit the replacement text if you wish.`n`nExample entry: :R:btw`::by the way,,,,,,,, :R:`::%Hotstring%
if ErrorLevel ; The user pressed Cancel.
return
if InStr(Hotstring, ":R`:::")
{
MsgBox You didn't provide an abbreviation. The hotstring has not been added.
return
}
; Otherwise, add the hotstring and reload the script:
FileAppend, `n%Hotstring%, %A_ScriptFullPath% ; Put a `n at the beginning in case file lacks a blank line at its end.
Reload
Sleep 200 ; If successful, the reload will close this instance during the Sleep, so the line below will never be reached.
MsgBox, 4,, The hotstring just added appears to be improperly formatted. Would you like to open the script for editing? Note that the bad hotstring is at the bottom of the script.
IfMsgBox, Yes, Edit
return
MoveCaret:
if not WinActive("New Hotstring")
return
; Otherwise, move the input box's insertion point to where the user will type the abbreviation.
Send {Home}{Right 3}
SetTimer, MoveCaret, Off
return
Remarks
The Click command is generally preferred over MouseClick because it automatically compensates if the user has swapped the left and right mouse buttons via the system’s control panel.
The Click command uses the sending method set by SendMode. To override this mode for a particular click, use a specific Send command in combination with , as in this example: .
To perform a shift-click or control-click, is generally easiest. For example:
Send +{Click 100 200} ; Shift+LeftClick
Send ^{Click 100 200 Right} ; Control+RightClick
Unlike Send, the Click command does not automatically release the modifier keys (Ctrl, Alt, Shift, and Win). For example, if Ctrl is currently down, would produce a control-click but would produce a normal click.
The SendPlay mode is able to successfully generate mouse events in a broader variety of games than the other modes. In addition, some applications and games may have trouble tracking the mouse if it moves too quickly, in which case SetDefaultMouseSpeed can be used to reduce the speed (but only in SendEvent mode).
The BlockInput command can be used to prevent any physical mouse activity by the user from disrupting the simulated mouse events produced by the mouse commands. However, this is generally not needed for the SendInput and SendPlay modes because they automatically postpone the user’s physical mouse activity until afterward.
There is an automatic delay after every click-down and click-up of the mouse (except for SendInput mode and for turning the mouse wheel). Use SetMouseDelay to change the length of the delay.
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:
- Find the script file, select it, and press Ctrl+C.
- 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).
- Right click inside the window, and click «Paste Shortcut». The shortcut to the script should now be in the Startup folder.
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.
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.
Other Features
NumLock, CapsLock, and ScrollLock: These keys may be forced to be «AlwaysOn» or «AlwaysOff». For example: .
Overriding Explorer’s hotkeys: Windows’ built-in hotkeys such as Win+E (#e) and Win+R (#r) can be individually overridden simply by assigning them to an action in the script. See the override page for details.
Substitutes for Alt-Tab: Hotkeys can provide an alternate means of alt-tabbing. For example, the following two hotkeys allow you to alt-tab with your right hand:
RControl & RShift::AltTab ; Hold down right-control then press right-shift repeatedly to move forward. RControl & Enter::ShiftAltTab ; Without even having to release right-control, press Enter to reverse direction.
For more details, see .