AutoHotkey Beginner Tutorial

Auto Hotkey

AutoHotkey Beginner Tutorial by tidbit

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

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.

Currently there is no installer for AutoHotkey v2. The easiest way to get it work is to download the binaries, follow the installation steps below, and replace AutoHotkey.exe with the downloaded binaries inside the installation folder.

Text instructions:

  1. Go to the AutoHotkey Homepage. https://autohotkey.com/
  2. Click Download. https://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.

Video instructions:
Frankie's "Install and Hello World"
http://www.autohotkey.com/forum/viewtopic.php?t=77674

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. Note: It must end with a .ahk extension. Ex. 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 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.


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

Video instructions:
Frankie's "Install and Hello World"
http://www.autohotkey.com/forum/viewtopic.php?t=77674

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. In section 5 we'll talk about why it doesn't work as you might expect and what you can do instead.

d. Other basic info

How to find the Help File on your computer:

Downloads for v2.0-a076 and later include an offline help file. Currently there is no installer for v2, so the help file is wherever you put it.

Look for AutoHotkey.chm or a file that says AutoHotkey and has a yellow question mark on it.

Online Links:
Documentation
Command List
Functions
Variables

2 - Hotkeys & Hotstrings

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

a. Keys and their mysterious symbols

You might be wondering "How the crud am I supposed to know that ^ means CTRL?!". Well, good question. To help you learn what ^ and other symbols mean, gaze upon this chart:
SymbolDescription
#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

b. Window specific 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

c. Multiple hotkeys/hotstrings per file

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.

d. Examples

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

3 - Sending key strokes

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.


An example showing what shouldn't be done to 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
Another common issue is that people think that everything needs to be wrapped in brackets with the send command. That is FALSE. If it's not in the chart, it does not need brackets. You do not need to wrap common letters, numbers or even some symbols (such as . (period)) in {}'s.
Also, with the Send commands you are able to send more than 1 letter, number or symbol at a time. So no need for a bunch of Send commands with 1 letter each.
; 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
To hold down or release a key, enclose the key name in brackets and then use the word UP or DOWN.
; 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.
But now you are wondering "How can I make my really long send commands readable?". Easy. Use what is known as a Continuation Section. Simply specify an opening parenthesis on a new line, then your content, finally a closing parenthesis on its own line. For more information, read about Continuation Sections.
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.

a. Games

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.


From the FAQ page:
Some games use DirectInput exclusively. As a side-effect, they might ignore all simulated keystrokes and mouse clicks. To work around this, try one of the following (or a combination):
  • Use SendPlay via: 1) the SendPlay command; 2) using SendMode Play; and/or 3) the hotstring option SP.
  • Increase SetKeyDelay. For example:
  • SetKeyDelay, 0, 50
  • SetKeyDelay, 150, 150, Play
  • Try ControlSend, which might work in cases where the other Send modes fail.

4 - Running programs & websites

To run a program such as Mspaint.exe, Calc.exe, script.ahk or even a folder, you can use the Run command. It can even be used to open URLs such as https://autohotkey.com/ . If your computer is setup to run the type of program you want to run, it's very simple:
; 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
There are some other advanced features as well, such as Command-Line parameters and CLSID.
If you want to learn more about that stuff, visit the run page.
Here are a few more samples:
; 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.

5 - Commands vs. Functions()

AutoHotkey has two main types of things used by the scripter to create code:
Commands and Functions()

A list of all commands/functions: commands/index.htm

Note that all commands can be called as functions and vice versa, except for control flow statements such as Return. Which syntax you want to use is up to you, but in general the function syntax is preferred to have more flexibility.

Commands

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.
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.exe
Commands 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.

Functions

As stated above, functions are different because they use parenthesis. A typical function looks like:
Function(parameter1, parameter2, parameter3)

Functions have a few main differences:
  1. You can do math in them.
    -- SubStr(37*12, 1, 2)
    -- SubStr(A_Hour-12, 2)
  2. Variables do not need to be wrapped in percent signs.
    -- SubStr(A_Now, 7, 2)
  3. Functions can go inside of functions.
    -- SubStr(A_AHKPath, inStr(A_AHKPath, "AutoHotkey"))
  4. Text needs to be wrapped in quotes.
    -- SubStr("I'm scripting, awesome!", 16)
