You are on page 1of 21

Comi's Autoit guide.

First of all Im writing this guide to help people understand the basics of autoit, and end up having a general idea of how to script with au3. Im making this guide with info from me, the autoit help file, the autoit forums, & others. Be ready to read a lot , and read the same stuff several times if you dont understand. Be ready to do LOTS of tests since its the BEST way to learn this lang IMO. Best way to used this guide is to go testing each example as they go appearing. This guide is not ment to be-all and end-all autoit3 guides out there. All autoit3 info is NOT and wont be in this guide as this is a begginer's guide. Already know programming ? Already knew autoit2 or 3 ? Go read the help file. Dont like autoit? Get out of here and dont leave witty comments. Dont like my guide ? Go write your own.

________________________________________
Introduction
Quote: AutoIt v3 is a 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.

Which in simple's man talk means, that with autoit you can basically do everything that you can do with mouse & keyboard , and much more... AutoIt has been designed to work on Windows 95, 98, ME, NT 4, 2000, XP and 2003.

________________________________________
Getting autoit v3
In order to use this guide properly you will need autoit. Find it here http://www.autoitscript.com/autoit3/ Make sure to install it, if you have trouble installing it, coding simply is not for you.

________________________________________

Basics
AutoIt scripts are simple text files that you can edit with notepad or any other simple test editor. Autoit will read those scripts and do what you write step by step. If you have previous programming knowledge you will find that scriptiong in autoit is extremely easy, therefore also very fun to do. Quote: 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 to just sending keystrokes.

________________________________________
Autoit Window spy
Awesome utility that gives you all the info you might need about a specific window. It will reveal info only about the window you have currently selected. It will also be "always on top", meaning that it will always be on top of other windows. Quote: AutoIt Window Spy allows you to get information from a specified window that can be used to effectively automate it.

If will give the folowing info:


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 Name of the Control underneath the mouse pointer

With the help of AU3Spy you should be automating in no time! Quote: When AU3Spy 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. 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 AU3Spy by pressing CTRL-ALT-F. Press the keys again to "unfreeze".

CTRL + ALT + F , remember that as since it is very usefull. Look here an example of the autoit window spy:

________________________________________
General au3 language reference
Basic reference for the autoit language.

________________________________________
Types of data
In autoit , to make it simple you have 2 types of data , numeric and string (text) data. String data String data is basically text info thats sotred on a variable(explained next). String data always starts and ends with "" or '', even if single or double quotes are inserted in the text it the first and final quotes are the important ones. For example variable="hello" , variable will contain hello in it. variable="comi "not really" rocks" , variable will contain comi "not really" rocks in it. If you have 2 numeric strings stored and try to do arimetic operations with the autoit will automatically convert them to numeric. Variables can contain strings of up to 2 billion characters. Numeric data Basically numbers, you will use them mostly for internal operations or as counter for multiple things ... ect... Quote: Numbers can be standard decimal numbers like 2, 4.566, and -7. Scientific notation is also supported; therefore, you could write 1.5e3 instead of 1500.

numeric & string reference Quote: A variant can contain numeric or string data and decides how to use the data depending on the situation it is being used in. For example, if you try and multiply two variants they will be

treated as numbers, if you try and concatenate (join) two variants they will be treated as strings. Some examples:

10 * 20 equals the number 200 (* is used to multiply two numbers) 10 * "20" equals the number 200 "10" * "20" equals the number 200 10 & 20 equals the string "1020" (& is used to join strings)[/[/list]

& is very important, as it can be used to join string and numberic variables with/or direct
data. Whenever using & the return value will be string.

________________________________________
Variables
Quote: A variable is just a place to store data in memory so that it can be accessed quickly. Think of it as a mailbox in memory that you can put information in or take information out of. For example you might create a variable to store the number a user's response to a question, or the result to a math equation. Each variable has a name (again, similar to a mailbox) and must start with the $ character and may only contain letters, numbers and the underscore _ character.

Here are some example names: $var1 $my_variable Note that a variable will only hold numeric OR string value, i cant contain both. Declaring Variables Variables can be declared in several ways, but ill go with the easy one , or else why would you be reading this tutorial ? For extended info refer to the autoit help. You can and will declare variables by simply assigning them a value, either string or numeric. You will use = to assign a value to a variable. You will add a value either directly on the script, via user imput, via .ini or file read or else thru a aritmetic operation. Many many functions in autoit will give RETURN VALUES , you will use variables to obtain them.

Examples, all work: $cookienum=15 $blizzhackers="ownage" $sex = "good" $mix= 16 * 3 $result = (2 * 2)+5 $hesaid=InputBox("Question", "what do you want to say?", "", )
(more on these later on)

$emoticon=" }:p " & " <--- he is a crazy guy" Macros Quote: AutoIt has an number of Macros that are special read-only variables used by AutoIt. Macros start with the @ character instead of the usual $ so are easy to tell apart. As with normal variables you can use macros in expressions but you cannot assign a value to them. The pre-defined macros are generally used to provide easy access to system information like the location of the Windows directory, or the name of the logged on user.

Check the help file for a complete list.

________________________________________
Operators
AutoIt has mathematical, logical and comparison operators. mathematical operators will do a matematic precedure, adding for example. 2-2=1 3*3=9 Logical operators will do a logic precedure on separate values. ... 1 NOT 2 ... if "A" AND "c" are uppercase .... Comparison operators will compare 2 or more values with eachother. If $var= 5 Then (true if $var equals 5)

________________________________________
Quote: When more than one operator is used in an expression the order in which things happen is controlled by operator precedence. The precedence used in AutoIt is given below. Where two operators have the same precedence the expression is evaluated left to right.

From highest precedence to lowest:


NOT ^ */ +& < > <= >= = <> == AND OR

e.g. 2 + 4 * 10 is evaluated as 42: 4 * 10 (equals 40) 2 + 40 (equals 42) As the * has a higher precedence than + it occurs before the addition. You can use brackets to force a part of the expression to be evaluated first. e.g. (2 + 4) * 10 equals 60.

________________________________________
Operators list

+ Adds two numbers. e.g. 10 + 20 (equals 30) - Subtracts two numbers. e.g. 20 - 10 (equals 10) * Multiplies two numbers. e.g. 20 * 10 (equals 200) / Divides two numbers. e.g. 20 / 10 (equals 2) & Concatenates/joins two strings. e.g. "one" & 10 (equals "one10") ^ Raises a number to the power. e.g. 2 ^ 4 (equals 16) NOT Logical NOT operation. e.g. NOT 1 (equals 0)

= Tests if two values are equal (case insensitive if used with strings). e.g. If $var= 5 Then
(true if $var equals 5)

== Tests if two values are equal (case sensitive if used with strings) <> Test if two values are not equal. > Tests if the first value is greater than the second. >= Tests if the first value is greater than or equal to the second. < Tests if the first value is less than the second. <= Tests if the first value is less than or equal to the second. AND Logical AND operation. e.g. If $var = 5 AND $var2 > 6 Then (true if $var equals
5 and $var2 is greater than 6)

OR Logical OR operation. e.g. If $var = 5 OR $var2 > 6 Then (true if $var equals 5 or
$var2 is greater than 6)

________________________________________
Conditional Statements
Quote: You will often want to change the flow of your script based on a condition or series of conditions. Is one number bigger than another? Or, does a string contain a certain value?

Conditional statements are available in AutoIt If...Then...Else Select...Case Both statements are similar and decide which code to execute depending on the condition given. Here is an example of an If statement that pops up a message box if a variable is greater than 10.

________________________________________ If...Then...Else...EndIf
Conditionally run statements. Code: Select all
If <expression> Then statements ...

[ElseIf expression-n Then [elseif statements ... ]] ... [Else [else statements] ... EndIf

If the expression is true, the first statement block is executed. If not, the first true ElseIf block is executed. Otherwise, the "Else" block is executed. Here is an example of an If statement that pops up a message box if a variable is greater than 10. Code: Select all
$var = 20 If $var > 10 Then MsgBox(0, "Example", "$var was greater than 10!") Else MsgBox(0, "Example", "$var was less than 10") EndIf

In the example above the expression $var > 10 evaluated to true because the variable was indeed greater than 10. This caused the If statement to execute the first MsgBox line and display "$var was greater than 10!".

________________________________________ Select...Case...EndSelect
Conditionally run statements. Code: Select all
Select Case <expression> statement1 ... [Case statement2 ...] [Case Else statementN ...] EndSelect

If the expression is true the following statements up to the next Case or EndSelect statement are executed. If more than one of the Case statements are true, only the first one is executed. A Select statement is very similar to the IF statement, but is generally used for situations where you want to test a large number of conditions as it is generally easier to read than than large If/ElseIf type block. e.g. Code: Select all

$var = 30 Select Case $var > 1 AND $var <= 10 MsgBox(0, "Example", "$var was greater than 1") Case $var > 10 AND $var <= 20 MsgBox(0, "Example", "$var was greater than 10") Case $var > 20 AND $var <= 30 MsgBox(0, "Example", "$var was greater than 20") Case $var > 30 AND $var <= 40 MsgBox(0, "Example", "$var was greater than 30") Case $var > 40 MsgBox(0, "Example", "$var was greater than 40") EndSelect

of course Case $var > 20 AND $var <= 30 will be the selected case and the mesage box will return "$var was greater than 20"

________________________________________
Loop Statements
Code: Select all
A loop is how you refer to a section of script that you repeat a number of times. You might might want to loop a given number of times or you might wish to repeat a section of script as long as a certain condition is true or false.

The following loop statements are available in AutoIt: For...Next While...WEnd Do...Until While (no pun intended) all the statements perform similar functions, they are slightly different and one will usually be more appropriate than another for a given situation.

________________________________________ For...Next
Loop based on an expression. I dont use this one much really... Code: Select all
For $<variable> = <start> To <stop> [Step <stepval>] statements

... Next

Parameters variable The variable used for the count. start The initial numeric value of the variable. stop The final numeric value of the variable. stepval [optional] The numeric value (possibly fractional) that the count is increased by each loop. Default is 1. Important Quote: For...Next statements may be nested. The For loop terminates when the value of variable exceeds the stop threshold. If stepVal or stop is a variable, its value is only read the first time the loop executes. A For loop will execute zero times if: start > stop and step > 0, or start < stop and step is negative

Example Code: Select all


For $i = 5 to 1 Step -1 MsgBox(0, "Count down!", $i) Next MsgBox(0,"", "Blast Off!")

This will result in 5 message boxes counting from 5 to 1 one after eachother and after the one a message box will come saying Blast Off!

________________________________________ While...WEnd
Loop based on an expression. Extremely used loop. Code: Select all
While <expression> statements ... WEnd

If the expression is true the following statements up to the WEnd statement are executed. This loop continues until the expression is false.

Important While...WEnd statements may be nested. The expression is tested before the loop is executed so the loop will be executed zero or more times. To create an infinite loop, you can use a non-zero number as the expression. Example Code: Select all
$i = 0 While $i <= 10 MsgBox(0, "Value of $i is:", $i) $i = $i + 1 WEnd

This example loop will start showing a msgbox with "0" and contine goin on adding 1 untill it reaches 10.

________________________________________ Do...Until
Loop based on an expression. Code: Select all
Do statements ... Until <expression>

The statements in between Do and Until are executed until the expression is true. Important Do...Until statements may be nested. The expression is tested after the loop is executed, so the loop will be executed one or more times. Example Code: Select all
$i = 0 Do MsgBox(0, "Value of $i is:", $i) $i = $i + 1 Until $i = 10

Same result as while, this example loop will start showing a msgbox with "0" and contine goin on adding 1 untill it reaches 10.

________________________________________
Functions

A function is a section of code that can be called from the script to perform a certain "function". There are two sorts of functions in AutoIt, inbuilt functions and user functions. You will use a function mostly for code re-use & better script organization.

Inbuilt Functions
There are really usefull, but they are not as flexible as self-made functions. For an Inbuild function list refer to the autoit help file.

User Functions
User functions are declared using the Func...EndFunc statements. Quote:

Func...Return...EndFunc
Defines a user-defined function that takes zero or more arguments and optionally returns a result. Code: Select all
Func functioname ( [ByRef] $param1, ..., [ByRef] $paramN) ... [Return [value]] EndFunc

The parameters are set by you. You later call the function like any other built-in function. The ByRef keyword is optional and means: (1) the parameter must a variable, and (2) the variable could be changed by the function. By default, a parameter is passed by value which means that a copy of the parameter's value is manipulated by the function. Use the Return keyword to exit the function. Unlike built-in functions, user-defined functions return 0 unless another return value is specified. Arrays can be passed to functions (and returned from them) by simply using the array name without any brackets. Note that function declarations cannot appear inside other function declarations.

Functions can accept parameters and return values as required. Function names must start with either a letter or an underscore, and the remainder of the name can contain any combination of letters and numbers and underscores. Some valid function names are: MyFunc Func1

_My_Func1 For better organization of the script I usually define the functions at the top of the script. Examples Here is an example of using a function to double a number 5 times: (note that only from Func to EndFunc is the real function) Code: Select all
$val = 10 For $i = 1 To 10 $doubled = MyDouble($val) MsgBox(0, "", $val & " doubled is " & $doubled) $val = $doubled Next Exit Func MyDouble($value) $value = $value * 2 Return $value EndFunc

Sample script with three user-defined functions. Notice the use of variables, ByRef, and Return. Code: Select all
$foo = 2 $bar = 5 msgBox(0,"Today is " & today(), "$foo equals " & $foo) swap($foo, $bar) msgBox(0,"After swapping $foo and $bar", "$foo now contains " & $foo) msgBox(0,"Finally", "The larger of 3 and 4 is " & max(3,4)) Exit Func swap(ByRef $a, ByRef $b) Local $t $t = $a $a = $b $b = $t EndFunc ;swap the contents of two variables

Func today() ;Return the current date in mm/dd/yyyy form return (@MON & "/" & @MDAY & "/" & @YEAR) EndFunc Func max($x, $y) ;Return the larger of two numbers If $x > $y Then return $x Else return $y EndIf EndFunc

One of my Functions, extremely usefull for logging stuff.

Code: Select all


Func datetime() $min=string(@MIN) $hour=@HOUR $day=string(@MDAY) $mon=string(@MON) $year=string(@YEAR) If $hour=00 then $hour="24" Else $hour=string(@HOUR) Endif $time = $hour & ":" & $min $date= $day & "/" & $mon & "/" & $year $dt=$time & " -- " & $date Return ($dt) EndFunc

add this to a script to test it Code: Select all


$likeomg=datetime() Msgbox(0, "The current date and time", $likeomg)

________________________________________
Extra usefull info
Although only one statement per line is allowed, a long statement can span multiple lines if an underscore, _, is placed at the end of a "broken" line. Like for example Code: Select all
MsgBox(64,"", "This is a rather long line, so I broke it with the underscore, _, character.")

Would be the same as Code: Select all


MsgBox(64,"", "This is a rather _ long line, so _ I broke it with the _ underscore, _, char_ acter.")

Might not look usefull but in this case for example (real example) Code: Select all
IF $indexmin= "error" OR $indexmax= "error" OR $forummin= "error" OR $forummax= "error" OR $topicmin= "error" OR $topicmax= "error" OR $artmin= "error" OR $artmax= "error" OR $profmin= "error" OR $profmax= "error" OR $tabmin= "error" OR $tabmax= "error" OR $IEname= "error" OR $root= "error" OR $server1= "error" OR $server2= "error" OR $server3= "error" OR $server4= "error" OR $server5= "error" OR $server6= "error" OR $server7= "error" OR

$server8= "error" OR $server9= "error" OR $server10= "error" OR $topicini= "error" OR $topicend= "error" OR $artini= "error" OR $artend= "error" OR $profini= "error" OR $profend= "error" OR $tabnummax= "error" OR $subtabstimes= "error" Then MsgBox(48, "Gaiabot by Comi", "Error reading the ini file") Exit Endif

Thats a bit of a mess ... but if scripted like this: Code: Select all
IF _ $indexmin= "error" OR _ $indexmax= "error" OR _ $forummin= "error" OR _ $forummax= "error" OR _ $topicmin= "error" OR _ $topicmax= "error" OR _ $artmin= "error" OR _ $artmax= "error" OR _ $profmin= "error" OR _ $profmax= "error" OR _ $tabmin= "error" OR _ $tabmax= "error" OR _ $IEname= "error" OR _ $root= "error" OR _ $server1= "error" OR _ $server2= "error" OR _ $server3= "error" OR _ $server4= "error" OR _ $server5= "error" OR _ $server6= "error" OR _ $server7= "error" OR _ $server8= "error" OR _ $server9= "error" OR _ $server10= "error" OR _ $topicini= "error" OR _ $topicend= "error" OR _ $artini= "error" OR _ $artend= "error" OR _ $profini= "error" OR _ $profend= "error" OR _ $tabnummax= "error" OR _ $subtabstimes= "error" _ Then MsgBox(48, "Gaiabot by Comi", "Error reading the ini file") Exit Endif

Its MUCH easyer to read , remeber if you script is easy to understand it will be easyer to update/fix/patch it.

________________________________________
The semicolon (;) is the comment character. Unless the semicolon is within a string, all text following it is ignored by the script interpreter/complier.

Examples Code: Select all


; The next line contains a meaningful, end-of-line comment Sleep(5000) ;pause 5 seconds

Fox example, on the next script lines the green text will be completely ignored when interpreted or compiled. From a real used script... Note that semicolons are in red just to be remarked. Quote: ;********checks if d2 is running, also check if using d2 or d2loader.********* $d2loader=0 If WinExists("Diablo") Then ;norm diablo $d2loader=1 Else If NOT WinExists("D2Loader") Then ;d2loader MsgBox(48, "MHstarter by Comi", "Could not find Diablo II") Exit Endif Endif

________________________________________
For long extense comments you can use #comments-start . Similar to the comments in C. Specify that an entire section of script should be commented out. Code: Select all
#comments-start ... ... #comments-end

... ... Will be completly ignored by the interperter. The #comments-start and #comments-end directives can be nested. You can also use the abbreviated keywords #cs and #ce. Additionally, the directives themselves can be commented out! Example Code: Select all
#comments-start MsgBox(4096, "", "This won't be executed") MsgBox(4096, "", "Or this") #comments-end

Comments in general can be very usefull for debugging(searching for errors and polishing the script) since you may ignore a line or sector instead of deleting it. Alos usefull when you are unsure where the error is.

________________________________________
NOTE: You cannot put comments on lines ending with underscores! For example, this wont work and it will give you a big nice error. Code: Select all
IF _ $indexmin= $indexmax= $forummin= $forummax= $topicmin= "error" "error" "error" "error" "error" OR OR OR OR OR _ _ _ ;like omg can i say this here? _ _ Then

$error="no errors?" Endif

Function Reference
In autoit, there are loads of functions, most of them do unique things but sometimes something done by 1 can be done with a combo of several. I will only list the most used and not-hard-to-use functions ONLY. For a FULL funct. list make sure to read the autoit3 help file.

________________________________________
Send
Quote: Sends simulated keystrokes to the active window.

The send command, you will use this one to simulate general keyboard use. This function is really versatile, and you will be able to pretty much simulate ANYTHING (keyboard related) with it. Code: Select all
Send ( "keys" [, flag] )

Quote: keys =The sequence of keys to send. flag [optional] Changes how "keys" is processed:

flag = 0 (default), Text contains special characters like + and ! to indicate SHIFT and ALT key presses. flag = 1, keys are sent raw.

'!' This tells AutoIt to send an ALT keystroke, therefore Send("This is text!a") would send the keys "This is text" and then press "ALT+a". N.B. Some programs are very choosy about capital letters and ALT keys, i.e. "!A" is different to "!a". The first says ALT+SHIFT+A, the second is ALT+a. If in doubt, use lowercase! '+' This tells AutoIt to send a SHIFT keystroke, therefore Send("Hell+o") would send the text "HellO". Send("!+a") would send "ALT+SHIFT+a". '^' This tells AutoIt to send a CONTROL keystroke, therefore Send("^!a") would send "CTRL+ALT+a". N.B. Some programs are very choosy about capital letters and CTRL keys, i.e. "^A" is different to "^a". The first says CTRL+SHIFT+A, the second is CTRL+a. If in doubt, use lowercase! '#' The hash now sends a Windows keystroke; therefore, Send("#r") would send Win+r which launches the Run dialog box. You can, if wanted send a specific keypress simlulation. like most used: {SPACE} {ENTER} {ALT} {BACKSPACE} or {BS} {DELETE} or {DEL} {ESCAPE} or {ESC} There are many more, all usefull. Read the help file. ______________________________________ Send Examples Code: Select all
Send("Comi rocks")

Will send the Comi rocks keypresses, if in active text bar , will write it. Code: Select all
$myvar="coke is 1337" Send($myvar)

Will send coke is 1337 Code: Select all


Send("ok lets press enter{ENTER}")

Will send ok lets press enter and will prss enter. Code: Select all
Send("ok lets press enter{ENTER}", 1)

Will send ok lets press enter{ENTER} There are many ways to use this function, those are the basics. Read the help file.

________________________________________
Send
Quote: Perform a mouse click operation. So basically, this will emulate the mouseclicks you do with your mouse. Not a so-simple command, but surely one of the most important ones. Code: Select all
MouseClick ( "button" [, x, y [, clicks [, speed ]]] )

______________________________________ button Quote: The button to click, "left", "right" or "middle". No big deal on this one, simply put whatever buttong you want to press. If a user has switched his primary (left) and secondary (right) mouse buttons, a script may not work as you expect(will press inverese keys of what youve scripted). Solution below. ****************************************** Coordinates Quote: x, y [optional] The x/y coordinates to move the mouse to. If no x and y coords are given, the current position is used. Basically where you will click. Remeber that to get coordinates you will use Autoit3 window spy. IMPORTANT!

MouseCoordMode(option) by default will use absolute screen coordinates. You will most likely need to set this au3 option to 0,relative coords to the active window. Code: Select all
MouseCoordMode(0)

****************************************** clicks Quote: clicks [optional] The number of times to click the mouse. Default is 1. How many click ull do , usually 1 will do. Its usually better to write the command line twice than use the clicks option. MouseClickDelay(option) Alters the length of the brief pause in between mouse clicks. Time in milliseconds to pause (default=10). ****************************************** speed Quote: speed [optional] the speed to move the mouse in the range 1 (fastest) to 100 (slowest). A speed of 0 will move the mouse instantly. Default speed is 10. Lets say mouse is in position A, and you want to click on B. If you dont set the speed , it will take time for the cursor to move from a to b, once in B it will click. Using default value in this will make your mouseuse script go extremely slow, and can create delay and loop bugs. I EXTREMELY RECOMMEND THE USE OF SPEED AT 0 (instant click). ______________________________________ MouseClick Examples Code: Select all
MouseClick("left")

Will do a left click wherever the cursor is. Code: Select all
MouseClick("left", 34, 500, 2)

Double click at coords 34-500 Code: Select all


Dim $primary Dim $secondary ;Determine if user has swapped right and left mouse buttons $k = RegRead("HKEY_CURRENT_USER\Control Panel\Mouse", "SwapMouseButtons") ; It's okay to NOT check the success of the RegRead operation If $k = 1 Then $primary = "right" $secondary = "left"

Else ;normal (also case if could not read registry key) $primary = "left" $secondary = "right" EndIf MouseClick($primary, 0, 500, 2) Exit

^ Fix for the swiched mousekeys.

________________________________________

You might also like