Saturday 1 March 2008

autoitcripts

AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI. It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks in a way not possible or reliable with other languages (e.g. VBScript and SendKeys).

AutoIt was initially designed for PC "roll out" situations to configure thousands of PCs, but with the arrival of v3 it is also well suited to performing home automation and the scripting of repetitive tasks.

AutoIt can:

  • Execute Windows and DOS executables
  • Simulate key strokes (supports most keyboards layouts)
  • Simulate mouse movements and clicks
  • Move, resize and manipulate windows
  • Interact directly with "controls" on a window (set/get text, move, disable, etc.)
  • Work with the clipboard to cut/paste text items
  • Work with the registry

Unlike AutoIt v2, the new v3 language has a much more standard syntax -similar to VBScript and BASIC - and now supports complex expressions, user functions, looping and everything else that veteran scripters would expect.

As with previous versions, AutoIt has been designed to be as small as possible and stand-alone with no external .dll files or registry entries required. Scripts can also be compiled into stand-alone executables with Aut2Exe.

There have also been updates to the ActiveX and DLL versions of AutoIt called AutoItX - unlike v2 this will be a combined control (COM and standard DLL functions in the same DLL). AutoItX will allow you to add the unique features of AutoIt to your own favourite scripting or programming languages! See the AutoItX Help file (Start \ AutoIt v3 \ Extras \ AutoItX \ AutoItX Help File) for more information and examples.

Best of all, AutoIt continues to be FREE - but if you want to support the time, money and effort spent on the project and web hosting then you may donate at the AutoIt homepage.

What's New?

v3 has a completely different syntax to v2.64 so old scripts are not compatible. However, v2.64 will continue to be supported and downloadable. Both AutoIt v3 and v2.64 can be installed on the same machine together without any problems and you can keep your old scripts intact. v2 uses the .aut extension and v3 uses .au3. There is rarely a need to rewrite a working v2.64 script for v3.

v3 has the same concepts as previous versions with windows titles and text and keyboard and mouse simulation but has many new features:

Controls

Directly get information on and interact with edit boxes, check boxes, list boxes, combos, buttons, status bars without the risk of keystrokes getting lost. Even work with controls in windows that aren't active!

Language Upgrades

"Proper" numbers, unlimited-length strings, complex expressions, if statements, select, while loops, for loops, do loops, functions, arrays, excellent string handling (over 25 functions!) - the list goes on. Everything you need to make your automation routines as painless as possible. Yes, this is a GUI automation language but the syntax in v3 is powerful enough for general purpose scripting. Old versions of AutoIt were often referred to as "not a proper language". Not any more.

Key and Mouse Simulation

Much time has been spent optimizing the keystroke and mouse simulation functions to be as accurate as possible on all current operating systems. The mouse functions also look more "human" in this version and can even be used to create slick demo scripts. All the mouse and keyboard routines are highly configurable both in terms of simulation "speed" and functionality.

Window Management

In addition to the "title/text" v2 way of accessing windows you can also access windows by their class names and handles. As usual you can expect to move, hide, show, resize, activate, close and pretty much do what you want with windows.

And much, much more.

Software License

AutoIt v3


Author : Jonathan Bennett and the AutoIt Team
WWW : http://www.autoitscript.com/autoit3/
Email : support at autoitscript dot com
________________________________________________________

END-USER LICENSE AGREEMENT FOR THIS SOFTWARE
Important - read carefully:

This End-User License Agreement ("EULA") is a legal agreement between you (either an individual or a single entity) and the mentioned author of this Software for the software product identified above, which includes computer software and may include associated media, printed materials, and "online" or electronic documentation ("SOFTWARE PRODUCT"). By installing, copying, or otherwise using the SOFTWARE PRODUCT, you agree to be bound by the terms of this EULA. If you do not agree to the terms of this EULA, do not install or use the SOFTWARE PRODUCT.

SOFTWARE PRODUCT LICENSE

The SOFTWARE PRODUCT is protected by copyright laws and international copyright treaties, as well as other intellectual property laws and treaties. The SOFTWARE PRODUCT is licensed, not sold.

The definition of SOFTWARE PRODUCT includes any files generated by the SOFTWARE PRODUCT, such as compiled script files in the form of standalone executables.

1. GRANT OF LICENSE.

This EULA grants you the following rights:

Installation and Use. You may install and use an unlimited number of copies of the SOFTWARE PRODUCT.

Reproduction and Distribution. You may reproduce and distribute an unlimited number of copies of the SOFTWARE PRODUCT either in whole or in part; each copy should include all copyright and trademark notices, and shall be accompanied by a copy of this EULA. Copies of the SOFTWARE PRODUCT may be distributed as a standalone product or included with your own product.

Commercial Use. You may sell for profit and freely distribute scripts and/or compiled scripts that were created with the SOFTWARE PRODUCT.

2. COPYRIGHT.

All title and copyrights in and to the SOFTWARE PRODUCT (including but not limited to any images, photographs, animations, video, audio, music, text, and "applets" incorporated into the SOFTWARE PRODUCT), the accompanying printed materials, and any copies of the SOFTWARE PRODUCT are owned by the Author of this Software. The SOFTWARE PRODUCT is protected by copyright laws and international treaty provisions. Therefore, you must treat
the SOFTWARE PRODUCT like any other copyrighted material.

MISCELLANEOUS

If you acquired this product in the United Kingdom, this EULA is governed by the laws of the United Kingdom.

If this product was acquired outside the United Kingdom, then local law may apply.

Should you have any questions concerning this EULA, or if you desire to contact the author of this Software for any reason, please contact him/her at the email address mentioned at the top of this EULA.

LIMITED WARRANTY

NO WARRANTIES.
The Author of this Software expressly disclaims any warranty for the SOFTWARE PRODUCT. The SOFTWARE PRODUCT and any related documentation is provided "as is" without warranty of any kind, either express or implied, including, without limitation, the implied warranties or merchantability, fitness for a particular purpose, or non-infringement. The entire risk arising out of use or performance of the SOFTWARE PRODUCT remains with you.

