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.
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.
Video instructions:
Install and Hello World by Frankie
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".
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 section 5.
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. ^j::
is
the Hotkey. ^
means
CTRL,
j
is the letter
j. Anything to the left of
::
are the keys you need to press.
- The second line. Send, My First Script
is how you SEND keystrokes. SEND
is the command, anything after the comma (,) will be typed.
- The third line. Return
. Return 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.
Video instructions:
Install and Hello World by Frankie
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. In section 5 we'll talk about why it doesn't work as you might expect and what you can do instead.
Online Links:
Documentation
Command List
Functions
Variables
What is a Hotkey? A hotkey is a key that is hot to the touch. ... Just kidding. It is a key or key combination that the person at the keyboard presses to trigger some actions.
What is a Hotstring? Hotstrings are mainly used to expand abbreviations as you type them (auto-replace), they can also be used to launch any scripted action.
Here is a hotkey:
^j:: Send, My First Script Return
Here is a hotstring:
::ftw::Free the whales
The difference between the two examples is that the hotkey will be triggered when you press CTRL & J while the hotstring will convert your typed "ftw" into "Free the whales".
"So, how exactly does a person such as myself create a hotkey?"
Good question. A hotkey is created by using a single pair of ::'s. The key or key combo needs to go on the left of the ::
. And the content needs to go below, followed by a Return
.
Note: There are exceptions, but those tend to cause confusion a lot of the time. So it won't be covered in the tutorial, at least, not right now.
esc:: MsgBox Escape!!!! Return
A hotstring has a pair of ::'s on each side of the text you want to trigger the text replacement. While the text to replace your typed text goes on the right of the second pair of ::'s.
Hotstring, as mentioned above, can also launch scripted actions. That's fancy talk for "do pretty much anything". Same with hotkeys.
::btw:: MsgBox You typed "btw". Return
A nice thing to know is that you can have many lines of code for each hotkey, hotstring, label, and a lot of other things we haven't talked about yet.
^j:: MsgBox Wow! MsgBox this is Run, Notepad.exe winactivate, Untitled - Notepad WinWaitActive, Untitled - Notepad send, 7 lines{!}{enter} sendinput, inside the ctrl{+}j hotkey Return
Symbol | Description |
---|---|
# | Win (Windows logo key) |
! | Alt |
^ | Control |
+ | Shift |
& | An ampersand may be used between any two keys or mouse buttons to combine them into a custom hotkey. |
(For the full list of symbols, see the Hotkey page)
Additionally, here is a list of all/most hotkey names that can be used on the left side of a hotkeys :: symbol:
KeyList.htm
You can define a custom combination of two (and only 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. Return Numpad0 & Numpad2:: Run Notepad Return
But you are now wondering if hotstrings have any cool modifiers since hotkeys do. Yes, they do!
Hotstrings modifiers go between the first set of ::'s. Such as:
:*:ftw::Free the whales
For additional hotkey and hotstring modifiers, information and examples, visit:
Hotkeys
Hotstrings
Sometime you might want a hotkey or hotstring to only work (or be disabled) in a certain window. To do this, you will need to use either of these fancy commands with a # in-front of them.
#IfWinActive
#IfWinExist
These special commands (technically called "directives") create context-sensitive hotkeys and hotstrings. Simply specify a window title. But in some cases you might want to specify an HWND, group, or class. Those are a bit advanced and are covered more in-depth here: #IfWinActive.
#IfWinActive Untitled - Notepad #space:: MsgBox You pressed Win+Spacebar in Notepad. Return #IfWinActive
To turn off context sensitivity, specify any #IfWin command but leave all of its parameters blank. For example:
; Notepad #IfWinActive untitled - Notepad !q:: MsgBox, You pressed Alt and Q in Notepad. Return #IfWinActive ; Any window that isn't Untitled - Notepad !q:: MsgBox, You pressed Alt and Q in any window. Return
When #IfWin commands are turned off (or never used in a script), all hotkeys and hotstrings are enabled for all windows.
The #IfWin commands are positional: they affect all hotkeys and hotstrings physically beneath them in the script.
; Notepad #IfWinActive ahk_class Notepad #space:: MsgBox, You pressed Win+Spacebar in Notepad. Return ::msg::You typed msg in Notepad #IfWinActive ; MSPaint #IfWinActive untitled - Paint #space:: MsgBox, You pressed Win+Spacebar in MSPaint! Return ::msg::You typed msg in MSPaint! #IfWinActive
For more in-depth information and similar
commands, check out:
#IfWinActive
This, for some reason crosses some people's minds. So I'll set it clear: AutoHotkey has the ability to have as many hotkeys and hotstrings in 1 file as you want. Whether it's 1, or 3253 (or more).
#i:: run, http://www.google.com/ Return ^p:: run, notepad.exe Return ~j:: send, ack Return :*:acheiv::achiev ::achievment::achievement ::acquaintence::acquaintance :*:adquir::acquir ::aquisition::acquisition :*:agravat::aggravat :*:allign::align ::ameria::America
The above code is perfectly acceptable. Multiple hotkeys, multiple hotstrings. All in one big happy script file.
::btw::By the way ; Replaces "btw" with "By the way" as soon as you press an EndChar. :*:btw::By the way ; Replaces "btw" with "By the way" without needing an EndChar ^n:: ; Ctrl & n Hotkey run, notepad.exe ; Run the program notepad.exe when you press Ctrl & n Return ; This ends the hotkey. The code below this will not get triggered. ^b:: ; Ctrl & b Hotkey send, {ctrl down}c{ctrl up} ; Copies the selected text. ^c could be used as well, but this method is more secure. SendInput, [b]{ctrl down}v{ctrl up}[/b] ; Wraps the selected text in bbcode (forum) Bold tags. Return ; This ends the hotkey. The code below this point will not get triggered.
So now you decided that you want to send (type) keys to a
program. We can do that. Use the Send command. Send literally sends keystrokes, to simulate typing or pressing of keys.
Before we get into things, here are some common issues
that people have:
Just like Hotkeys, Send has special keys too. Lots and lots of them.
Here are the 4 most common symbols:
!: Sends the ALT key. For example, Send This is text!a would send the keys "This is text" and then press ALT+a. Note: !A produces a different effect in some programs than !a. This is because !A presses ALT+SHIFT+A and !a presses ALT+a. If in doubt, use lowercase.
+: Sends the SHIFT key. For example, Send +abC would send the text "AbC", and Send !+a would press ALT+SHIFT+a.
^: Sends the CONTROL (Ctrl) key. For example, Send ^!a would press CTRL+ALT+a, and Send ^{Home} would send CONTROL+HOME. Note: ^A produces a different effect in some programs than ^a. This is because ^A presses CONTROL+SHIFT+A and ^a presses CONTROL+a. If in doubt, use lowercase.
#: Sends the WIN key (the key with the Windows logo) therefore Send #e would hold down the Windows key and then press the letter "e".
The next couple of paragraphs are talking about the table on send page.
Note:
This table does not apply to hotkeys. Meaning, you do not wrap CTRL or ENTER (or any other key) inside {}'s when making a hotkey.
; When making a hotkey... ; WRONG {LCtrl}:: send, AutoHotkey Return ; CORRECT LCtrl:: send, AutoHotkey Return
The gigantic table above shows pretty much every special key built-in to AHK. Such as: {enter}
and {space}
.
A common issue lots of people have is they assume that the curly brackets are put in the documentation pages just for fun. But in fact they are needed. It's how AHK knows that {!}
means "exclamation point" and not "press the Alt key". So please remember to check the table on the send page and make sure you have your brackets in the right places.
; Notice the ! is in {}'s? That's because if it wasn't, AHK would ; press the ALT key. send, This text has been typed{!}
; Same as above, but with the ENTER key. AHK would type out "enter" if ... ; ... it wasn't wrapped in {}'s. send, Multiple enter lines have enter been sent. ; WRONG send, Multiple{enter}lines have{enter}been sent. ; CORRECT
; Don't wrap words or individual letters that are not in the table mentioned above. send, {a} ; WRONG send, {b} ; WRONG send, {c} ; WRONG send, {a}{b}{c} ; WRONG send, {abc} ; WRONG send, abc ; CORRECT
; This is how you hold 1 key down and press another key (or keys). ; If 1 method doesn't work in your program, please try the other. send, ^s ; Both of these send CTRL+s send, {ctrl down}s{ctrl up} ; Both of these send CTRL+s Send, {ctrl down}c{ctrl up} Send, {b down}{b up} Send, {TAB down}{TAB up} Send, {Up down} ; Press down the up-arrow key. Sleep, 1000 ; Keep it down for one second. Send, {Up up} ; Release the up-arrow key.
send, ( Line 1 Line 2 Apples are a fruit. )
Note: There are several different forms of send. Each has their own special features. If one form of send does not work for your needs, try another type of send. Simply replace the commands name "send" with "sendPlay" or whatever you want.
Here are most ways to send text:
Send
SendRaw
SendInput
SendPlay
SendEvent
For more information on what each one does, read this.
This is important!
A lot of games, especially modern ones, have cheat prevention software.
Things like GameGuard, Hackshield, PunkBuster and several others.
If a game has a cheat prevention system and your hotkeys,
hotstrings and send commands do not work, you are out of luck.
Not only is bypassing these systems in violation of the games policies
and will get you banned, they are complex to work around.
There are methods that can increase the chance of working in some games, but there is no
magical "make it work in my game now!!!" button. so try ALL
of these before giving up.
There are also known issues with DirectX. If you are having issues
and you know the game uses DirectX, try the stuff below. You should
also try running the game in Windowed Mode, if possible. That fixes
some DirectX issues.
More DirectX issues may occur when using pixel or image commands.
Colors might turn out black (0x000000) no matter the color you try
to get. That is another tricky thing to fix. Try running in Windowed Mode if you can.
There is no single solution to make AutoHotkey work in all programs. If everything you try fails, it may not be possible to use AutoHotkey for your needs.
SetKeyDelay, 0, 50
SetKeyDelay, 150, 150, Play
; Run a program. Note: most programs will require a FULL file path. Run, %A_ProgramFiles%\Some_Program\Program.exe ; Run a website Run, https://autohotkey.com
; Several programs do not need a full path, such as Windows-standard programs. Run, Notepad.exe Run, MsPaint.exe ; Run the "My Documents" folder using the built-in AHK variable Run, %A_MyDocuments% ; Run some websites Run, https://autohotkey.com Run, http://www.google.com
For more in-depth information and examples, check out:
commands/Run.htm.
Helpful links:
A list of all commands: commands/index.htm
A list of all built-in functions: Functions.htm#BuiltIn
You can tell what a command is by looking at its syntax (the way it looks). Commands do not use parenthesis "()" around the parameters like functions do. So a command would look like this:
Command, parameter1, parameter2, parameter3
When using commands, you cannot squish other commands onto the same line as a previous command (exception: ifEqual).
You cannot put commands inside the parameters of other commands.
Msgbox, Hello Run, Notepad.exe ; Wrong Msgbox, Hello, Run, Notepad.exe ; Wrong Msgbox, Hello ; Correct Run, Notepad.exeCommands also differ from function in that they use "traditional syntax". Meaning: when you use a
variable
, you NEED to use %'s around it. %variable%
. Any text and numbers do not need to be in "quotation marks". This is some text
. Additionally, you cannot do math in the parameters, unlike functions().
You can do math in parameters if you force an expression with a single %
, but that will not be covered.
Function(parameter1, parameter2, parameter3)
SubStr(37*12, 1, 2)
SubStr(A_Hour-12, 2)
SubStr(A_Now, 7, 2)
SubStr(A_AHKPath, inStr(A_AHKPath, "AutoHotkey"))
SubStr("I'm scripting, awesome!", 16)
MyVariable:=Function(Parameters)
MyVariable:=SubStr("I'm scripting, awesome!", 16)
This isn't the only way, but it's the most common. You are assigning MyVariable
to the value of the function (in this case, SubStr(...)
) that is to the right of the :=.
More about Functions
; These are commands Msgbox, This is some text. StringReplace, Output, Input, AutoHotKey, AutoHotkey, ALL SendInput, This is awesome{!}{!}{!} ; These are Functions SubStr("I'm scripting, awesome!", 16) FileExist(VariableContainingPath) Output:=SubStr("I'm scripting, awesome!", 16)
Code blocks are little curly brackets ({ and }) that are there to group a section of code together so that AutoHotkey knows it's one big family and that it needs to stay together. They are most often used with If and Loops. Without them, only the first line in the block is called.
if (var=5) { MsgBox, var equals %var%!! Exitapp }
if (var=5) MsgBox, var equals %var%!! Exitapp
if (var=5) MsgBox, var equals %var%!! MsgBox, We are now 'outside' the if. We did not need {}'s since there was only 1 line below it.
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 & scripting would be much more tedious.
variable=text
variable=%variable2%
variable:="text"
variable:=variable2
variable:=6+8/3*2-sqrt(9)
var=%var2% some text %var3%.
var:="The value of 5+ " Variable " is: " 5+Variable
Any equal sign (=) with a symbol in front of it is called an Assignment Operator, which are always an expression. So :=
+=
-=
.=
etc. always use expressions.
One of the most common issues with AutoHotkey involving variables is when to use the percent signs (%). Hopefully this will clear some confusion.
StringLen, OutputVar, InputVar
Var = 123abc
If Var1 < %Var2%
If (Var1 != Var2) Var1 := Var2 + 100
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.
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 Variable=text ; Assign a variable some text using 'traditional' assignment. VariableNumber:=6 ; Assign a variable a number using 'expressional' assignment. Variable2=%Variable% ; Assign a variable to another variable using traditional assignment. Variable3:=Variable ; Assign a variable to another variable using expressional assignment. Variable4.=Variable ; Append a variable to the end of another variable using expressional assignment. Variable5+=VariableNumber ; Add the value of a variable to another variable using expressional assignment. Variable5-=VariableNumber ; Subtract the value of a variable from another variable using expressional assignment. Variable6:=SubStr(Variable, 2, 2) ; Variable inside a function. This is always an expression. Variable7=%Variable% Text ; Assigns a variable to another variable with some extra text using tradition assignment. Variable8:=Variable " Text" ; Assigns a variable to another variable with some extra text using expressional assignment. MsgBox, %Variable% ; Variable inside a command. StringSplit, Variable, Variable, x ; Variable inside a command that uses InputVar and OutputVar. if (VariableNumber=6) ; Whenever an IF has parenthesis, it'll be an expression. So no %'s. If (Variable != VariableNumber) ; Whenever an IF has parenthesis, it'll be an expression. So no %'s. if VariableNumber=6 ; Without parenthesis, the if is Traditional. However, only variables on the 'right side' need %'s. If Var1 < %Var2% ; Without parenthesis, the if is Traditional. However, only variables on the 'right side' need %'s.
Objects are a way of organizing your data for more efficient usage. Sometimes objects are referred to as arrays, but it's important to note that all arrays are just objects. We call objects different things depending on what we are using them for, but all objects are the same.
MyObject := ["one", "two", "three", 17]
"one"
is stored in object key 1
(aka index 1), and the value 17
is stored in object key 4
(aka index 4).
Banana := {"Shape": "Elongated", "Color": "Yellow", "Taste": "Delicious", "Price": 3}
"yellow"
is stored in the object key "color"
. Also, the value 3
is stored in the object key "Price"
.
MyObject := Array("one", "two", "three", 17)
Banana := Object("Shape", "Elongated", "Color", "Yellow", "Taste", "Delicious", "Price", 3)
:=
.Banana.Consistency := "Mushy"
Banana["Pickled"] := True ; This banana has been pickled. Eww.
Value := Banana["Color"]
"Color"
, which is (unsurprisingly) the key Color
You will get a message box with the word "Yellow", because that is what we set the key Color
to in the previous section.
Value := Banana.Color
MyObject.NewKey := "Shiny"
MyObject["NewerKey"] := 3.1415
MyObject.InsertAt(Index, Value1, Value2, Value3...)
MyObject.Push(Value1, Value2, Value3...)
HasKey
method, and it will still come up in a for
loop. (for loops will be explained later)
RemovedValue := MyObject.Delete(AnyKey)
MyObject[AnyKey]
will be stored in RemovedValue.
NumberOfRemovedKeys := MyObject.Delete(FirstKey, LastKey)
MyObject.Pop()
RemovedValue := MyObject.RemoveAt(Index)
NumberOfRemovedKeys := MyObject.RemoveAt(Index, Length)
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!
ControlGetText, OutputVar [, Control, WinTitle, WinText, ExcludeTitle, ExcludeText]
ControlGetText, OutputVar
ControlGetText, OutputVar, Control, WinTitle
ControlGetText, OutputVar, Control,,, ExcludeTitle
Please note that you cannot IGNORE parameters, you can however leave them blank.
If you were to Ignore "WinTitle, WinText", it would look like this and cause issues:
ControlGetText, OutputVar, Control, ExcludeTitle
This is valid.
ControlGetText, OutputVar, Control,,, ExcludeTitle
MsgBox, %A_AHKVersion%Or look for "AutoHotkey Help File" or "AutoHotkey.chm" in the start menu or your installation directory.
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.
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. }Wiki has various styles and examples. Choose what you like or learn to indent how you think it's easiest to read.