AutoHotkey functions

A function groups a piece of work under a name so the rest of the script can call it. In v2 the built-in library and your own code follow identical rules, so once you can read one you can read both.

Writing one

#Requires AutoHotkey v2.0

Initials(fullName)
{
    parts := StrSplit(fullName, " ")
    out := ""
    for word in parts
        out .= SubStr(word, 1, 1)
    return out
}

MsgBox Initials("Ada Byron Lovelace")   ; ABL

Parameters can carry defaults (Greet(name, greeting := "Hello")), and a function that reaches the end without return gives back an empty string.

String helpers

FunctionDoes
StrLenLength of a string
SubStrSlice by position and length
StrReplaceSwap one substring for another
StrSplitSplit into an array
Trim, LTrim, RTrimRemove surrounding whitespace
StrUpper, StrLowerChange case
InStrFind a substring
RegExMatch, RegExReplacePattern matching
FormatBuild a string from a template

Numbers and time

Abs, Round, Floor, Ceil, Min, Max, Mod, Random, Sqrt, plus FormatTime and DateAdd for timestamps.

Files and folders

FileRead, FileAppend, FileDelete, FileCopy, FileMove, DirCreate, FileExist and SplitPath cover most disk work. Read once into a variable rather than reopening a file inside a loop.

Asking about windows

WinExist, WinActive, WinGetTitle, WinGetPos and ControlGetText return information instead of changing anything, which makes them the natural companions of the actions on the commands page.

Functions as values

SetTimer CheckMail, 60000

CheckMail()
{
    ToolTip "Checking…"
    Sleep 500
    ToolTip
}

A function name used without parentheses is a reference, which is how timers, hotkeys created at runtime and GUI event handlers receive the code they should run.

See the same ideas at full size in examples, or follow the guided path in tutorials.

Frequently asked questions

How do I define a function in AutoHotkey v2?

Write the name, a parameter list in parentheses, then a brace block; use return to hand a value back.

Do functions see global variables?

Not by default. Declare the variable with global inside the function, or pass it in as a parameter.

Can I pass a function to a timer?

Yes. Use the function name without parentheses, for example SetTimer CheckMail, 60000.


AutoHotkeyTools.com is an independent Windows resource covering AutoHotkey tools, scripts, hotkeys, tutorials and desktop automation. It is not affiliated with the AutoHotkey project.