NO LIABILITY FOR DAMAGES.
In no event shall the author of this Software be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or any other pecuniary loss) arising out of the use of or inability to use this product, even if the Author of this Software has been advised of the possibility of such damages. Because some states/jurisdictions do not allow the exclusion or limitation of liability for consequential or incidental damages, the above limitation may not apply to you.

Install Directory Structure

The AutoIt installer creates a directory structure (usually located in \Program Files\AutoIt3) summarized in the following table. The installer also creates Start Menu shortcuts, but no other files are added or modified.

Files and Directories Description
(Top-level files)
AutoIt3.exe The AutoIt main program and only file required to run scripts!
AutoIt3A.exe The ANSI version of AutoIt3.exe for Windows 9x.
AU3Info.exe The AutoIt Window Info Tool.
AU3InfoA.exe The ANSI version of Au3Info.exe for Windows 9x.
AU3Check.exe The AutoIt syntax checker.
AutoIt.chm This help file which use AutoIt3.chm and UDFs3.chm
psapi.dll Process...() function helper DLL - used under Windows NT 4 only (Microsoft redistributable file)
Uninstall.exe The AutoIt uninstaller.
AutoIt v3 Website.url A shortcut to http://www.autoitscript.com/autoit3/
Aut2Exe

Icons\ Contains icons used for the .au3 filetype icon in Explorer.

Aut2Exe.exe The script compiler.

Aut2ExeA.exe The ANSI version of Aut2Exe for Windows 9x .

AutoItSC.bin Executable stub for compiled scripts

UPX.exe The UPX compressor (shinks the size of exe files).
Examples

GUI\ Contains examples of GUIs written in AutoIt.

Helpfile\ Contains scripts used in many of the help file examples.
Extras

AutoUpdateIt\ Contains a script for easily retrieving the latest version of AutoIt3.

Editors\ Contains syntax coloring definitions for some popular text editors.

Exe2Aut\ Contains utils for converting compiled scripts back in to source code.
SQLite\ Contains SQLite command line executable and an help file.

v2_to_v3_Converter\ Contains a tool for converting v2.64 script to AutoIt v3 syntax.
Icons

Contains icons used for the .au3 filetype icon in Explorer.
Include

Contains standard include files (pre-written user functions). See the Library Functions)
AutoItX

Contains a DLL version of AutoIt v3 that provides a subset of the features of AutoIt via an ActiveX/COM and DLL interface.
SciTe

Contains a light version of SciTe which allows syntax coloring.

It should be repeated that to run AutoIt scripts, the only required file is AutoIt3.exe. If you compile a script into an executable then a user does not require AutoIt to be installed to run that compiled executable.

(exception: Under Windows NT 4 the file PSAPI.dll needs to be in the path or AutoIt directory for the Process...() related functions to work)

Registry Keys

The AutoIt installer creates registry keys under HKEY_LOCAL_MACHINE\Software\AutoIt v3 and HKEY_CURRENT_USER\Software\AutoIt v3. The keys are NOT used/created when AutoIt utilities are run on machines that lack a full AutoIt installation--AutoIt is "clean" to run on servers, etc.

The table below shows the default (or typical) registry keys. The keys in italic are not created by the installer itself but by the first execution of the corresponding utility:
HKEY_LOCAL_MACHINE\SOFTWARE\AutoIt v3\
AutoIt

(Default) REG_SZ (value not set)

InstallDir REG_SZ C:\Program Files\AutoIt3

Version REG_SZ Version Number


HKEY_CURRENT_USER\Software\AutoIt v3\
Aut2Exe

(Default) REG_SZ (value not set)

AllowDecompile REG_DWORD 0x1

LastCompression REG_DWORD 0x2

LastExeDir REG_SZ My Documents

LastIcon REG_SZ

LastIconDir REG_SZ C:\Program Files\AutoIt3\Aut2Exe\Icons

LastScriptDir REG_SZ My Documents
AutoUpdateIt

(Default) REG_SZ (value not set)

DoneOption REG_SZ Notify

DownloadDir REG_SZ C:\Downloads\ForExample\
Exe2Aut

(Default) REG_SZ (value not set)

LastExeDir REG_SZ C:\ForExample\

LastScriptDir REG_SZ
AU3Info

Default REG_SZ (value not set)

AlwaysOnTop REG_DWORD 0x1

ColorMode REG_DWORD 0x1

CoordMode REG_DWORD 0x1

HighlightColor REG_DWORD 0x0

HighlightControls REG_DWORD 0x1

Magnify REG_DWORD 0x0

WinH REG_DWORD 0x01c2

WinW REG_DWORD 0x012c

WinX REG_DWORD 0x0064

WinY REG_DWORD 0x0064

Frequently Asked Questions (FAQ)

This section gives some of the more frequently asked questions from the forum. If you can't find the answer you seek here then the forum should be your first port of call.

Questions

1. Why doesn't my old AutoIt v2.64 script run in v3?

2. Isn't v3 much more difficult than previous versions?

3. How can I convert my v2.64 scripts to v3?

4. Where is the "goto" command?

5. How can I run a DOS program from within AutoIt?

6. Why can I only use Run() to execute .exe and .com files? What about .msi / .txt and others?

7. Why do I get errors when I try and use double quotes (") ?

8. What do the window "title" and "text" parameters mean?

9. Why can't I print a variable using "My var is $variable"?

10. When I use Send() to send a variable odd things happen?

11. What is the difference between the return value and @error?

12. How can I exit my script with a hot-key?

13. How can I use a custom icon when compiling my scripts?

14. How can I make sure only one copy of my script is run?

15. What are the current technical limits of AutoIt v3?

16. I get a missing picture symbol in the Help file under the Examples.

1. Why doesn't my old AutoIt v2.64 script run in v3?

v3 has a different language structure to v2.64.

Previous versions of AutoIt were fine for what they were designed for - writing simple scripts to help with software installations. Over time people began using it for general and complicated scripting tasks. The old syntax and structure made this possible but very very difficult and cumbersome. The decision was made to make AutoIt more suitable for general automation tasks and to achieve that a more standard and basic-like language was made. This also means that if you already know a scripting language you will pick AutoIt v3 up easily.

Back To Top

2. Isn't v3 much more difficult than previous versions?

No. In fact in many instances it's much easier than previous versions as you don't have to try and force the language to do something it was never designed to do. It also uses a familiar BASIC-like language, and BASIC is known for being...well...basic :)

