# Notes for AutoIt v2 Users

## Benefits

- Enjoy nearly complete backward compatibility with AutoIt v2. There is no need to learn new syntax and commands unless you want to.
- Use Else with every IF-type command.
- Use blocks (multi-line sections) with IFs and ELSEs (virtually eliminating the need for Goto).
- Use break and continue inside loops (another way to eliminate Goto's).
- Use many new commands and benefit from enhancements to old ones (see below).
- Catch silly errors and typos early (at load-time) rather than later (during runtime) when you may be less prepared to deal with them: Syntax errors are caught as part of the optimization process.
- Gain a significant boost in performance.

## Running AutoIt v2 (.aut) Scripts

AutoHotkey will run most existing .aut scripts without the need to change them. Only the following AutoIt v2 features are not supported:

- Adlib section (SetTimer can be used instead)
- Break (break is now used for loops instead)
- HideAutoItDebug

## Converting Scripts from .aut to .ahk

Although .aut scripts can be run, to take full advantage of AutoHotkey's new features (that is, if you plan to make improvements to the script) you should convert the script to a .ahk file. This is necessary because some commands accept new, optional parameters that if enabled for AutoIt v2 scripts, would cause some of them to behave incorrectly (see further below for details).

You can automatically convert an AutoIt v2 (.aut) script to AutoHotkey format (.ahk) . The conversion will make the escape character an accent/backtick (`) instead of backslash (\). This is harder than it sounds due to the precise ordering of escape sequences in each line, which is why you can't just do a search-and-replace in a text editor. This automated way should take care of all the details:

1. Append a .ahk to the end of an existing .aut filename, so that it now ends in ".aut.ahk"
2. Run this file with AutoHotkey, which, rather than than running the file, will create a new file in the same directory that ends in "-NEW.ahk". This is the converted version. The original version will be unchanged.
3. If you were using #EscapeChar in the script, remove it from the converted version.

After converting a script from .aut to .ahk, the main problem areas to check for are commands that accept additional parameters in .ahk files but not in .aut files. If you used any non-escaped commas in the parameter that was formerly the last parameter (in AutoIt v2) but is now not the last parameter, those commas will be interpreted as delimiters. For example:

    WinActivate, title, text with literal comma, here.

The above would be a problem after conversion; The string "here." would be interpreted as the new "exclude title" parameter.
Here is a list of commands that both accept new parameters and that might be problematic:
StringReplace
StringGetPos
FileSelectFile
FileRemoveDir
WinClose/Kill/Activate/Minimize/Maximize/Restore/Hide/Show
WinSetTitle/WinGetTitle
Note: Even though they accept new parameters in .ahk files, commands such as IfWinExist are not troublesome with respect to the above because the program can tell the difference between the AutoIt v2 and AutoHotkey methods. The WinWait family of commands should also not be a problem, nor should the MsgBox command since it has smart handling of commas.

## Enhanced Syntax

With a few exceptions, floating point numbers (e.g. 3.5) and hexadecimal notation (e.g. 0xFF) are supported by all commands.

The keyword ELSE is supported with all IF-type commands. In addition, blocks are supported. For example:

OLD STYLE:

    IfWinExist, Notepad, , WinActivate, Notepad

NEW STYLE (use {…} to create a block if there’s more than one line to be executed):

    IfWinExist, Untitled - Notepad
    {
        WinActivate   ; no need to specify title again, since it will automatically use the "last found" window.
        WinMaximize  ; if this line weren't here, you wouldn't need a block (braces) around this section
    }
    else
        Run Notepad

Nested IFs and blocks example:

    if varx = 1
    {
        if vary = 2
            if varz = 3
                sleep, 1
            else  ; this else goes with the nearest IF
                sleep, 1
    }
    else  ; this else goes with the top IF because the block prevents it from going with "if vary = y"
        sleep, 1

Also, blocks can be used with loops. But this first example doesn't need a block because the if+else is considered only a single statement:

    Loop, 5000
        IfNotExist, c:\semaphore.txt
            sleep, 1000
        else
            break  ; terminate the loop early

Here's one that does require a block:

    Loop  ; Since there's no count specified, it's an infinite loop unless an Exit, Return, or Break is encountered.
    {
        ...
        if var <= 5
            continue  ; skip the rest of the block and begin at the top of the block for the next iteration.
        ...
        if var > 25
            break  ; break out of the loop
    }

Example of a file-loop to explore the contents of a folder (registry-loops and parsing-loops are also supported):

    Loop, %A_ProgramFiles%\*.txt, , 1  ; Recurse into subfolders.
    {
        MsgBox, 4, , Filename = %A_LoopFileFullPath%`n`nContinue?
        IfMsgBox, No
            break
    }

Finally, complex expressions and function calls are supported, such as the following:

    NetPrice := Price * (1 - Discount/100)

    LargestOfTwo := Max(x, y)

    if (CurrentSetting > 100 or FoundColor <> "Blue")
        MsgBox The setting is too high or the wrong color is present.

## Other differences between AutoIt v2 and AutoHotkey

AutoIt v2 (.aut) scripts are run by AutoHotkey.exe with:

- backslash (\) as their escape character. But other script types (.ahk, .ini) use accent (`). Use #EscapeChar to change these defaults.
- support for same-line comments disabled (use #AllowSameLineComments to enable them).
- the pound sign (#) as a comment character in the Send command. Other script types use # to indicate the windows key. For example, #y would send Win-Y.
- DetectHiddenText defaulting to OFF. Other script types default to ON because it performs better.
- SetBatchLines defaulting to 1, meaning that scripts run fairly slowly by default. Other script types use 10ms.
- SetWinDelay defaulting to 500. Other script types default to 100, which makes windowing operations much faster.
- extended (new) parameters disabled for the following commands. This is done for compatibility reasons (see conversion notes above):
  MsgBox
  FileSelectFile
  FileRemoveDir
  IniRead
  StringReplace
  StringGetPos
  WinClose
  WinKill
  WinActivate
  WinMinimize
  WinMaximize
  WinRestore
  WinHide
  WinShow
  WinSetTitle
  WinGetTitle

AutoIt v2 (.aut) scripts are not supported by the script compiler (Ahk2Exe) because there's no way for the compiled script to figure out whether to run in AutoIt v2 mode or AutoHotkey mode. So first convert your .aut script to .ahk before compiling it (see above).

Unlike AutoIt v2, IfGreater/Less compare alphabetically whenever one of the inputs isn't purely numeric.

IniWrite and IniDelete: For AutoIt v2 (.aut) scripts: ErrorLevel is not set by these commands. For other script types, ErrorLevel is set to 1 if there was a problem or 0 otherwise.

InputBox: For AutoIt v2 (.aut) scripts: If the user presses the cancel button, the output variable is made blank so that there is a way to detect that the cancel button was pressed. For AutoHotkey scripts: The output variable is set to whatever the user entered, even if the user pressed the cancel button. To tell the difference, ErrorLevel is set to 1 if Cancel, Alt-F4, or the X-button was pressed to dismiss the window. Otherwise, ErrorLevel is set to 0. This allows the cancel button to specify that a different operation should be performed on the entered text.

SplashTextOn: AutoIt v2 (.aut) scripts use splash windows that are a little less tall than those in AutoHotkey scripts. So if you convert a .aut script to .ahk, or copy & paste code from a .aut script into a .ahk script, you might want to reduce the height of the window by the height of its title bar (probably around 20 pixels, but it depends on your desktop settings).

Finally, unlike AutoIt v2, AutoHotkey does not store its variables as environment variables. This is because performance would be worse and also because the operating system limits such variables to 32 KBytes. To explicitly place a value into an environment variable, use EnvSet, not SetEnv.

## New Language and Command Style

Same-line comments can be used if the file extension of the script isn't .aut (AutoIt v2). The semicolon is used as a prefix character for these comments, just as it is for whole line comments. However, a semicolon is not considered a comment unless there is at least one space or tab to the left of it. If there's ever a need to have a literal semicolon with a space or tab to its left, you can escape it by preceding it with an accent/backtick (`). In both of the following examples, a literal semicolon is stored in the variable:
var = `;
var =;

For convenience, the first comma may be omitted (except when the first parameter is blank or starts with := or =, or the command is alone at the top of a continuation section). For example: Sleep 1, MsgBox test, etc.

For some commands, you can optionally use a new style in lieu the original AutoIt v2 style. These are:

- Var = value ; can be used instead of SetEnv, var, value. Value can be blank, i.e. var =
- if var <> value ; you can use <> != < = > as comparison operators rather than ifequal/notequal/greater, etc.
- var += 5 ; This is equivalent to envadd, var, 5. The other operators are -=, *=, /=
- But don't use the new command style on the same line as an old command:

      IfEqual, x, 35, y = 55 ; The y = 55 part will not be properly recognized as the action of the IF.
      ; Instead, do this:
      IfEqual, x, 35, SetEnv, y, 55
      ; Or this:
      IfEqual, x, 35
          y = 55

You can also check whether a variable matches one of the items in a list:
if var [not] in item1,item2,item3 ; Exact match
if var [not] contains item1,item2,item3 ; Substring match.

... or whether a variable is between two values:
if var [not] between 5 and 10

... or whether a variable conforms to a specified data type:
if var is number
if var is not float ; not floating point

The SetTitleMatchMode command has been improved: In addition to supporting the traditional modes of 1 & 2, the command now supports the words fast and slow (for example: SetTitleMatchMode, slow). The default is fast, which is what AutoIt v2 uses. By contrast, the slow mode can "see" more text for certain types of windows. The fast mode performs significantly better, which may help the speed of scripts that that do a lot of windowing commands. The slow mode need only be used when there is no other way to uniquely identify a given window. The version of Window Spy included with the program indicates which text of a window is available only in the slow mode.

## Enhanced Commands

For most of the window commands, such as WinActivate, passing zero parameters results in activating the window most recently found by IfWinExist or WinWait. In addition, passing the letter A for the window title tells the command to act upon the currently-active (foreground) window. For example: WinClose, A

Also, most of the Window commands support new parameters for Exclude-Title and Exclude-Text. A window that would otherwise be a match will be disqualified if its Title contains Exclude-Title or its text contains Exclude-Text.

StringGetPos now supports a new optional last parameter. If that parameter is the letter R, the search will be conducted from the right instead of the left, that is, the last occurrence will be found rather than the first.

MouseClick supports a new parameter, which if the letter D, holds down the button until it is released by the user physically clicking it or via another action in the script. If this last parameter is U, the button will be released (even if it wasn't down before, an up-event will still be sent). In addition, you may find the syntax of the new Click command to be easier and more flexible.

A_Space and A_Tab are two new built-in variables, which contain a single space and single tab character, respectively. This avoids the need for a workaround to get a variable to contain a space. For example:

    String = String with spaces
    IfInString, String, %A_SPACE%
        MsgBox, A space was found.
    ; But to assign a naked space to a variable of your own, be sure to turn off AutoTrim so that the
    ; assignment won't remove all leading and trailing spaces:
    AutoTrim, off
    MySpace = %A_SPACE%

ClipboardAll is a new built-in variable containing everything on the clipboard (such as pictures and formatting). It can be used to back up one or more "saved clipboards" to memory or disk, which can be restored at a later time. This is especially useful for allowing a script to make temporary use of the clipboard without fear of disturbing whatever the user may have stored on it.

Run and RunWait can run shortcuts (.lnk files), documents, and URLs. For example:

    Run, www.yahoo.com
    RunWait, New Document.doc

In addition, they now support the following system verbs: properties, edit, print, find, explore, open, and print. For example:

    Run, properties c:\autoexec.bat  ; Bring up the properties dialog for this file.
    Run, edit %A_SCRIPTFULLPATH%  ; Perform the associated "edit" action for this file (if it has one).

Send and ControlSend have been enhanced so that you do not need to use the Sleep command to allow the user time to release the modifier keys (Ctrl/Alt/Shift/Win) with hotkeys that use the Send command. The Send command knows to change the modifiers to what they need to be for every key that will be sent.

StringReplace can optionally replace all occurrences, via passing a last parameter "A".

StringGetPos now supports a new optional last parameter. If that parameter is the letter R, the search will be conducted from the right instead of the left. In other words, the last occurrence will be found rather than the first.

MsgBox supports a new optional last parameter: Timeout value (in seconds, after which the MsgBox will close. IfMsgBox will see the value TIMEOUT in this case). For compatibility reasons, this new parameter is only supported if the script filename doesn't end in .aut.

IniRead supports a new optional last parameter: the default value to put into the output variable if the command fails for any reason. For compatibility reasons, this new parameter is only supported if the script filename doesn't end in .aut.

FileSelectFile has been improved with new capabilities.

## New Commands and Features

Here are some of the most noteworthy new commands and features:

GUI: Create and manage graphical user interface (GUI) windows and controls. Build your own professional looking applications and forms without the hassle and complexity of a programming language.

Menu: Build your own custom menu bars, tray icon menus, and popup menus.

Hotkeys: For keyboard, joystick, and mouse.

Hotstrings: Have abbreviations expand automatically as you type them (auto-replace).

DllCall: Call functions inside DLLs, such as standard Windows API functions.

OnMessage: Specifies a function to run automatically when the script receives the specified message (from the operating system, an external program, or some other script).

SendInput and SendPlay: These are two new methods for sending keystrokes and mouse clicks with greater speed and reliability. In addition, SendPlay is able to send keystrokes and mouse clicks to a broader variety of games than other modes.

Progress and SplashImage: Display progress bars and images, with optional accompanying text.

OnExit: Have a subroutine run automatically whenever the script exits. A script can also use this to detect whether the user is logging off or the system is shutting down.

Process: Performs one of the following operations on a process: checks if it exists; changes its priority; closes it; waits for it to close.

SoundSet: Changes various settings of a sound device (master mute, master volume, etc.)

SetTimer: Run one or more subroutines automatically at intervals of your choice.

ClipWait: Wait for the clipboard to contain text (become non-empty).

StatusBarWait: Wait for the status bar of a window to contain the specified text, or become blank.

StatusBarGetText: Retrieve text from the status bar.

WinActivateBottom: This command is similar to WinActivate but activates the oldest (bottom-most) window rather than the newest. If there is only one window that matches, this command will perform identically to WinActivate.

DriveSpaceFree, DriveGet, and Drive: Retrieves and changes various information about a Drive (e.g. its free space).

AutoTrim, on/off (defaults to on): When you assign a value to a variable, this controls whether whitespace is automatically trimmed from the left and right of the string. For this purpose, whitespace consists of spaces and tabs, but NOT newlines/linefeeds. Thus, I believe the "on" setting yields the same behavior as AutoIt v2 in this regard.

StringUpper and StringLower: Convert a string to uppercase or lowercase.

ControlFocus, ControlSetText, Control, ControlGet: These and other Control commands operate directly upon the controls of a window.

SoundPlay: Play virtually any type of media file that the OS supports.

SoundGet, SoundSet, and SoundSetWaveVolume: Retrieves and changes various settings of a sound device (master mute, master volume, wave volume, etc.)

PixelGetColor and PixelSearch: These commands are capable of detecting the colors of dots on the screen, which can help respond to the changing state of an application or game.

GetKeyState: Find out whether a key or mouse/joystick button is down or up; find out the position of a joystick axis; etc.

WinMenuSelectItem: Invoke menu bar items directly, even if the target window isn't active.

#AllowSameLineComments: To increase compatibility with AutoIt v2, scripts that end in .aut are normally not permitted to have same-line comments (for example: Run, notepad ; this is a comment). Add the line #AllowSameLineComments to the top of your script to allow them.

#SingleInstance: Specifying this anywhere in a script will prevent new instances of that script from being launched once there is already one running. Instead, you will be prompted for whether to keep the original (old) instance or replace it with the new instance.

#EscapeChar: The escape character is normally "`" but this allows you to change it to AutoIt v2's escape character (backslash) or some other char of your choice. Note that by default, scripts that end in .aut will use the backslash for their escape char.

Suspend (and tray menu item of the same name): This function prevents new hotkey subroutines from launching (it will not halt any subroutines that are already running -- use Pause for that).

Pause (and tray menu item of the same name): Unlike Suspend -- which disables hotkeys entirely -- pause will freeze the currently running subroutine (if none, pause will have no effect).

Files-and-folders loops, registry-loops, and enhanced loops.

The concept of a Window Group is supported. Once defined, a group can be traversed via the GroupActivate command.

Finally, there are many other new commands, which can be viewed in the alphabetical command list.