Functions usually return a value differently than a command does. Commands need an OutputVar parameter, functions do not. The most common way to assign a variable to the value of a function is like so:
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

In short:
; These are commands
Msgbox, This is some text.
StrReplace, Output, %Input%, AutoHotKey, AutoHotkey
SendInput, This is awesome{!}{!}{!}

; These are Functions
MsgBox("This is some text.")
Output := StrReplace(Input, "AutoHotKey", "AutoHotkey")
SendInput("This is awesome{!}{!}{!}")

a. Code blocks

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.

In the following code, both lines are run only if var equals 5.
if (var=5)
{
   MsgBox, var equals %var%!!
   Exitapp
}

In the following code, the msgbox is only shown if var equals 5. The code will always exit, even if var isn't 5.
if (var=5)
   MsgBox, var equals %var%!!
   Exitapp

This is perfectly fine since the if only had 1 line of code associated with it. It's exactly the same as above, but I outdented the second line so we know it's separate from the if.
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.

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 & 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 colon equal sign (:=).
  1. variable := "text"
    This is the simplest form for a variable. Simply type in your text and done. Any text needs to be in "quotes".
  2. variable := variable2
    Same as above, but you are assigning a variable to a different variables value.
  3. variable := 6+8/3*2-sqrt(9)
    Thanks to expressions, you can do math!

All of them can be combined in two ways:

Method #1: var:="The value of 5+ " Variable " is: " 5+Variable
Method #2: 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.

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 %'s:
  1. When you are using Commands (see above) you use percent signs.
    -- Except when the parameter is OutputVar.
  2. When you want to use the content of a variable inside a quoted string (see the 2nd method in the previous section).
When not to use %'s:
  1. In parameters that are output variables, For example: StrLen, OutputVar, %InputVar%
  2. On the left side of an assignment: Var := "123abc"
  3. Everywhere in expressions (but outside of quoted strings). 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, What is your first name?, Question 1
if (OutputVar="Bill")
   MsgBox("That's is an awesome name, %OutputVar%.")

InputBox, OutputVar2, Do you like AutoHotkey?, Question 2
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?

Result := MsgBox("Would you like to continue?",, 4)
if Result = "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 a var some text.
VarNmbr := 6              ; Assign a var a number.
Var2 := Var               ; Assign a var to another var.
Var3 := "%Var%"           ; Assign a var to another var using percents.
Var4 .= Var               ; Append a var to the end of another var.
Var5 += VarNmbr           ; Add the value of a var to another var.
Var5 -= VarNmbr           ; Subtract the value of a var from another var.
Var6 := SubStr(Var, 2, 2) ; Var inside a function.
Var7 := Var "Text"        ; Assigns a var to another var with some extra text.
Var8 := "%Var% Text"      ; Assigns a var to another var with some extra text using percents.
MsgBox, %Var%             ; Var inside a command. 
MsgBox(Var)               ; Same as above, but inside a function. 
StrSplit, Var, %Var%, x   ; Var inside a command that uses InputVar and OutputVar.
if (VarNmbr = 6)          ; Check if a var is equal to a number.
if VarNmbr = 6            ; Same as above.
if (Var != VarNmbr)       ; Check if a var is not equal to another var.
if Var1 < Var2            ; Check if a var is lesser than another var.

7 - Objects

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.


An object is basically a collection of variables. The variable names are known as "Keys", and the contents of the variables are "Values".

When you hear people calling an object an array or indexed array, it usually means that all the keys are sequential numbers 1 and up.
When you hear people calling an object an associative array, it means that the keys are either strings (text) or non-sequential numbers. Sometimes it's a mix of both, and sequential numbers too!

There are no restrictions to what a key or value can be, and they can even be other arrays!
When the values are arrays too, this is referred to as a nested array, and these will be explained later.
There are a number of reasons you might want to use an object for something. Some examples:
  1. You want to have a numbered list of things, such as a grocery list (this would be referred to as an indexed array)
  2. You want to represent a grid, perhaps for a board game (this would be done with nested objects)
  3. You have a list of things where each thing has a name, such as the characteristics of a fruit (this would be referred to as an associative array)

a. Creating Objects

There are a few ways to create an object, and the most common ones are listed below
  1. MyObject := ["one", "two", "three", 17]
    Bracket syntax. This will start you off with what is sometimes called an "indexed array". An indexed array is an object representing a list of items, numbered 1 and up. In this example, the value "one" is stored in object key 1 (aka index 1), and the value 17 is stored in object key 4 (aka index 4).
  2. Banana := {"Shape": "Elongated", "Color": "Yellow", "Taste": "Delicious", "Price": 3}
    Brace syntax. This will let you start of by defining what is sometimes called an "associative array". An associative array is a collection of data where each item has a name. In this example, the value "yellow" is stored in the object key "color". Also, the value 3 is stored in the object key "Price".
  3. MyObject := Array("one", "two", "three", 17)
    The "array" creation function. This is equivalent to the bracket syntax, but wrapped in a function.
  4. Banana := Object("Shape", "Elongated", "Color", "Yellow", "Taste", "Delicious", "Price", 3)
    The object creation function. This is equivalent to the brace syntax, but wrapped in a function.
It's important to remember that every one of these definitions all create the same thing (objects), just with different keys.

b. Using Objects

There are many ways to use objects, including retrieving values, setting values, adding more values, and more.

To set values:
Setting values in an object is as simple as setting the value of a variable.
All you have to do is put your bracket or dot notation (as seen in the retrieval section) on the left side of an expression assignment symbol :=.

For example:
Banana.Consistency := "Mushy"
Banana["Pickled"] := True ; This banana has been pickled. Eww.

To retrieve values:
  1. Value := Banana["Color"]
    Bracket notation. This allows you to use an expression as the key to get the value from your object. In this case, I used the simple expression "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.
  2. Value := Banana.Color
    Dot notation. This only lets you use literal strings for the keys. You cannot use variables in your keys with dot notation.

To add new keys and values:
  1. Directly adding values
    To directly add a key and value, just set a key that doesn't exist yet. For example:
    MyObject.NewKey := "Shiny"
    MyObject["NewerKey"] := 3.1415
  2. Inserting values
    Another way to add keys and values to an object is to use one of the following methods.

    MyObject.InsertAt(Index, Value1, Value2, Value3...)
    Index is any integer key. This will shift ALL higher integer keys up by the number of values which were inserted, even if there are gaps (for example, only keys 1 and 100 exist, and you insert a value at key 50, it will shift 100 up to 101).

    MyObject.Push(Value1, Value2, Value3...)
    This "appends" the values to the end of the array MyObject. In other words, it inserts the values at the highest integer key plus one.

To remove keys and values:
  1. Blanking the value out.
    The simplest way to remove a value is to just blank it out. You can do this by setting it to "", also known as an empty string. This doesn't remove the key, but it will make the value appear identical to an unset value.
    It is possible to tell that the key still exists by using the HasKey method, and it will still come up in a for loop. (for loops will be explained later)
  2. Removing the key
    There are a few different ways to remove both the key and the value. They are:
    1. RemovedValue := MyObject.Delete(AnyKey)
      The previous value of MyObject[AnyKey] will be stored in RemovedValue.
    2. NumberOfRemovedKeys := MyObject.Delete(FirstKey, LastKey)
      Using the remove method in this way allows you to remove a range of numbered/integer or string keys between FirstKey and LastKey.

      The value it gives will be the number of keys that were removed, which is useful if you have a gap between your keys (eg, you specify keys 1 through four, but key number 2 doesn't exist, this will set NumberOfRemovedKeys to 3 as only three keys were there to be removed)
    3. MyObject.Pop()
      This removes the highest integer key, and returns the value. There are no keys higher than it to be affected.
    4. RemovedValue := MyObject.RemoveAt(Index)
      NumberOfRemovedKeys := MyObject.RemoveAt(Index, Length)
      This removes all keys from Index to Index + Length - 1 (inclusive). If Length is omitted it defaults to 1. After removing the keys it takes all higher numbered/integer keys and moves them down to fill the gap, so that if there was a value at Index + Length it will now be at Index. This is similar to how the InsertAt method with multiple specified values works.

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 []'s

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 []'s in your code.

On the ControlGetText page you will see this (without the colors):
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, 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

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

No indents:
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.
http://en.wikipedia.org/wiki/Indent_style

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.

f. Other links

Frequently Asked Questions (FAQ)