The vast majority of old AutoIt scripts were focused around software installation and clicking "Next" a lot in dialog boxes. Most of these scripts can be converted to v3 simply by adding a couple of brackets here and there. Here is an example of such a script in v2 and v3 (simulating a software installation with a few dialogs that have a Next button and a Finish button)

; v2.64 Script
WinWaitActive, Welcome, Welcome to the XSoft installation
Send, !n
WinWaitActive, Choose Destination, Please choose the
Send, !n
WinWaitActive, Ready to install, Click Next to install
Send, !n
WinWaitActive, Installation Complete, Click Finish to exit
Send, !f
WinWaitClose, Installation Complete

; v3 Script
WinWaitActive("Welcome", "Welcome to the XSoft installation")
Send("!n")
WinWaitActive("Choose Destination", "Please choose the")
Send("!n")
WinWaitActive("Ready to install", "Click Next to install")
Send("!n")
WinWaitActive("Installation Complete", "Click Finish to exit")
Send("!f")
WinWaitClose("Installation Complete")

Now, that wasn't so bad! :) As all "strings" are enclosed in quotes you no longer have to wrestle with problems caused by leading and trailing spaces in text. There is also fantastic support for many text editors so that when you are writing v3 scripts you can have syntax highlighting which makes everything much easier.

Back To Top

3. How can I convert my v2.64 scripts to v3?

The first thing you should ask yourself is "Do I need to convert my script?". v2.64 will continue to be downloadable and supported so don't update all your scripts just for the sake of it - well not unless you want to :)

There is a section in the Help file that shows how the commands in v2 and v3 are related - click here to see the page.

One of the AutoIt v3 authors has written a utility to automatically convert v2 scripts to v3. Conversion is pretty good unless your code is a rats-nest of gotos :) You can find the converter in the "Extras" directory (Start \ AutoIt v3 \ Extras - or look in the directory that you installed AutoIt v3).

Back To Top

4. Where is the "goto" command?

Gone. It's evil. No, you can't ask why - it just is. It's like that lump of rock they find in the microwave at the end of the film Time Bandits :)

AutoIt v3 features most of the common "loops" in use today and with these Goto is no longer required. Look up While, Do, For, ExitLoop, ContinueLoop and Functions for the modern way of doing things :) And while you are looking at help file sections check out these on loops, conditional statements and functions. I promise you, once you have got the hang of such things you will be able to script in virtually any other language within a couple of minutes.

Just to get you started, the most basic use of Goto in version 2.64 was an infinite loop like:

:mylabel
...do something...
...and something else...
goto, mylabel

A simple v3 version of that is a While loop that is always "true".

While 1 = 1
...do something...
...do something else...
Wend

Back To Top

5. How can I run a DOS program from within AutoIt?

If you wanted to run something like a DOS "Dir" command then you must run it though the command interpreter (command.com or cmd.exe depending on your OS). The @Comspec macro contains the correct location of this file. You should use the RunWait() function as it waits for the DOS program to finish before continuing with the next line of the script. Here is an example of running the DOS Dir command on the C: drive: (effectively running the command command.com /c Dir C:\ )

RunWait(@COMSPEC & " /c Dir C:\")

Back To Top

6. Why can I only use Run() to execute .exe files? What about .msi / .txt and others?

Only a few file extensions are usually "runable" - these are .exe, .bat, .com, .pif. Other file types like .txt and .msi are actually executed with another program. When you double click on a "myfile.msi" file what actually happens in the background is that "msiexec.exe myfile.msi" is executed. So to run a .msi file from AutoIt you would do:

RunWait("msiexec myfile.msi")

Or, run the command "start" which will automatically work out how to execute the file for you:

RunWait(@COMSPEC & " /c Start myfile.msi")

Or, use the ShellExecuteWait function which will automatically work out how to execute the file for you:

ShellExecuteWait("myfile.msi")

Back To Top

7. Why do I get errors when I try and use double quotes (") ?

If you want to use double-quotes inside a string then you must "double them up". So for every one quote you want you should use two. For example if you wanted to set a variable to the string: A word in "this" sentence has quotes around it! You would do:

$var = "A word in ""this"" sentence has quotes around it!"

or use single quotes instead:

$var = 'A word in "this" sentence has quotes around it!'

Back To Top

8. What do the window "title" and "text" parameters mean?

There is a detailed description here.

Back To Top

9. Why can't I print a variable using "My var is $variable"?

If you have a variable called $msg and you want to print in inside a MsgBox then this will NOT work:

MsgBox(0, "Example", "My variable is $msg")

It will actually print My variable is $msg . What you need to do is tell AutoIt to join the string and the variable together using the & operator:

MsgBox(0, "Example", "My variable is " & $msg)

Advanced: If you have many variables to add into a string then you may find the StringFormat() function useful. For example, if I wanted to insert $var1 to $var5 into a string then it may be easier to do:

$msg = StringFormat("Var1 is %s, Var2 is %s, Var3 is %s, Var4 is %s, Var5 is %s", $var1, $var2, $var3, $var4, $var5)
MsgBox(0, "Example", $msg)

Back To Top

10. When I use Send() to send a variable odd things happen?

If you are sending the contents of a variable then be mindful that if it contains special send characters like ! ^ + {SPACE} then these will be translated into special keystrokes - rarely what is wanted. To overcome this use the RAW mode of Send() that does not translate special keys:

Send($myvar, 1)

Back To Top

11. What is the difference between the return value and @error?

Generally a return value is used to indicate the success of a function. But, if a function is already returning something ( like WinGetText() ) then we need to have a way of working out if the function was successful, so we set @error instead.

Back To Top

12. How can I exit my script with a hot-key?

Ah, an easy one. If you want to make your script exit when you press a certain key combination then use the HotKeySet() function to make a user function run when the desired key is pressed. This user function should just contain the Exit keyword.

Here some code that will cause the script to exit when CTRL+ALT+x is pressed:

HotKeySet("^!x", "MyExit")
...
...
; Rest of Script
...
...
Func MyExit()
Exit
EndFunc

Back To Top

13. How can I use a custom icon when compiling my scripts?

You need to run the full compiler program (rather than just right-clicking a script and selecting compile). This page describes the compiler in detail.

Back To Top

14. How can I make sure only one copy of my script is run?

The easiest way is to rename the title of the hidden AutoIt window when your script first starts. Then in the same script check for that window title existing - if it does then another copy of the script is running.


; Place at the top of your script
$g_szVersion = "My Script 1.1"
If WinExists($g_szVersion) Then Exit ; It's already running
AutoItWinSetTitle($g_szVersion)
; Rest of your script goes here

Back To Top

15. What are the current technical limits of AutoIt v3?

Here are details of the current technical limits of AutoIt. Please note that some of the limits are theoretical and you may run into performance or memory related problems before you reach the actual limit.

Maximum length of a single script line: 4,095
Maximum string length: 2,147,483,647 characters

Number range (floating point): 1.7E–308 to 1.7E+308 with 15-digit precision
Number range (integers): 64-bit signed integer
Hexadecimal numbers: 32-bit signed integer (0x80000000 to 0x7FFFFFFF)

Arrays: A maximum of 64 dimensions and/or a total of 16 million elements
Maximum depth of recursive function calls: 384 levels

Maximum number of variables in use at one time: No limit
Maximum number of user defined functions: No limit

Maximum number of GUI windows: 1024
Maximum number of GUI controls per window: 4096

Back To Top

16. I get a missing picture symbol in the Help file under the Examples.

This should be the Open button that enable you to open the Examples in the Help file.
This issue is that the hhctrl.ocx isn't properly registered or corrupted.
Try registering it by doing "regsvr32 hhctrl.ocx" from the command prompt or check if the file is still valid.

Back To Top

Running Scripts

When you start AutoIt you will be asked to open a script file. A script file is a simple text file containing AutoIt keywords and functions that tell AutoIt what you want it to do. Script files are created in a simple text editor such as notepad.exe or a much better alternative.

Although AutoIt v3 scripts are just plain-text files they are usually given the file extension .au3 to help tell the difference between a script and a text file. If you used the full installer to install AutoIt you can execute an AutoIt script simply by double-clicking it. There are also various options to open, edit, or compile a script if you right-click on the .au3 file.

Here is an example script. Notice that ; is used for comments (much like REM in DOS batch files):

; This is my first script
MsgBox(0, "My First Script!", "Hello World!")

More complicated scripts may use functions, which are usually placed at the end of a script. Here is a similar script using functions:

; This is my second script (with functions)
MsgBox(0, "My second script!", "Hello from the main script!")
TestFunc()

Func TestFunc()
MsgBox(0, "My Second Script!", "Hello from the functions!")
EndFunc

Command Line Parameters

The special array $CmdLine is initialized with the command line parameters passed in to your AutoIt script. Note the scriptname is not classed as a parameter; get this information with @ScriptName instead. A parameter that contains spaces must be surrounded by "double quotes". Compiled scripts accept command line parameters in the same way.

$CmdLine[0] is number of parameters
$CmdLine[1] is param 1 (after the script name)
$CmdLine[2] is param 2 etc
...
$CmdLine[$CmdLine[0]] is one way to get the last parameter...

So if your script is run like this:

AutoIt3.exe myscript.au3 param1 "this is another param"

$CmdLine[0] equals... 2

$CmdLine[1] equals... param1

$CmdLine[2] equals... this is another param

@ScriptName equals... myscript.au3

In addition to $CmdLine there is a variable called $CmdLineRaw that contains the entire command line unsplit, so for the above example:

$CmdLineRaw equals... myscript.au3 param1 "this is another param"

If the script was compiled it would have been run like this:

myscript.exe param1 "this is another param"

$CmdLineRaw equals... param1 "this is another param"

Note that $CmdLineRaw just return the parameters.

Note : only 63 parameters can be return by $CmdLine[...], but $CmdLineRaw will always returns the entire command line.

AutoIt specific command Line Switches

Form1: AutoIt3.exe [/ErrorStdOut] [/AutoIt3ExecuteScript] file [params ...]
Execute an AutoIt3 Script File


/ErrorStdOut Allows to redirect fatal error to StdOut which can be captured by an application as Scite editor. This switch can be used with a compiled script.

To execute a standard AutoIt Script File 'myscript.au3', use the command:
'AutoIt3.exe myscript.au3'

Form2: Compiled.exe [/ErrorStdOut] [params ...]
Execute an compiled AutoIt3 Script File produced with Aut2Exe.

Form3: Compiled.exe [/ErrorStdOut] [/AutoIt3ExecuteScript file] [params ...]
Execute another script file from a compiled AutoIt3 Script File. Then you don't need to fileinstall another copy of AutoIT3.exe in your compiled file.


Form4: AutoIt3.exe [/ErrorStdOut] /AutoIt3ExecuteLine "command line"
Execute one line of code.

To execute a single line of code, use the command:
Run(@AutoItExe & ' /AutoIt3ExecuteLine "MsgBox(0, ''Hello World!'', ''Hi!'')"')

The tray icon will not be displayed when using /AutoIt3ExecuteLine

NOTE: Correct usage of single- and double- quotation marks is important, even double single.

AutoIt on Windows Vista

Windows Vista brings new security features to restrict the running of files that require administrative rights. Even administrator users will be prompted every time an executable runs which will perform some administrative operation (such as writing to the registry key HKEY_LOCAL_MACHINE or writing to the C:\Windows directory). This is called User Account Control (UAC).

By default AutoIt scripts run with standard user permissions but AutoIt has been coded to allow the script writer the option to "tag" a script in order to tell AutoIt if it needs to run with full admin rights or not.

To force a script to attempt to run itself with administrative rights add the #requireadmin directive at the top of your script as follows:

; This script requires full Administrative rights
#requireadmin

MsgBox(0, "Info", "This script has admin rights! ")

When the script runs AutoIt will check if it already has full admin rights and if not it will cause the operating system to prompt the user for permission as shown in "UAC Prompts". If permission is not given by the user the script will terminate.

UAC Prompts

The prompts that Vista will show when launching a program with administrative rights are shown below. The type of prompt displayed will depend on if the user is a "standard user" or an "adminstrator user" (remember even administrators need to get elevated permissions to perform admin operations). Note: The prompts shown are for the digitally signed version of AutoIt - all release versions are signed but beta versions may not be and will give a warning as shown in "Compiled Scripts" below.

Standard User Prompt

A standard user must select a user name and enter a password in order to continue and run the script with elevated rights.

Administrator User Prompt

As the user is already an administrator and just requires elevation the user needs only to click on continue - no password is needed.

Compiled Scripts

Compiled scripts (and possibly beta versions of AutoIt) are not digitally signed and will give a more serious looking warning as shown:

The user must click on Allow to continue (or enter a password if they are a standard user).

If you have your own Authenticode signature you may sign your compiled scripts yourself.

Important: Whether AutoIt or a compiled script is signed or not, you should only run scripts from sources you trust!

Even signed code can be malicious!

Command Line Parameters

The special array $CmdLine is initialized with the command line parameters passed in to your AutoIt script. Note the scriptname is not classed as a parameter; get this information with @ScriptName instead. A parameter that contains spaces must be surrounded by "double quotes". Compiled scripts accept command line parameters in the same way.

$CmdLine[0] is number of parameters
$CmdLine[1] is param 1 (after the script name)
$CmdLine[2] is param 2 etc
...
$CmdLine[$CmdLine[0]] is one way to get the last parameter...

So if your script is run like this:

AutoIt3.exe myscript.au3 param1 "this is another param"

$CmdLine[0] equals... 2

$CmdLine[1] equals... param1

$CmdLine[2] equals... this is another param

@ScriptName equals... myscript.au3

In addition to $CmdLine there is a variable called $CmdLineRaw that contains the entire command line unsplit, so for the above example:

$CmdLineRaw equals... myscript.au3 param1 "this is another param"

If the script was compiled it would have been run like this:

myscript.exe param1 "this is another param"

$CmdLineRaw equals... param1 "this is another param"

Note that $CmdLineRaw just return the parameters.

Note : only 63 parameters can be return by $CmdLine[...], but $CmdLineRaw will always returns the entire command line.

AutoIt specific command Line Switches

Form1: AutoIt3.exe [/ErrorStdOut] [/AutoIt3ExecuteScript] file [params ...]
Execute an AutoIt3 Script File


/ErrorStdOut Allows to redirect fatal error to StdOut which can be captured by an application as Scite editor. This switch can be used with a compiled script.

To execute a standard AutoIt Script File 'myscript.au3', use the command:
'AutoIt3.exe myscript.au3'

Form2: Compiled.exe [/ErrorStdOut] [params ...]
Execute an compiled AutoIt3 Script File produced with Aut2Exe.

Form3: Compiled.exe [/ErrorStdOut] [/AutoIt3ExecuteScript file] [params ...]
Execute another script file from a compiled AutoIt3 Script File. Then you don't need to fileinstall another copy of AutoIT3.exe in your compiled file.


Form4: AutoIt3.exe [/ErrorStdOut] /AutoIt3ExecuteLine "command line"
Execute one line of code.

To execute a single line of code, use the command:
Run(@AutoItExe & ' /AutoIt3ExecuteLine "MsgBox(0, ''Hello World!'', ''Hi!'')"')

The tray icon will not be displayed when using /AutoIt3ExecuteLine

NOTE: Correct usage of single- and double- quotation marks is important, even double single.

Script Editors

AutoIt scripts are simple text files that you can edit with any text editor. However there are many free or shareware editors that are much better for writing scripts and many feature syntax highlighting so that AutoIt keywords and functions stand out making scripting much easier and less prone to mistakes.

The current editor used by the majority of AutoIt users is SciTe, the AutoIt development team has created a custom version of SciTe with full syntax highlighting that also integrates various third-party AutoIt tools (like syntax checking and script tidying). A "lite" version of the SciTE editor comes with the AutoIt installation package. The full AutoIt version of SciTe that comes with all to tools can be downloaded seperately at http://www.autoitscript.com/autoit3/scite/

Some other recommended editors are:

AutoIt comes supplied with some pre-written syntax files for many editors and they can be found in the Extra installation directory (there is a link under Start Menu / AutoIt v3 / Extra).

Compiling Scripts with Aut2Exe

It is possible to take your .au3 script and compile it into a standalone executable; this executable can be used without the need for AutoIt to be installed and without the need to have AutoIt3.exe on the machine. In addition, the compiled script is compressed and encrypted and there is the option to bind additional files (also compressed/encrypted) to the exe using the FileInstall function. Also, any #include files will also be compiled into the script so they are not required at run-time.

Caution: the script to be compiled must be free of syntax error as the compilation will not check the syntax.

Aut2Exe can be used in three ways:

Method 1 - Start Menu

Only available if full install performed.

1. Open the Start Menu and browse to the AutoIt v3 group.

2. Click Script Compiler \ Convert .au3 to .exe

3. The main Aut2Exe interface should appear.

4. Use the Browse buttons to select your input (.au3) and output (.exe) files.

5. If you like you can change the icon of the resulting .exe - just browse to the icon you want (some example icons are supplied in Program Files\AutoIt3\Aut2Exe\Icons).

6. If you don't want anyone to be able to decompile your script (when a decompiler is made available) then you should enter a passphrase.

7. The only other option you might wish to change is the compression level (especially if using FileInstall to add extra files). Use the Compression menu to set this. As with all compression routines the better the compression you select the slower it will be. However, no matter what compression level you select the decompression speed (when the .exe is run) is the same.

8. Click on Convert to compile the script.

Note: scripts can be compile with .a3x extension. They should be run with AutoIt.exe filename.a3x. The .a3x contains the script itself with all referred #include plus the FileInstall files. This format allow to distribute smaller files as they don't include the AutoIt3.exe in each compile script. You still need to have it accessible on the target machine but just AutoIt3.exe.

Method 2 - Right Click

Only available if full install performed.

1. In Explorer browse to the .au3 file that you wish to compile.

2. Right-click the file to access the pop-up menu.

3. The file will be silently compiled with the same filename - just with a .exe extension.

When compiling in this way, Aut2Exe uses current icon/compression settings (from the last time Aut2Exe was run manually as in method 1).

Method 3 - The Command Line

The Aut2Exe.exe program can be run from the command line as follows:

Aut2exe.exe /in [/out ] [/icon ] [/nodecompile] [/comp 0-4] [/pass ] [/nopack] [/ansi] [/unicode]

Long filenames should be enclosed in double-quotes like "C:\Program Files\Test\test.au3". If no "out" file is given the input filename is used with a .exe extension.

Technical Details

The compiled script and additional files added with FileInstall are compressed with my own (Jon) compression scheme.

Because a compiled script must "run" itself without a password it needs to be able to decrypt itself - i.e., the encryption is two-way. For this reason you should regard the compiled exe as being encoded rather than completely safe. For example, if I wrote a script that contained a username and password (say, for a desktop rollout) then I would be happy using something like a workstation-level user/password but I would not consider it safe for a domain/entire network password unless I was sure that the end-user would not have easy access to the .exe file.

AutoIt Window Information Tool

AutoIt v3 comes with a standalone tool called the AutoIt Window Info Tool (Program Files\AutoIt3\AU3Info.exe). AU3Info allows you to get information from a specified window that can be used to effectively automate it. Information that can be obtained includes:

  • Window titles
  • Text on the window (visible and hidden)
  • Window size and position
  • Contents of the status bar
  • Position of the mouse pointer
  • Colour of the pixels underneath the mouse pointer
  • Details of the Control underneath the mouse pointer

To use AU3Info just run it (from the command line or Start menu). AU3Info will remain the top most window at all times so that you can read it. Once active move to the window you are interested in and activate it - the contents of AU3Info will change to show the information that is available. With the help of AU3Info you should be automating in no time!

When AU3Info is running you may want to copy text directly from it using CTRL-C and then paste it into your script to avoid spelling/case errors. For the tabs that have information in a list view (like the control information shown below) just double-click on an entry to copy it to the clipboard. This can be difficult when you want to capture pixel/mouse information as it keeps changing! To help with this you can "freeze" the output of AU3Info by pressing CTRL-ALT-F. Press the keys again to "unfreeze".

Here is an example of AU3Info in use with the Windows "WordPad" editor:

Window Titles and Text (Basic)

When automating, most windows can be uniquely identified by their title or a combination of their title & text. And by using AutoIt Window Info Tool (or even by sight) this information is easy to obtain. The titles of most windows are fairly obvious, for example Untitled - Notepad is the title of the notepad.exe editor and in many cases this is enough to automate.

Note: If a blank string "" is given for both title and text then the currently Active window will be used (this is not true in some of the more advanced WinTitleMatchModes)!

Window titles and text are case sensitive. You must match the case and punctuation exactly. To avoid problems select the title/text in the Window Info Tool and use ctrl-c to copy it and then paste it directly into your script.
You can force match in lower case using advanced modes.

Most of AutoIt's window functions have space for a title and text entry, here is the WinWaitActive function. This function pauses execution of the script until the specified window appears and is active.

WinWaitActive ( "title", ["text"], [timeout] )

title is the only required parameter for this function, both the text and timeout are optional. In some functions the text parameter is not optional, if you do not wish to specify any text then just use "" (a blank string). A blank string, or nothing at all, in the text tells AutoIt that any text is valid.

To use the above function with any notepad window both these methods will work:

WinWaitActive("Untitled - Notepad")

and

WinWaitActive("Untitled - Notepad", "")

If the same notepad window had "This is a line of text" typed into the window, the Window Info Tool would show:

Note that the Window Info Tool has seen the title and text of the notepad window. Whatever the Window Info Tool can see is what AutoIt can see. Now we have enough information to identify this exact window even if there are lots of other notepad windows open. In this case we use:

WinWaitActive("Untitled - Notepad", "This is some text!")

Window Text

The window text consists of all the text that AutoIt can "see". This will usually be things like the contents of edit controls (as above with "This is a line of text") but will also include other text like:

  • Button text like &Yes, &No, &Next (the & indicates an underlined letter)
  • Dialog text like "Are you sure you wish to continue?"
  • Control text
  • Misc text - sometimes you don't know what it is :)

The important thing is that you can use the text along with the title to uniquely identify a window to work with.

When you specify the text parameter in a window function it is treated as a substring. So for the example above if you used the text "is some " you would get a match.

What has been described is the default mode that AutoIt operates in, there are a number of more advanced modes to use when things are not as simple as this.

Window Titles and Text (Advanced)

AutoIt operates in one of three "Window matching" modes. The modes are set with the AutoItSetOption function using the WinTitleMatchMode option.

Mode 1 (default)

Matches partial titles from the start.

In this mode the a window titled Untitled - Notepad would be matched by "Untitled - Notepad", "Untitled", "Un", etc.

e.g.

WinWait("Untitled")

Mode 2

Matches any substring in the title.

In this mode a window titled Untitled - Notepad would be matched by "Untitled - Notepad", "Untitled", "Notepad", "pad", etc.

e.g.

WinWait("Notepad")

Mode 3

Exact title match.

In this mode a window titled Untitled - Notepad would only be matched by "Untitled - Notepad"

Mode 4

Advanced mode.

See Advanced Window Descriptions.

Mode -1 to -4

Force lower case match according to other type of match.

Advanced Window Descriptions

A special description can be used as the window title parameter. This description can be used to identify a window by the following properties:

  • TITLE - Window title
  • CLASS - The internal window classname
  • REGEXPTITLE - Window title using a regular expression (if the regular expression is wrong @error will be set to 2)
  • LAST - Last window used in a previous AutoIt command
  • ACTIVE - Currently active window
  • INSTANCE - The 1-based instance when all given properties match

One or more properties are used in the title parameter of a window command in the format:

[PROPERTY1:Value1; PROPERTY2:Value2]

e.g. Wait a window of classname "Notepad"

WinWaitActive("[CLASS:Notepad]", "")

e.g. Close the currently active window

WinClose("[ACTIVE]", "")

e.g. Wait for the 2nd instance of a window with title "My Window" and classname "My Class"

WinWaitActive("[TITLE:My Window; CLASS:My Class; INSTANCE:2]", "")

Window Handles / HWNDs

The variant datatype in AutoIt natively supports window handles (HWNDs). A window handle is a special value that windows assigns to a window each time it is created. When you have a handle you may use it in place of the title parameter in any of the function calls that use the title/text convention. The advantage of using window handles is that if you have multiple copies of an application open - which have the same title/text - you can uniquely identify them when using handles. When you use a window handle for the title parameter then the text parameter is completely ignored.

Various functions such as WinGetHandle, WinList and GUICreate return these handles. It is important to note that a window handle is not classed as a number or string - it is its own special type.

Note: Window handles will work no matter what WinTitleMatchMode is currently in use.

Controls

One of the best new features with AutoIt v3 is the ability to work directly with certain types of Window Controls. Almost everything you see on a window is a control of some kind: buttons, listboxes, edit fields, static text are all controls. In fact Notepad is just one big "Edit" control! Because AutoIt works directly with a control they provide a more reliable way to automate than just sending keystrokes.

Note: AutoIt only works with standard Microsoft controls - some applications write their own custom controls which may look like a standard MS control but may resist automation. Experiment!

Using the AutoIt Window Info Tool you can move your mouse around the window you are interested in and you will be given information of the control that is currently under your mouse.

A special description can be used as the controlID parameter used in most of the Control...() functions . This description can be used to identify a control by the following properties:

  • ID - The internal control ID. The Control ID is the internal numeric identifier that windows gives to each control. It is generally the best method of identifying controls. In addition to the AutoIt Window Info Tool, other applications such as screenreaders for the blind and Microsoft tools/APIs may allow you to get this Control ID
  • TEXT - The text on a control, for example "&Next" on a button
  • CLASS - The internal control classname such as "Edit" or "Button"
  • INSTANCE - The 1-based instance when all given properties match
  • CLASSNN - The ClassnameNN value as used in previous versions of AutoIt, such as "Edit1"

One or more properties are used in the controlID parameter of a control command in the format:

[PROPERTY1:Value1; PROPERTY2:Value2]

Note: If this special format is not used then the parameter is taken to be a control ID (if numeric) or the ClassnameNN/text of the control (if a string). Although the special format is more longwinded than these methods it is much less ambiguous.

e.g. Send text to the 1st Edit control in the Notepad window

ControlSend("Untitled - Notepad", "", "[CLASS:Edit; INSTANCE:1]", "This is some text")

or

ControlSend("Untitled - Notepad", "", "[CLASSNN:Edit1]", "This is some text")

or

ControlSend("Untitled - Notepad", "", "Edit1", "This is some text")

e.g. Click on control ID 254 in "My Window"

ControlClick("My Window", "", "[ID:254]")

or

ControlClick("My Window", "", 254)

e.g. Click the 2nd instance of a "Button" control containing the text "Finish"

ControlClick("My Window", "", "[CLASS:Button; TEXT:Finish; INSTANCE:2]")

Control Handle (HWND)

Using the ControlGetHandle function you can determine the Handle or HWND of a control. A handle is the unique identifier that Windows gives controls. The handle changes each time the control is created. This method of accessing controls is generally only designed for users who are familar with working with handles.

Look under the contents for Function Reference \ Window Management \ Controls for a list of the functions that work with controls.

Unicode Support

From version 3.2.4.0 AutoIt is supplied with both Unicode and ANSI compiled versions. The Unicode versions are the default for Windows NT, Windows 2000, Windows XP and later. ANSI versions are supplied for backwards compatibility with Windows 9x systems. AutoIt executables with an A on the end are the ANSI versions. For example:

  • AutoIt.exe - Unicode version
  • AutoIt3A.exe - ANSI version

The Unicode versions will allow our international friends to finally use AutoIt with extended characters and scripts!

Note: the Unicode version of AutoIt (AutoIt3.exe) and scripts compiled in Unicode mode will only run on Windows NT/2000/XP/2003/Vista and later machines. To allow scripts to run on Windows 9x scripts must be compiled using the ANSI compiler (Aut2ExeA.exe).

AutoIt will read script files in ANSI, UTF16 (big or little endian) and UTF8 formats. In addition, functions such as FileReadLine will automatically read text from ANSI and UTF16/UTF8 text files providing a valid BOM is found. UTF files without a valid BOM will be treated as ANSI.

Output functions such as FileWriteLine can use ANSI, UTF16 (big or little endian) and UTF8 formats - but the file must be opened in the desired mode using the desired FileOpen flags otherwise the default ANSI mode is used.

The supported file formats for text files and scripts as saved in Notepad and the AutoIt SciTe editor are shown in this table:

AutoIt Notation Notepad SciTe
ANSI ANSI 8 bit / Code Page Property
UTF16 Little Endian Unicode UCS-2 Little Endian
UTF16 Big Endian Unicode big endian UCS-2 Big Endian
UTF8 UTF-8 UTF-8 with BOM

The recommended Unicode format is UTF16 Little Endian - this is how strings are stored within AutoIt and therefore require less processing/conversion when reading/writing. However, the UTF8 format will use less space in script files and is also a good choice.

Current Limitations

There are a few parts of AutoIt that don't yet have full Unicode support. These are:

These limits will be addressed in future versions if possible.

Intended Use

AutoIt is a 'growing' scripting language. It started as an add-on tool to automate basic tasks in GUI's of other programs.
These tasks (like sending a keystroke or clicking a button) are still the core components of an AutoIt script. However with the recent GUI additions, you can now incorporate your own graphical interface using native AutoIt script commands.
The new COM (Object) functionality fills the gap with WSH languages, such as VBScript/JScript. Under certain conditions you can now even use WSH-like scripts on otherwise unsupported operating systems (like Windows 9x/Me/NT).

With this combination of GUI Automation, GUI Interfaces and COM support, AutoIt offers you a powerful scripting tool that is able to compete with fully-fledged scripting languages like WSH or KiXStart).

Notes for users familiar with AutoIt 2.64

Apart from the concept of windows and keystrokes, AutoIt v3 is quite different to v2.64 and previous versions of AutoIt. v2.64 will continue to be available for download and there are few reasons why users should try and convert existing scripts (if it ain't broke, etc.). However v3 has lots of great new features to make GUI automation easier than ever before, as well as being a much better general purpose scripting language.

When start to use v3 the following should help to make things a little easier. There is also a v2.64 to v3 script converter available in the "Extra" directory which is located in the installation directory.


- Backslashes are no longer a special character. However, quotation marks are a new issue....
For example, Run('C:\Windows\Notepad.exe "C:\Some File.txt" ')

- Command-Line Syntax:
There is only script mode, i.e., AutoIt.exe

- Conventions:
, [,] has been replaced with Cmd(parm1 [,parm2])


- Goto does not exist due to the support of loops and user-defined functions.

- AutoItv3 supports variables like most programming languages: $myVar = "Example of assignment"

- Scripts have the extension .au3 instead of .aut


If you wish to re-write version 2.64 scripts as version 3, the following table may help you:

Version 2.64 function Version 3 equivalent
AdlibOn AdlibEnable
BlockInput BlockInput
Break Break
DetectHiddenText AutoItSetOption("WinDetectHiddenText",...)
Exit Exit
EnvAdd [see + operator]
EnvDiv [see / operator]
EnvMult [see * operator]
EnvSub [see - operator]
FileAppend [FileOpen(...,2) followed by FileWriteLine]
FileCopy FileCopy
FileCreateDir DirCreate
FileDelete FileDelete or FileRecycle
FileInstall FileInstall
FileReadLine FileReadLine
FileRemoveDir DirRemove
FileSelectFile FileOpenDialog or FileSaveDialog
Gosub [see Func...EndFunc]
Return [see Func...EndFunc]
Goto [not needed]
HideAutoItDebug --
HideAutoItWin AutoItSetOption("TrayIconHide",...)
IfInString If StringInStr(...) Then
IfNotInString If Not StringInStr(...) Then
IfWinExist If WinExists(...) Then
IfWinNotExist If Not WinExists(...) Then
IfWinActive If WinActive(...) Then
IfWinNotActive If Not WinActive(...) Then
IfEqual [see = and == operators]
IfNotEqual [see <> operator]
IfGreater [see > operator]
IfGreaterOrEqual [see >= operator]
IfLess [see <>
IfLessOrEqual [see <= operator]
IfExist FileExists
IfNotExist If Not FileExists(...) Then
IfMsgBox [see MsgBox(...) and Select...Case...EndSelect]
IniRead IniRead
IniWrite IniWrite
IniDelete IniDelete
InputBox InputBox
LeftClick MouseClick("left",...)
RightClick MouseClick("right",...)
LeftClickDrag MouseClickDrag("left",...)
RightClickDrag MouseClickDrag("right",...)
MouseGetPos MouseGetPos
MouseMove MouseMove
MsgBox MsgBox
Random Random
RegRead RegRead
RegWrite RegWrite
RegDelete RegDelete
Repeat [see For...Next]
EndRepeat [see For...Next]
Run Run
RunWait RunWait
Send Send
SetCapslockState AutoItSetOption("SendCapslockMode",0) + Send ("{CAPSLOCK}")
SetEnv EnvSet
SetBatchLines --
SetKeyDelay AutoItSetOption("SendKeyDelay",...)
SetStoreCapslockMode AutoItSetOption("SendCapslockMode",...)
SetTitleMatchMode AutoItSetOption("WinTitleMatchMode",...)
SetWinDelay AutoItSetOption("WinWaitDelay",...)
Shutdown Shutdown
Sleep Sleep
SplashTextOn SplashTextOn and others
SplashTextOff SplashOff
StringCaseSense [see individual functions]
StringLeft StringLeft
StringRight StringRight
StringMid StringMid
StringLen StringLen
StringReplace StringReplace
StringTrimLeft StringTrimLeft
StringTrimRight StringTrimRight
StringGetPos StringInStr
WinGetActiveStats [see WinGetPos, WinGetTitle, WinGetText]
WinGetActiveTitle WinGetTitle("")
WinKill WinKill
WinWait WinWait
WinWaitClose WinWaitClose
WinWaitActive WinWaitActive
WinWaitNotActive WinWaitNotActive
WinHide WinSetState(..., @SW_HIDE)
WinShow WinSetState(..., @SW_SHOW)
WinRestore WinSetState(...,@SW_RESTORE)
WinMinimize WinSetState(...,@SW_MINIMIZE)
WinMaximize WinSetState(...,@SW_MAXIMIZE)
WinActivate WinActivate
WinClose WinClose
WinMove WinMove
WinSetTitle WinSetTitle
WinMinimizeAll WinMinimizeAll
WinMinimizeAllUndo WinMinimizeAllUndo
#Include #Include
%CLIPBOARD% [see ClipGet and ClipPut]
A_OSTYPE @OSType
A_OSVERSION @OSVersion
A_SCRIPTNAME @ScriptName
A_SCRIPTDIR @ScriptDir
A_SCRIPTFULLPATH @ScriptFullPath
A_WORKINGDIR @WorkingDir
A_NUMBATCHLINES --
A_SEC @SEC
A_MIN @MIN
A_HOUR @HOUR
A_MDAY @MDAY
A_MON @MON
A_YEAR @YEAR
A_WDAY @WDAY
A_YDAY @YDAY

No comments: