Sie sind auf Seite 1von 406

v3.3.6.

1 1999-2010 Jonathan Bennett & AutoIt Team AutoIt v3 Homepage

AutoIt Documentation

Introduction License Installation Directory Frequently Asked Questions (FAQ) Credits History / ChangeLog History of AutoIt and Developers

Using AutoIt

Running Sc ripts AutoIt on Windows Vista Command Line Parameters Script Editors Compiling Sc ripts AutoIt Window Info Tool (AU3Info) Window Titles and Text (Basic) Window Titles and Text (Advanced) Controls Unicode Support Intended Use Notes for AutoIt v2 Users Running under Windows 64-bit Edition

Tutorials

My First Script (Hello World) Simple Notepad Automation WinZip Installation String Regular expression

Language Reference

Datatypes Variables Macros Operators Conditional Statements Loop Statements Functions Comments

GUI Reference

GUI Concepts GUI MessageLoop Mode GUI OnEvent Mode

Keyword Reference

Keyword Reference

Macro Reference

Macro Reference

Function Reference

Function Reference

Appendix

AutoIt3 limits/defaults ASCII Characters CLSIDs of Special Folders GUI Control Styles Splash... Fonts @OSLang Values Send Key List Windows Message Codes

v3.3.6.1 1999-2010 Jonathan Bennett & AutoIt Team AutoIt v3 Homepage

Introduction
AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting. 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 is also very small, self-contained and will run on all versions of Windows out-of-the-box with no annoying "runtimes" required! AutoIt was initially designed for PC "roll out" situations to reliably automate and configure thousands of PCs. Over time it has become a powerful language that supports complex expressions, user functions, loops and everything else that veteran scripters would expect. Features:

Easy to learn BASIC-like syntax Simulate keystrokes and mouse movements Manipulate windows and processes Interact with all standard windows controls Scripts can be compiled into standalone executables Create Graphical User Interfaces (GUIs) COM support Regular expressions Directly call external DLL and Windows API functions Scriptable RunAs functions Detailed helpfile and large c ommunity-based support forums Compatible with Windows 95 / 98 / ME / NT4 / 2000 / XP / 2003 / Vista / 2008 Unicode and x64 support Digitally signed for peace of mind Works with Windows Vista's User Account Control (UAC)

AutoIt has been designed to be as small as possible and stand-alone with no external .dll files or registry entries required making it safe to use on Servers. Scripts can be compiled into stand-alone executables with Aut2Exe. Also supplied is a combined COM and DLL version of AutoIt called AutoItX that allows you to add the unique features of AutoIt to your own favourite sc ripting or programming languages! 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.

Features in Detail
Basic-like Syntax and Rich Function Set AutoIt has a BASIC-like syntax which means that most people who have ever written a script or used a high-level language should be able to pick it up easily. Although it started life as a simple automation tool, AutoIt now has functions and features that allow it to be used as a general purpose scripting language (with awesome automation as well of course!). Language features include:

The usual high-level elements for functions, loops and expression parsing A staggering amount of string handling functions and a Perl compatible regular expression engine (using the PCRE library). COM support Call Win32 and third-party DLL APIs

Built-in Editor with Syntax Highlighting AutoIt comes with a customised "lite" version of SciTe that makes editing scripts easy. Users can also download a complete version of SciTe that includes additional tools to make things even easier. Standalone and Small AutoIt is a very small and standalone application with no reliance on massive runtimes like .NET or VB. All you need to run AutoIt scripts are the main AutoIt executable (AutoIt3.exe) and the script. Scripts can also be encoded into standalone executables with the built-in script compiler Aut2Exe. International and 64-bit Support AutoIt is fully Unicode aware and also includes x64 versions of all the main components! How many other free scripting languages can you say that about? Key and Mouse Simulation Much time has been spent optimizing the keystroke and mouse simulation functions to be as accurate as possible on all versions of Windows. All the mouse and keyboard routines are highly configurable both in terms of simulation "speed" and functionality. Window Management You can expect to move, hide, show, resize, activate, close and pretty much do what you want with windows. Windows can be referenced by title, text on the window, size, position, class and even internal Win32 API handles.

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! Graphical User Interfaces (GUIs) AutoIt v3 will also allow you to create some complex GUIs - just like those below!

And much, much more...

Software License
AutoIt 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 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 does not 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 use the SOFTWARE PRODUCT for commercial purposes. You may sell for profit and freely distribute scripts and/or compiled scripts that were created with the SOFTWARE PRODUCT. Reverse engineering. You may not reverse engineer or disassemble the SOFTWARE PRODUCT 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 1. 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. 2. 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. [END OF LICENSE]

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 (Top-level files) AutoIt3.exe AutoIt3_x64.exe AU3Info.exe AU3Info_x64.exe AU3Check.exe AutoIt.chm Uninstall.exe AutoIt v3 Website.url Aut2Exe Icons\ Aut2Exe.exe Aut2Exe_x64.exe AutoItSC.bin AutoItSC_x64.bin UPX.exe Examples GUI\ Helpfile\ Extras AutoUpdateIt\ Editors\ Exe2Aut\ 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.
(e x ce ption: Unde r W indows NT 4 the file PSAPI.dll ne e ds to be in the path or AutoIt dire ctory for the Proce ss...() re late d functions to work )

Description The AutoIt main program and only file required to run scripts! The x64 version of AutoIt (if installed). The AutoIt Window Info Tool. The x64 version of Au3Info (if installed). The AutoIt syntax checker. This help file which use AutoIt3.chm and UDFs3.chm The AutoIt uninstaller. A shortcut to http://www.autoitscript.com/autoit3/ Contains icons used for the .au3 filetype icon in Explorer. The script compiler. The x64 version of Aut2Exe (if installed). Executable stub for compiled scripts. x64 executable stub for compiled scripts. The UPX compressor (shinks the size of exe files). Contains examples of GUIs written in AutoIt. Contains scripts used in many of the help file examples. Contains a script for easily retrieving the latest version of AutoIt3. Contains syntax coloring definitions for some popular text editors. Contains utils for converting compiled scripts back in to source code. Contains SQLite command line executable and an help file.

SQLite\

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

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) InstallDir Version REG_SZ REG_SZ REG_SZ (value not set) C:\Program Files\AutoIt3 Version Number

HKEY_CURRENT_USER\Software\AutoIt v3\ Aut2Exe (Default) AllowDec ompile LastCompression LastExeDir LastIcon LastIconDir LastScriptDir AutoUpdateIt (Default) DoneOption DownloadDir Exe2Aut (Default) LastExeDir LastScriptDir AU3Info Default AlwaysOnTop ColorMode CoordMode HighlightColor HighlightControls Magnify WinH WinW WinX WinY REG_SZ REG_DWORD REG_DWORD REG_DWORD REG_DWORD REG_DWORD REG_DWORD REG_DWORD REG_DWORD REG_DWORD REG_DWORD (value not set) 0x1 0x1 0x1 0x0 0x1 0x0 0x01c 2 0x012c 0x0064 0x0064 REG_SZ REG_SZ REG_SZ (value not set) C:\ForExample\ REG_SZ REG_SZ REG_SZ (value not set) Notify C:\Downloads\ForExample\ REG_SZ REG_DWORD REG_DWORD REG_SZ REG_SZ REG_SZ REG_SZ (value not set) 0x1 0x2 My Documents C:\Program Files\AutoIt3\Aut2Exe\Icons My Documents

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 c ommand 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?
Use the _Singleton() function. See the User Defined Functions documentation for more information on _Singleton() and how to use it.
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.7E308 to 1.7E+308 with 15-digit precision Number range (integers): 64-bit signed integer Hexadec imal 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: 5100 levels Maximum number of variables in use at one time: No limit Maximum number of user defined func tions: No limit Maximum number of GUI windows: No limit Maximum number of GUI c ontrols: 65532
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

Using AutoIt

Running Sc ripts AutoIt on Windows Vista Command Line Parameters Script Editors Compiling Sc ripts AutoIt Window Info Tool (AU3Info) Window Titles and Text (Basic) Window Titles and Text (Advanced) Controls Unicode Support Intended Use Notes for AutoIt v2 Users Running under Windows 64-bit Edition

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 c ommand 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!

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:

TextPad Crimson Editor (free) Source Edit (free) UltraEdit

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 #inc lude 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. 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. 7. 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 <infile.au3> [/out <outfile.exe>] [/icon <iconfile.ico>] [/comp 0-4] [/nopack] [x64] [/bin <binfile.bin>] Where Switch /in /out /icon /comp /nopack /pack /x64 /x86 /console /gui /bin Usage <infile.au3> Specifies the path and file name of the script to be compiled. <outfile.exe> Specifies the path and name of the compiled file. <outfile.a3x> Specifies the path and file name when creating an *.a3x file. <iconfile.ico> Specifies the path and file name of the icon to use for the compiled file. Specifies the compression level to be used when encoding the script (This is NOT related to UPX). It must be a number between 0 (none) and 4 (maximum). Specifies that the file should not be compressed with UPX after compilation. Specifies that the file should be compressed with UPX after compilation. Specifies that the script should be compiled for use on systems with x64 (64-bit) architecture. Specifies that the script should be compiled for use on systems with x86 (32-bit) architecture. Specifies that the script should be compiled as a Console application. Specifies that the script should be compiled as a Windows application. <binfile.bin> Specifies the path and file name of the bin file to be use to compile the file. Default value None. The file must be specified The input filename with a .exe extension The AutoIt icon 2 pack pack see notes see notes Windows application (/gui) Windows application (/gui) searched in Aut2exe folder

Command Line Examples


/in c:\myscript.au3 /out c:\myapp.exe /icon c:\myicon.ico /x64 Will result in the creation of c:\myapp.exe with normal compression which will use the specified icon and be compiled for use on x64 system architecture. /in c:\myscript.au3 will result in the creation of a unicode c:\myscript.exe with normal compression which will use the default AutoIt icon for use on win_32 systems.

Command Line Notes


Long filenames should be enclosed in double-quotes like "C:\Program Files\Test\test.au3". With the exception of /in all switches are optional. By default, the 32-bit compiler produces a 32-bit binary and the 64-bit compiler produces a 64-bit binary. Use the /x86 and /x64 parameters to explicitly specify the output. The /pass and /nodecompile switches are redundant as of version 3.2.8.1. They will be ignored if used and have been removed from this list. The /ansi and /unicode switches are redundant as of version 3.3.0.0.

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

AutoIt Window Information Tool


AutoIt v3 comes with a standalone tool called the AutoIt Window Info Tool (Program File s\AutoIt3 \AU3Info.e x e ).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. Note: Hidden window can be matched by "title" only if "text" is empty ("").

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 (Kept for backward compatibility) Advanced mode Must be replaced with Advanced Window Descriptions which does not need any mode to be set. Mode -1 to -3 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) REGEXPCLASS - Window classname 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 X \ Y \ W \ H - The position and size of a 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] Note : if a Value must contain a ";" it must be doubled.

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]", "") e.g. List windows matching a classname defined by a regular expression WinList("[REGEXPCLASS:#\d+]")

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. Example $handle = WinGetHandle("Untitled - Notepad", "") WinClose($handle)

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" CLASSNN - The ClassnameNN value as used in previous versions of AutoIt, such as "Edit1" NAME - The internal .NET Framework WinForms name (if available) REGEXPCLASS - Control classname using a regular expression X \ Y \ W \ H - The position and size of a control. INSTANCE - The 1-based instance when all given properties match.

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. If a Value must contain a ";" it must be doubled. 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. Set the text of the .NET Winforms "textBoxFolder" control to "C:\Some\Folder" ControlSetText("My Window", "", "[NAME:textBoxFolder]", "C:\Some\Folder")

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 familiar 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 as a Unicode program. 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 you must use an older version of AutoIt. The last version compatible with Windows 9x was 3.2.12.x. AutoIt will read script files in ANSI or UTF16 (big or little endian) / UTF8 formats with a valid BOM. In addition, functions such as FileReadLine will automatically read text from ANSI and UTF16/UTF8 text files providing a valid BOM is found. UTF8 files with or without a BOM are also supported. Output functions such as FileWriteLine can use ANSI, UTF16 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 and their notation in popular editors are shown in this table: AutoIt Notation ANSI UTF16 Little Endian UTF16 Big Endian UTF8 with BOM UTF8 without BOM The recommended script format is UTF-8. ANSI formats are not recommended for languages other than English as they can cause problems when run on machines with different locales. Notepad ANSI Unicode Unicode big endian UTF-8 Not supported Notepad++ ANSI UCS-2 Little Endian UCS-2 Big Endian UTF-8 UTF-8 without BOM SciTe (AutoIt Default Editor) 8 bit / Code Page Property UCS-2 Little Endian UCS-2 Big Endian UTF-8 with BOM UTF-8

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

Send and ControlSend - Instead, Use ControlSetText or the Clipboard functions. Console operations are converted to ANSI.

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. 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 <filename of script file> - Conventions: <cmd>, <parameter1> [,<parameter2>] 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 AdlibOn Bloc kInput Break DetectHiddenText Exit EnvAdd EnvDiv EnvMult EnvSub FileAppend FileCopy FileCreateDir FileDelete FileInstall FileReadLine FileRemoveDir FileSelectFile Gosub Return Goto HideAutoItDebug HideAutoItWin IfInString Version 3 equivalent AdlibRegister Bloc kInput Break AutoItSetOption("WinDetectHiddenText",...) Exit [see + operator] [see / operator] [see * operator] [see - operator] [FileOpen(...,2) followed by FileWriteLine] FileCopy DirCreate FileDelete or FileRecycle FileInstall FileReadLine DirRemove FileOpenDialog or FileSaveDialog [see Func...EndFunc] [see Func...EndFunc] [not needed] -AutoItSetOption("TrayIconHide",...) If StringInStr(...) Then

IfNotInString IfWinExist IfWinNotExist IfWinActive IfWinNotActive IfEqual IfNotEqual IfGreater IfGreaterOrEqual IfLess IfLessOrEqual IfExist IfNotExist IfMsgBox IniRead IniWrite IniDelete InputBox LeftClick RightClic k LeftClic kDrag RightClic kDrag MouseGetPos MouseMove MsgBox Random RegRead RegWrite RegDelete Repeat EndRepeat Run RunWait Send SetCapslockState SetEnv SetBatchLines SetKeyDelay SetStoreCapslockMode SetTitleMatchMode SetWinDelay Shutdown Sleep SplashTextOn SplashTextOff

If Not StringInStr(...) Then If WinExists(...) Then If Not WinExists(...) Then If WinActive(...) Then If Not WinActive(...) Then [see = and == operators] [see <> operator] [see > operator] [see >= operator] [see < operator] [see <= operator] FileExists If Not FileExists(...) Then [see MsgBox(...) and Select...Case...EndSelect] IniRead IniWrite IniDelete InputBox MouseClick("left",...) MouseClick("right",...) MouseClic kDrag("left",...) MouseClic kDrag("right",...) MouseGetPos MouseMove MsgBox Random RegRead RegWrite RegDelete [see For...Next] [see For...Next] Run RunWait Send AutoItSetOption("SendCapsloc kMode",0) + Send ("{CAPSLOCK}") EnvSet -AutoItSetOption("SendKeyDelay",...) AutoItSetOption("SendCapslockMode",...) AutoItSetOption("WinTitleMatchMode",...) AutoItSetOption("WinWaitDelay",...) Shutdown Sleep SplashTextOn and others SplashOff

StringCaseSense StringLeft StringRight StringMid StringLen StringReplace StringTrimLeft StringTrimRight StringGetPos WinGetActiveStats WinGetActiveTitle WinKill WinWait WinWaitClose WinWaitActive WinWaitNotActive WinHide WinShow WinRestore WinMinimize WinMaximize WinActivate WinClose WinMove WinSetTitle WinMinimizeAll WinMinimizeAllUndo #Inc lude %CLIPBOARD% A_OSTYPE A_OSVERSION A_SCRIPTNAME A_SCRIPTDIR A_SCRIPTFULLPATH A_WORKINGDIR A_NUMBATCHLINES A_SEC A_MIN A_HOUR A_MDAY A_MON A_YEAR A_WDAY A_YDAY

[see individual functions] StringLeft StringRight StringMid StringLen StringReplace StringTrimLeft StringTrimRight StringInStr [see WinGetPos, WinGetTitle, WinGetText] WinGetTitle("") WinKill WinWait WinWaitClose WinWaitActive WinWaitNotActive WinSetState(..., @SW_HIDE) WinSetState(..., @SW_SHOW) WinSetState(...,@SW_RESTORE) WinSetState(...,@SW_MINIMIZE) WinSetState(...,@SW_MAXIMIZE) WinActivate WinClose WinMove WinSetTitle WinMinimizeAll WinMinimizeAllUndo #Inc lude [see ClipGet and ClipPut] @OSType @OSVersion @Sc riptName @Sc riptDir @ScriptFullPath @WorkingDir -@SEC @MIN @HOUR @MDAY @MON @YEAR @WDAY @YDAY

Running under Windows 64-bit Edition


AutoIt has traditionally been a 32-bit application. With the 3.2.10.0 release native x64 versions of some components have been added, including:

AutoIt (AutoIt3_x64.exe) Aut2Exe (Aut2Exe_x64.exe) Au3Info (Au3Info_x64.exe) AutoItX (AutoItX3_x64.dll)

During installation, if found to be running on x64 you will be given the choice to install and configure the x64 versions. These versions are fully x64 compatible, however, some scripts that use DllCall/DllStruct with custom structures may use values that break 64-bit compatibility (such as using 32-bit integers for pointers). This includes some of the UDFs supplied with AutoIt as they have not all been tested under x64. You can run the x86 version of AutoIt by right-clicking a script and selecting "Run Script (x86)". If you suspect that a script is not working correctly under x64 but it works under x86 then please report a bug. To see if you are running under a 64-Bit Edition of Windows use @OSArch macro. To see if you are using the 32 or 64-bit version of AutoIt use @AutoItX64.

Running the 32-bit version of AutoIt on a x64 System


For Files, Windows has a special redirection mechanism for some system directories : Directories @SystemDir @ProgramFilesDir 32-bit Value @WindowsDir & "\SYSWOW64" {SystemDrive} & "\Program Files (x86)" 64-Bit Value @WindowsDir & "\System32" {SystemDrive} & "\Program Files"

It is possible to access the 64-bit version of those directories by disabling the redirection mechanism. DllCall("kernel32.dll", "int", "Wow64DisableWow64FsRedirection", "int", 1) Some more information can be found at MSDN. For registry, use HKCR64 or HKLM64 to bypass the redirection mechanism see Registry Functions documentation.

Tutorials

My First Script (Hello World) Simple Notepad Automation WinZip Installation String Regular expression

Tutorial - HelloWorld
This tutorial explains the basics of creating an AutoIt script and running it. The tutorial assumes that you have already fully installed AutoIt v3 using the supplied installer. First open a folder where you wish to create the script. Right-click in the folder and select New / AutoIt v3 Script.

A new file will be created, immediately allowing you to rename it to something more appropriate. Change 'New AutoIt v3 Script' to 'helloworld', leaving the '.au3' in the name intact if it is visible.

Now we have created the script file we want to edit it to make it do something useful. Right-click on helloworld.au3 and select Edit Script.

The SciTE editor will open and you will see something like this:

The code you see is simply some comments that you can use to organise your scripts. The lines that start with a semi-colon ; and are treated as comments (ignored). ; is similar to the REM statement in a DOS batch file. Now we want to tell AutoIt to display a message box - this is done with the MsgBox function. At the bottom of the file type the following: MsgBox(0, "Tutorial", "Hello World!") All functions take parameters, MsgBox takes three - a flag, a title and a message. The flag is a number that changes the way MsgBox displays - we will use 0 for now. The title and message are both string parameters when using strings in AutoIt surround the text in double or single quotes. "This is some text" or 'This is some text' - both will work fine. Now save the script and close the editor. You've just written your very first AutoIt script! To run the script simply double-click the helloworld.au3 file (you may also right-click the file and select Run Script) . You should see this:

Now, let's look at the flag parameter for the MsgBox function again. From the manual page we can see various values listed which change the way MsgBox displays. The value of 0 simply shows a simple message box with an OK button. A value of 64 displays the message box with an information icon. Edit the script again and change the 0 to 64 so you have: MsgBox(64, "Tutorial", "Hello World!") Run the script and you will see:

Experiment with the various flag values to see what kind of results you can get. Remember, if you want to use more than one flag value then simply add the required values together.

Tutorial - Notepad
This tutorial explains how to automate the opening of Notepad, automatically type some text and then close Notepad. It is assumed that you are already familiar with creating and running AutoIt scripts as shown in the HelloWorld tutorial. First create an empty script called npad.au3 and then edit the file (using Notepad or SciTe as you prefer). The first thing we need to know is the name of the Notepad executable. It is notepad.exe - you can get this information by looking at the properties of the Notepad shortcut icon in the Start Menu. To execute Notepad we use the AutoIt Run function. This function simply launches a given executable and then continues. Type in the first line of script as: Run("notepad.exe") Run the script - if all goes well then a new instance of Notepad should open. When automating applications AutoIt can check for window title so that it knows which window it should work with. With Notepad the window title is obviously Untitled - Notepad. AutoIt is case-sensitive when using window titles so you must get the title exactly right - the best way to do this is to use the AutoIt Window Information Tool. Run the Information Tool from Start Menu \ AutoIt v3 \ AutoIt Window Info. With the Info Tool open click on the newly opened Notepad window to activate it; the Info Tool will give you information about it. The information we are interested in is the window title.

Highlight the title in the AutoIt Info Tool window and press CTRL-C to copy it to the clipboard - we can then paste the title into our script without fear of misspelling it. After Running a copy of Notepad we need to wait for it to appear and become active before we send any keystrokes. We can wait for a window using the WinWaitActive function. Most window-related functions in AutoIt take a window title as a parameter. Enter the following as the second line in the script (use CTRL-V or Edit\Paste to paste our window title from the clipboard). WinWaitActive("Untitled - Notepad") After we are sure the Notepad window is visible we want to type in some text. This is done with the Send function. Add this line to our script. Send("This is some text.") The entire script will now look like this:

Run("notepad.exe") WinWaitActive("Untitled - Notepad") Send("This is some text.") Close the copy of Notepad that we previously opened (you will need to do this every time you run the script otherwise you will end up with lots of copies running!). Run the script. You should see Notepad open, and then some text will magically appear!

Next we want to close notepad, we can do this with the WinClose function. WinClose("Untitled - Notepad") When Notepad tries to close you will get a message asking you to save the changes. Use the Window Info Tool to get details of the dialog that has popped up so that we can respond to it :)

So, we add a line to wait for this dialog to become active (we will also use the window text to make the function more reliable and to distinguish this new window from the original Notepad window): WinWaitActive("Notepad", "Do you want to save") Next we want to automatically press Alt-N to select the No/Don't save button (Underlined letters in windows usually indicate that you can use the ALT key and that letter as a keyboard shortcut). In the Send function to send an ALT key we use ! . Send("!n") Our complete script now looks like this:

Run("notepad.exe") WinWaitActive("Untitled - Notepad") Send("This is some text.") WinClose("Untitled - Notepad") WinWaitActive("Notepad", "Do you want to save") Send("!n") Run the script and you will see Notepad open, some text appear, then close! You should be able to use the techniques learned in this tutorial to automate many other applications.

Tutorial - WinZip
This tutorial explains how to automate the installation of WinZip 9 SR-1. It is assumed that you are already familiar with creating and running AutoIt scripts and the use of the AutoIt Window Information Tool to read window titles and text, as shown in the HelloWorld and Notepad tutorials. The WinZip installation consists of approximately 10 dialog boxes that you must click buttons (usually Next) to continue. We are going to write a script that simply waits for these dialog boxes to appear and then clicks the appropriate buttons. As usual with these types of installations the window title of each dialog is the same (WinZip Setup) so we must use window text to tell the difference between windows. Screenshots of each dialog will be provided and you can click on the picture to see the Information Tool output for that dialog. First create a directory that we will use for the WinZip installer and our script file. Copy the WinZip installer to this directory and create a blank script called winzipinstall.au3.

We will now run through the installation manually and write the script as we go. The script lines to automate each dialog will be shown after each picture (remember to click on the picture to see the AutoIt Window Information Tool output). You can also look at the completed script for reference. The first script line is easy, we want to run the winzip90.exe installer. So the first line is: Run("winzip90.exe") The first dialog will pop-up:

We need to wait for this window to popup and become active, and then we need to send the keystroke ALT-s to click the Setup button. The resulting script lines are: WinWaitActive("WinZip 9.0 SR-1 Setup", "&Setup") Send("!s") (Remember to click on the picture to see the AutoIt Window Information Tool output, this is especially important as the title contains the special (R) character which would be difficult to type). The installation location dialog will appear next:

We need to wait for this screen to be active and then click ENTER to accept the install location. The script lines are: WinWaitActive("WinZip Setup", "into the following folder") Send("{ENTER}") The WinZip Features dialog will appear next:

Notice that this window has exactly the same title as the first of WinZip Setup - in fact all the dialogs in the setup have this title! In order to tell the difference between these windows we must also use the window text on each screen try to pick the most unique text you can. In this case I've chosen WinZip features include. After the window has appeared we will want to press ALT-n: WinWaitActive("WinZip Setup", "WinZip features include") Send("!n") The License dialog will appear next:

Wait for the window to appear and then press ALT-y to accept the agreement: WinWaitActive("License Agreement") Send("!y") Setup continues in a similar fashion for a few dialogs. The picture of each dialog is shown along with the script lines needed to automate it.

WinWaitActive("WinZip Setup", "Quick Start Guide") Send("!n")

WinWaitActive("WinZip Setup", "switch between the two interfaces") Send("!c") Send("!n")

WinWaitActive("WinZip Setup", "&Express setup (recommended)") Send("!e") Send("!n")

WinWaitActive("WinZip Setup", "WinZip needs to associate itself with your archives") Send("!n")

This is the final dialog of the setup. Notice that the Finish button doesn't have a keyboard shortcut - luckily it is the default button on this dialog so we can just press ENTER to select it. If this were not the case then we would have to TAB between controls or better yet use the ControlClic k function. WinWaitActive("WinZip Setup", "Thank you for installing this evaluation version") Send("{ENTER}") After installation WinZip will automatically start:

We simply wait for the main WinZip window to appear and then close it with the WinClose function. WinWaitActive("WinZip (Evaluation Version)") WinClose("WinZip (Evaluation Version)") Here is the completed script - note that I have commented each dialog separately which makes it easier to follow and to change in the future (the next version of WinZip may be slightly different). And that's it! Run the winzipinstaller.au3 script and watch as WinZip is installed in just a few seconds! The techniques used in this tutorial can be used to automate the installation of most programs. As an exercise for the reader, try and redo the script but instead of using the Send function (which sends keys to the active window) to click on buttons try and use ControlClic k instead which can be much more reliable. You will need to read up on Controls to do this.

Tutorial - Regular Expression


Here's a smallish guide on unravelling the seeming mysteries of StringRegExp(). StringRegExp( "test", "pattern" [, flag ] ) "test" = The string to search through for matches. "pattern" = A string consisting of certain key characters that let the function know PRECISELY what you want to match. No ifs, ands, or buts.. it's a match or it isn't. flag[optional] = Tells the function if you just want to know if the "pattern" is found, or if you want it to return the first match, or if you want it to return all the matches in the "test" string.

The Very Basics


As you may have figured out, the "pattern" string is the only difficult part of calling a StringRegExp() (forthwith: SRE). I find it best to think of patterns as telling the function to match a string character by character. There are different ways to find a certain character: If you want to match the string "test", that should be simple enough. You want to tell SRE to first search the string for a "t". If it finds one, then it assumes it has a match, and the rest of the pattern is used to try to prove that what it's found is not a match. So, if the next character is an "e", it could still be a match. Let's say the next letter is an "x". SRE knows immediately that it hasn't found a match because the third character you tell it to look for is an "s". Example 1 MsgBox(0, "SRE Example 1 Result", StringRegExp("text", 'test')) In this example, the message box should read "0", which means the pattern "test" was not found in the test string "text". I know this seems pretty simple, but now you know why it wasn't found. The next way of specifying a pattern is by using a set ("[ ... ]"). You can equate a set to the logic function "OR". Let's use the previous Example. We want to find either the string "test" or the string "text". So, the way I start looking for a pattern is to think like SRE would think: The first character I want to match is "t", then the letter "e", this is the same for both strings we want to match. Now we want to match "s" OR "x", so we can use a set as a substitute: "[sx]" means match an "s" or an "x". Then the last letter is a "t" again. Example 2 MsgBox(0, "SRE Example 2 Result", StringRegExp("text", 'te[sx]t')) MsgBox(0, "SRE Example 2 Result", StringRegExp("test", 'te[sx]t')) These should both provide the result "1", because the pattern should match both "test" and "text". You can also specify how many times to match each character by using "{number of matches}" or you can specify a range by using "{min, max}". The first example below is redundant, but shows what I mean: Example 3 MsgBox(0, "SRE Example 3 Result", StringRegExp("text", 't{1}e{1}[sx]{1}t{1}')) MsgBox(0, "SRE Example 3 Result", StringRegExp("aaaabbbbcccc", 'b{4}'))

The Not-So Basics


Right now you're probably thinking "Isn't this just a glorified StringInStr() function?". Well, using a "flag" value of 0, most of the time you're right. But SRE is much more powerful than that. As you use SRE's more and more, you'll find you might know less and less about the type of pattern you are looking for. There are ways to be less and less specific about each character you wish to specify in the pattern. Take, for example, a line from the chat log of a game: "Gnarly Monster hits you for 18 damage." You want to find out how much damage Gnarly Monster hit you for. Well, you can't use StringInStr() because you aren't looking for "18", you're looking for "????", where ? could be any digit. Here's how I would assemble this pattern. Look at what you do and do not know about what you want to find: 1) You know that it will ALWAYS contain nothing but digits. 2) You know that it will SOMETIMES be 2 characters long. 2a) You know from playing the game that the maximum damage a monster can do is 999.

2b) You know that the minimum damage a monster can do is 0. 3) You know that it will ALWAYS be between 1 and 3 characters long. 4) You know that there are no other digits in the test string. At this point, I'd like to introduce the FLAG value of "1" and the grouping characters "()". The flag value of "1" means that SRE will not only match your pattern, but also return an array, with each element of the array consisting of a captured "group" of characters. So without veering off course too much, take this example: Example 4 $asResult = StringRegExp("This is a test example", '(test)', 1) If @error == 0 Then MsgBox(0, "SRE Example 4 Result", $asResult[0]) EndIf $asResult = StringRegExp("This is a test example", '(te)(st)', 1) If @error == 0 Then MsgBox(0, "SRE Example 4 Result", $asResult[0] & "," & $asResult[1]) EndIf So, first the pattern must match somewhere in the test string. If it does, then SRE is told to "capture" any groups ("()") and store them in the return array. You can use multiple captures, as demonstrated by the second piece of code in Example 4. Ok, back to the Gnarly Monster. Now that we know how to "capture" text, let's construct our pattern: Since you know what you're looking for is digits, there are 3 ways to specify "match any digit": "[:digit:]", "[0-9]", and "\d". The first is probably the easiest to understand. There are a few classes (digit, alnum, space, etc. Check the helpfile for a full list) you can use to specify sets of characters, one of them being digit. "[0-9]" just specifies a range of all the digits 0 through 9. "\d" is just a special character that means the same as the first two. There is no difference between the three, and with all SRE's there are usually at least a couple ways to construct any pattern. So, first we know we want to capture the digits, so indicate that with the opening parentheses "(". Next, we know we want to capture between 1 and 3 characters, all consisting of digits, so our pattern now looks like "([0-9]{1,3}". And finally close it off with the closing parentheses to indicate the end of our group: "([0-9] {1,3})". Let's try it: Example 5 $asResult = StringRegExp("Gnarly Monster hits you for 18 damage.", _ '([0-9]{1,3})', 1) If @error == 0 Then MsgBox(0, "SRE Example 5 Result", $asResult[0]) EndIf There you go, the message box correctly displays "18". Next we need to cover non-capturing groups. The way you indicate these groups is by opening the group with "(?:" instead of just "(". Let's say your log says "You deflect 36 of Gnarly Monster's 279 damage." Now if you run Example 5's SRE on this, you'll come up with "36" instead of "279". Now what I like to do here is just determine what's different between the numbers. One that jumps out at me is that the second number is always followed by a space and then the word "damage". We could just modify our previous pattern to be "([0-9]{1,3} damage)", but what if our script is just looking for the amount of damage, without " damage" tacked onto the end of the number? Here's where you can use a non-capturing group to accomplish this. Example 6 $asResult = StringRegExp("You deflect 36 of Gnarly Monster's 279 damage.", '([0-9]{1,3})(?: damage)', 1) If @error == 0 Then MsgBox(0, "SRE Example 6 Result", $asResult[0]) EndIf This could get lengthy, but mostly I just wanted to lay out the foundation for how regular expressions work, and mainly how SRE "thinks". A few things to keep in mind:

- Remember to think about the pattern one character at a time - The StringRegExp() function finds the first character in the pattern, then it's your job to provide enough evidence to "prove" whether or not it truly is a match. Example 6 is a good display of this. - Remember [ ... ] means OR ([xyz] matc h an "x", a "y", OR a "z") If you have any other questions, consult the help file first! It explains in detail all of the nitty gritty syntax that comes along with SRE's. One thing to look at in particular is the section on "Repeating Characters". It can make your pattern more readible by substituting certain characters for ranges. For example: "*" is equivalent to {0,} or the range from 0 to any number of characters. Good luck, Regular Expressions can greatly decrease the length of your code, and make it easier to modify later. Corrections and feedback are welcome!

Resources
Wikipedia Article - Regular Expressions - Thanks blindwig. The 30 Minute Regex Tutorial - by Jim Hollenhorst. GUI for testing various StringRegExp() patterns - Thanks steve8tch. Credit: w0uter Thanks to neogia for this tutorial.

Language Reference
The basics of the AutoIt language:

Datatypes Variables Macros Operators Conditional Statements Loop Statements Obj Statements User Functions Comments

Language Reference - Datatypes


In AutoIt there is only one datatype called a Variant. 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) If a string is used as a number, an implicit call to Number() function is done. So if it doesn't contain a valid number, it will be assumed to equal 0. For example, 10 * "fgh" equals the number 0. If a string is used as a boolean and it is an empty string "" , it will be assumed to equal False (see below). For example, NOT "" equals the Boolean true.

Numbers
Numbers c an be standard dec imal numbers like 2, 4.566, and -7. Scientific notation is also supported; therefore, you could write 1.5e3 instead of 1500. Integers (whole numbers) can also be represented in hexadecimal notation by preceding the integer with 0x as in 0x409 or 0x4fff (when using hex notation only 32-bit numbers are valid).

Strings
Strings are enclosed in double-quotes like "this". If you want a string to actually contain a double-quote use it twice like: "here is a ""double-quote"" - ok?" You can also use single-quotes like 'this' and 'here is a ' 'single-quote' ' - ok?' You can mix quote types to make for easier working and to avoid having to double-up your quotes to get what you want. For example if you want to use a lot of double-quotes in your strings then you should use singlequotes for declaring them: 'This "sentence" contains "lots" of "double-quotes" does it not?' is muc h simpler than: "This ""sentence"" contains ""lots"" of ""double-quotes"" does it not?" When evaluated, strings can have Env variables or Var variables substitution according to Opt() function definition.

Booleans
Booleans are logical values. Only two Boolean values exist: true and false. They can be used in variable assignments, together with the Boolean operators and, or and not. Examples: $Boolean1 = true $Boolean2 = false $Boolean3 = $Boolean1 AND $Boolean2

This will result in $Boolean3 being false $Boolean1 = false $Boolean2 = not $boolean1 This will result in $Boolean2 being true If Boolean values are used together with numbers, the following rules apply: A value 0 will be equal to Boolean false Any other number value will be equal to Boolean true Example: $Number1 = 0 $Boolean1 = true $Boolean2 = $Number1 and $Boolean1 This will result in $Boolean2 being false If you use arithmetics together with Boolean values (which is not advisable!), the following rules apply: A Boolean true will be converted into the numeric value 1 A Boolean false will be converted into the numeric value 0 Example: $Boolean1 = true $Number1 = 100 $Number2 = $Boolean1 + $Number1 This will result in $Number2 to be the numeric value 101 If you use strings together with Boolean values, they will be converted as follows: A Boolean true will be the string value "True" A Boolean false will be the string value "False" Example: $Boolean1=true $String1="Test is: " $String2=$String1 & $Boolean1 This will result in $String2 being the string value "Test is: True" The other way around however is different. When you use string comparisons with Boolean values, the following rules apply: Only an empty string ("")will be a Boolean false Any other string values(including a string equal "0")will be a Boolean true

Binary
Binary type can store any byte value. they are converted in hexadecimal representation when stored in a string variable. Example: $bin = Binary("abc ") $str = String($bin) ; "0x616263"

Pointer
Pointer types store a memory address which is 32bits or 64bits depending on if the 32bit or 64 bit of AutoIt is used. They are converted to hexadecimal representation when stored in a string variable. Window handles (HWnd) as returned from WinGetHandle are a pointer type.

Datatypes and Ranges


The following table shows the internal variant datatypes and their ranges. Data Sub-type Range and Notes Int32 Int64 Double String Binary Pointer Some functions in AutoIt only work with 32 bit numbers (e.g. BitAND) and are converted automatically - these functions are documented where required. A 32bit signed integer number. A 64bit signed integer number A double-precision floating point number. Can contain strings of up to 2147483647 characters. Binary data, can contain up to 2147483647 bytes. A memory address pointer. 32bit or 64bit depending on the version of AutoIt used.

Language Reference - Variables


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 Each variable is stored as a variant.

Declaring Variables
Variables are declared and created with the Dim, Local and Global keywords: Dim $var1 Or you can declare multiple variables at once: Dim $var1, $myvariable You can also assign a variable without declaring it first, but many prefer explicit declarations. $var1 = "create and assign"

Declaring Constants
Constants are declared and created using Const keyword like: Const $const1 = 1, $const2=12 Constants can be declared and initialized using Enum keyword like: Enum $const1 = 1, $const2, $const3 ; 1, 2, 3 Enum STEP 2 $incr0, $incr2, $incr4 ; 0, 2, 4 Enum STEP *2 $mult1, $mult2, $mult4 ; 1, 2, 4 Constants cannot redeclare an existing variable.

Scope
A variable's scope is controlled by when and how you declare the variable. If you declare a variable at the start of your script and outside any functions it exists in the Global scope and can be read or changed from anywhere in the script. If you declare a variable inside a function it is in Local scope and can only be used within that same function. Variables created inside functions are automatically destroyed when the function ends. By default when variables are declared using Dim or assigned in a function they have Local scope unless there is a global variable of the same name (in which case the global variable is reused). This can be altered by using the Local and Global keywords to declare variables and force the scope you want.

Arrays
An Array is a variable containing series of data elements of the same type and size. Each element in this

variable can be accessed by an index number. An example: Let's say you want to store these series of characters: "A", "U", "T", "O", "I", "T" and "3". You could use seven separate variables to do so, but using an Array is more efficient: $Array[0]="A" $Array[1]="U" ..etc.. $Array[6]="3" To access a specific value in an Array, you only have to know the index number: $MyChar=$Array[2] This results in $MyChar containing the letter "T" (See also: 'operators'). The index number can also be substituted by another variable or an expression, so you can build complex ways to assign or access elements in an array. Arrays can also be multi dimensional, when you use multiple series of index numbers, like: $Array[0][0]="Upper-Left" $Array[1][0]="Lower-Left" $Array[0][1]="Upper-Right" $Array[1][1]="Lower-Right" (These values are just examples) You can use up to 64 dimensions in an Array. The total number of entries cannot be greater than 2^24 (16 777 216). Before you can start using Arrays in your script, you must define their bounds using the 'Dim' keyword.

Data types in Arrays


It was said that an Array contains only one datatype of the same type. But technically speaking, a Variant in AutoIt can contain anything from a number to a boolean value. So an AutoIt-Array could also contain different types, even other Arrays: $Array[0]=1 $Array[1]=true $Array[2]="Text" $Array[3]=$AnotherArray This has not been strictly forbidden in AutoIt. However, it is NOT ADVISABLE to mix different datatypes in an Array. Especially the use of an Array inside another Array will severely affect the execution speed of your script.

Language Reference - Macros


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. Go here for a complete list.

Language Reference - Operators


AutoIt has the following assignment, mathematical, comparison, and logical operators. Operator Description Assignment operators = += -= *= /= &= + * / & ^ Assignment. e.g. $var = 5 (assigns the number 5 to $var) Addition assignment. e.g. $var += 1 (adds 1 to $var) Subtraction assignment. Multiplication assignment. Division assignment. Concatenation assignment. e.g. $var = "one", and then $var &= 10 ($var now equals "one10") Mathematical operators 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) Comparison operators (case insensitive if used with strings except for ==) = == <> > >= < <= Tests if two values are equal. e.g. If $var= 5 Then (true if $var equals 5). Case insensitive when used with strings. Tests if two strings are equal. Case sensitive. The left and right values are converted to strings if they are not strings already. This operator should only be used for string comparisons that need to be case sensitive. Tests if two values are not equal. Case insensitive when used with strings. To do a case sensitive not equal comparison use Not ("string1" == "string2") Tests if the first value is greater than the second. Strings are compared lexicographically even if the contents of the string happen to be numeric. Tests if the first value is greater than or equal to the second. Strings are compared lexicographically even if the contents of the string happen to be numeric. Tests if the first value is less than the second. Strings are compared lexicographically even if the contents of the string happen to be numeric. Tests if the first value is less than or equal to the second. Strings are compared lexicographically even if the contents of the string happen to be numeric. Logical operators AND OR NOT 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 ^ * / + & Logical AND operation. e.g. If $var = 5 AND $var2 > 6 Then (True if $var equals 5 and $var2 is greater than 6) Logical OR operation. e.g. If $var = 5 OR $var2 > 6 Then (True if $var equals 5 or $var2 is greater than 6) Logical NOT operation. e.g. NOT 1 (False)

< > <= >= = <> == 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. Note the following when using the logical operators AND, OR: e.g. If MyFunc1() OR MyFunc2() Then (MyFunc2() is not called if MyFunc1() returns true) e.g. If MyFunc1() AND MyFunc2() Then (MyFunc2() is not called if MyFunc1() returns false)

Language Reference - Conditional Statements


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? Conditions are evaluated as true (non-zero) or false (zero). Conditions generally use comparison operators like ==, <>, >=. The following conditional statements are available in AutoIt:

If...Then...Else Select...Case Switch...Case

All three statements are similar and decide which code to execute depending on the condition(s) given. Here is an example of an If statement that pops up a message box depending on the value of a variable. $var = -20 If $var > 0 Then MsgBox(0, "Example", "$var was positive!") ElseIf $var < 0 Then MsgBox(0, "Example", "$var was negative!") Else MsgBox(0, "Example", "$var was zero.") EndIf In the example above, the expression $var > 0 evaluated to false because the variable was less than zero. When the first condition failed, the second condition was tested. The expression $var < 0 evaluated to true. This caused the If statement to execute the second MsgBox line and display "$var was negative!". A Select statement is very similar, but is generally used for situations where you want to test a large number of conditions as it is generally easier to read than a large If/ElseIf type block. e.g. $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 A Switch statement is very similar to Select statement, but is generally used for situations where the same expression is tested against some different possible values. $var = 30 Switch Int($var) Case 1 To 10 MsgBox(0, "Example", "$var was greater than 1")

Case 11 To 20 MsgBox(0, "Example", "$var was greater than 10") Case 21 To 30 MsgBox(0, "Example", "$var was greater than 20") Case 31 To 40 MsgBox(0, "Example", "$var was greater than 30") Case Else MsgBox(0, "Example", "$var was greater than 40 or less or equal to 0") EndSwitch With each of these structures, the first condition that is true controls which group of statements get executed. All subsequent conditions and their associated statements get ignored.

Language Reference - Loop Statements


A loop is how you refer to a section of script that you repeat a number of times. You 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 For...In...Next

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.

Language Reference - Obj Statements


An obj is how you refer to an object. You might want to enumerate elements in an Object collection The following obj statements are available in AutoIt:

With...Endwith For...In...Next

Language Reference - User 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, built-in functions and user functions.

Built-in Functions
The full list of built-in functions is here and the notes on using them are here.

User Functions
User functions are declared using the Func...EndFunc statements. 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 Here is an example of using a function to double a number 10 times: $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

Language Reference - Comments


Although only one statement per line is allowed, a long statement can span multiple lines if an underscore " _" preceded by a blank is placed at the end of a "broken" line. String definition cannot be split in several lines, concatenation need to be used. MsgBox(4096,"", "This is a rather long line, so I " & _ "broke it with the underscore, _, character.") The semicolon (;) is the comment character. Unless the semicolon is within a string, all text following it is ignored by the script interpreter/compiler. ; The next line contains a meaningful, end-of-line comment Sleep(5000) ;pause 5 seconds You can combine underscore and semicolon to put comments on lines and still havea long statement span on next line. dim $b_ ; This _ is not a continuation character, nor is the next one dim $k_ Dim $a[8][2] = [ _ [ "Word", 4 ], _ ; Comment 1 [ "Test", 3 ], _ [ "pi", 3.14159], _ ; Associate the name with the value [ "e", 2.718281828465], _ ; Same here [ "test;1;2;3", 123], _ [ ';', Asc(';') ], _ ; This comment is removed, but the strings remain. ["", 0] ] It is also possible to comment of large blocks of script by using the #c omments-start and #c omments-end directives.

GUI Reference

GUI Concepts GUI MessageLoop Mode GUI OnEvent Mode GUI Constants include files

GUI Reference
AutoIt has the ability to create simple Graphical User Interfaces (GUIs) that consist of windows and controls.

GUI Concepts
A GUI consists of one or more windows and each window contains one or more controls. GUIs are "event driven" which means you react to events - like a button that is clicked. You spend most of your time idling and waiting for an event to happen - this is a little different to a normal script where you are in control of what happens and when! Think of it as waiting by the door for the postman - you sit there until a letter pops through the postbox and then you look at the letters and decide what to do with them - this is exactly how GUIs work - you wait for the postman to come to you. Of course, you may choose to do other tasks while the GUI is active - for example you might use the GUI functions to create an elaborate progress box that you update while your script performs complex actions.

GUI Controls
All users will be familiar with controls - anything you click on or interact with in a window is a type of control. The types of controls that can be created with AutoIt are listed below - you will have used most of them in other Windows programs.

Label Button Input Edit Checkbox Radio Combo List Date Pic Icon Progress Tab UpDown Avi Menu ContextMenu TreeView Slider ListView ListViewItem Graphic Dummy

A plain piece of text. A simple button. A single line control that you can enter text into. A multi-line control that you can enter text into. A box that can be "checked" or "unchecked". A set of circular buttons - only one can be active at once. A list with a dropdown box. A list. A date picker. A picture. An icon. A progress bar. A group of controls that are contained in tabs. A control that can be added to input controls. Display an AVI format clip. A menu across the top of the window. A menu that appears when you right click inside the window. A control similar to the windows file-explorer. A control similar to the windows sound volume control. A control displaying columns information. A control displaying item in a listview control. A control displaying graphics drawn with GUICtrlSetGraphic. A dummy user control.

Here is an example of a single window GUI that contains many of the controls available. As you can see it is possible to create very detailed GUIs!

Controls are created with the GUICtrlCreate... set of functions. When a control is created a Control ID is returned. The most important things to note about a control ID is that:

The control ID is a positive number (that is, a number greater than 0) Each control ID is unique - even when there are multiple windows The control ID is actually the same value as the Control ID that the AutoIt Window Info Tool shows.

GUI Basic Functions


These are the main functions that you will need to create a GUI. They are just the basics though, there are many more when you are ready to create some really advanced GUIs. Function GUICreate GUISetState GUIGetMsg GUICtrlRead GUICtrlSetData Explanation Create a window. Display or hide the window. Poll the GUI to see if an event has happened (MessageLoop mode only) Read the data in a control. Set/change the data in a control.

GUICtrlCreate... Create various controls in a window.

GUICtrlUpdate... Change various options for a control (color, style, etc.) You will need to #include <GUIConstantsEx.au3> for basic GUI related constants. There are other files containing constants related to the various controls you can create on the GUI. First let's create a window, call it "Hello World" and make it 200 by 100 pixels in size. When a new window is created it is hidden - so we must "show" it. #include <GUIConstantsEx.au3> GUICreate("Hello World", 200, 100) GUISetState(@SW_SHOW) Sleep(2000)

If your run the above script you will see a window open and close after 2 seconds. Not very interesting...let's add some text and an OK button. The text will be added at position 30, 10 and the button at 70, 50 and the button will be 60 pixels wide. #include <GUIConstantsEx.au3> GUICreate("Hello World", 200, 100) GUICtrlCreateLabel("Hello world! How are you?", 30, 10) GUICtrlCreateButton("OK", 70, 50, 60) GUISetState(@SW_SHOW) Sleep(2000) That's pretty good, but how do we make the GUI react to us clicking the button? Well, this is where we must make a decision as to how we will process events - via a MessageLoop or via OnEvent functions.

GUI Event Modes


As mentioned above there are two basic GUI modes: MessageLoop mode and OnEvent mode. The modes are simply two different ways of reacting to GUI events. The mode you choose will depend on personal preference, and to some extent the type of GUI you wish to create. Both modes are equally capable of creating any GUI you wish but sometimes one mode is more suited to a task than the other. The default mode is the MessageLoop mode. To switch to OnEvent mode use Opt("GUIOnEventMode", 1). Message-loop Mode (default) In the Message-loop mode your script will spend the majority of its time in a tight loop. This loop will simply poll the GUI using the GUIGetMsg function. When an event has occurred the return value of the GUIGetMsg function will show the details (a button is clicked, the GUI has been closed, etc.). In this mode you will only receive events while you are actively polling the GUIGetMsg function so you must ensure that you call it many times a second otherwise your GUI will be unresponsive. This mode is best for GUIs where the GUI is "king" and all you care about is waiting for user events. See this page for a more detailed explanation of the MessageLoop mode. OnEvent Mode In the OnEvent mode instead of constantly polling the GUI to find out if anything has happened you make the GUI temporarily pause your script and call a pre-defined function to handle the event. For example, if the user clicks Button1 the GUI halts your main script and calls a previously defined user function that deals with Button1. When the function call is completed the main script is resumed. This mode is similar to the Visual Basic forms method. This mode is best for GUIs where the GUI is of secondary importance and your script has other tasks to perform in addition to looking after the GUI. See this page for a more detailed explanation of the OnEvent mode.

GUI Reference - MessageLoop Mode


In the MessageLoop mode your script will spend the majority of its time in a tight loop. This loop will simply poll the GUI using the GUIGetMsg function. When an event has occurred the return value of the GUIGetMsg function will show the details (a button is clicked, the GUI has been closed, etc.). The MessageLoop mode is the default message mode for AutoIt GUIs - the other possible mode is the OnEvent mode. In the MessageLoop mode you will only receive events while you are actively polling the GUIGetMsg function so you must ensure that you call it many times a second otherwise your GUI will be unresponsive.

Basic MessageLoop Format


The general layout of MessageLoop code is: While 1 $msg = GUIGetMsg() ... ... WEnd Usually a tight loop like the one shown would send the CPU to 100% - fortunately the GUIGetMsg function automatically idles the CPU when there are no events waiting. Do not put a manual sleep in the loop for fear of stressing the CPU - this will only cause the GUI to become unresponsive.

GUI Events
There are three types of event messages that GUIGetMsg will return:

No Event Control Event System Event

No Event When there are no events waiting to be processed GUIGetMsg returns 0. In a usual GUI this is the most common event. Control Event When a control is clicked or changes a control event is sent - this event is a positive number that corresponds to the controlID that was returned when the control was created with GUICtrlCreate.... System Event System events - such as the GUI closing - are negative numbers. The different events are shown below and are defined in GUIConstantsEx.au3: $GUI_EVENT_CLOSE $GUI_EVENT_MINIMIZE $GUI_EVENT_RESTORE $GUI_EVENT_MAXIMIZE $GUI_EVENT_PRIMARYDOWN $GUI_EVENT_PRIMARYUP $GUI_EVENT_SECONDARYDOWN $GUI_EVENT_SECONDARYUP $GUI_EVENT_MOUSEMOVE $GUI_EVENT_RESIZED $GUI_EVENT_DROPPED

Example GUI
In the main GUI Reference page we started a simple Hello World example that looked like this: #include <GUIConstantsEx.au3> GUICreate("Hello World", 200, 100) GUICtrlCreateLabel("Hello world! How are you?", 30, 10) GUICtrlCreateButton("OK", 70, 50, 60) GUISetState(@SW_SHOW) Sleep(2000) Now we will finish the code using a MessageLoop and some of the event messages described above. It is usual because of the number of possible messages to use a Select statement for readability. #include <GUIConstantsEx.au3> GUICreate("Hello World", 200, 100) GUICtrlCreateLabel("Hello world! How are you?", 30, 10) $okbutton = GUICtrlCreateButton("OK", 70, 50, 60) GUISetState(@SW_SHOW) While 1 $msg = GUIGetMsg() Select Case $msg = $okbutton MsgBox(0, "GUI Event", "You pressed OK!") Case $msg = $GUI_EVENT_CLOSE MsgBox(0, "GUI Event", "You clicked CLOSE! Exiting...") ExitLoop EndSelect WEnd It's that simple. Obviously the more windows and controls you create the more complicated it gets but the above shows you the basics.

Advanced GUIGetMsg and Multiple Windows


Control IDs are unique, even when you have multiple windows, so the above code with work fine with controls and multiple windows. However, when processing events such as $GUI_EVENT_CLOSE or $GUI_MOUSEMOVE you need to know which GUI window generated the event. To do this you must call GUIGetMsg like so: $msg = GUIGetMsg(1) When called with the 1 parameter instead of returning an event value an array will be returned, the array contains the event ( in $array[0] ) and extra information such as the window handle ( in $array[1] ). If two windows were created in the previous example then the correct way to write the code would be: #include <GUIConstantsEx.au3> $mainwindow = GUICreate("Hello World", 200, 100) GUICtrlCreateLabel("Hello world! How are you?", 30, 10) $okbutton = GUICtrlCreateButton("OK", 70, 50, 60) $dummywindow = GUICreate("Dummy window for testing ", 200, 100) GUISwitch($mainwindow) GUISetState(@SW_SHOW) While 1

$msg = GUIGetMsg(1) Select Case $msg[0] = $okbutton MsgBox(0, "GUI Event", "You pressed OK!") Case $msg[0] = $GUI_EVENT_CLOSE And $msg[1] = $mainwindow MsgBox(0, "GUI Event", "You clicked CLOSE on the main window! Exiting...") ExitLoop EndSelect WEnd The first major change is the GUISwitch function call - when a new window is created it becomes the "default" window for future GUI operations (including control creation). In our case we want to work with the main "Hello World" window, not the test window, so we "switch". Some GUI functions allow you to use the window handle in the function call itself - these functions will do the switch automatically. In our example we could have done this with: GUISetState(@SW_SHOW, $mainwindow) The next change is the way GUIGetMsg is called and how the events are checked - notice the use of $msg[0] and $msg[1] - now we only exit the script if the close event is sent and the event is from our main window.

GUI Reference - OnEvent Mode


In the OnEvent mode instead of constantly polling the GUI to find out if anything has happened you make the GUI temporarily pause your script and call a pre-defined function to handle the event. For example, if the user clicks Button1 the GUI pauses your main script and calls a previously defined user function that deals with Button1. When the function call is completed the main script is resumed. This mode is similar to the Visual Basic forms method. While the GUI is executing, your main script could be doing any normal scripting work, but for ease of examples we will just make the main script "idle" in an infinite While loop. The default mode is the MessageLoop mode so before using the OnEvent mode we must use Opt ("GUIOnEventMode", 1).

Basic OnEvent Format


The general layout of OnEvent code is: While 1 Sleep(1000) ; Just idle around WEnd Func Event1() ; Code to handle event goes here EndFunc Func Event2() ; Code to handle event goes here EndFunc

GUI Events
In the OnEvent mode your GUI will generate the following "events":

Control Event System Event

Both types of event will call a user defined function if one was set for the GUI (GUISetOnEvent) or for a control (GUICtrlSetOnEvent). If no functions are defined for an event then it is simply ignored. When inside this called function various macros will be set to values to help process the event. Macro @GUI_CT RLID @GUI_WINHANDLE Details The control ID of the control sending the message OR the system event ID The handle of the GUI that sent the message

@GUI_CT RLHANDLE The handle of the Control that sent the message (if applicable) Note: It is perfectly legal to use the same function for multiple events, all that you need to do in these cases is to take action based on the @GUI_CTRLID macro. For example, you could register all system events to the same function. Control Event When a control is clicked or changes a control event is sent. The event is sent to the function defined with GUICtrlSetOnEvent. Inside the user defined function @GUI_CTRLID is set to the controlID that was returned when the control was created with GUICtrlCreate.... System Event System events - such as the GUI closing - are sent in a similar way to Control event, but the event type is defined by @GUI_CTRLID. The event is sent to the function defined with GUISetOnEvent. The possible system event values are shown here: $GUI_EVENT_CLOSE

$GUI_EVENT_MINIMIZE $GUI_EVENT_RESTORE $GUI_EVENT_MAXIMIZE $GUI_EVENT_PRIMARYDOWN $GUI_EVENT_PRIMARYUP $GUI_EVENT_SECONDARYDOWN $GUI_EVENT_SECONDARYUP $GUI_EVENT_MOUSEMOVE $GUI_EVENT_RESIZED $GUI_EVENT_DROPPED

Example GUI
In the main GUI Reference page we started a simple Hello World example that looked like this: #include <GUIConstantsEx.au3> GUICreate("Hello World", 200, 100) GUICtrlCreateLabel("Hello world! How are you?", 30, 10) GUICtrlCreateButton("OK", 70, 50, 60) GUISetState(@SW_SHOW) Sleep(2000) Now we will finish the code using OnEvents and some of the event messages described above. #include <GUIConstantsEx.au3> Opt("GUIOnEventMode", 1) ; Change to OnEvent mode $mainwindow = GUICreate("Hello World", 200, 100) GUISetOnEvent($GUI_EVENT_CLOSE, "CLOSEClicked") GUICtrlCreateLabel("Hello world! How are you?", 30, 10) $okbutton = GUICtrlCreateButton("OK", 70, 50, 60) GUICtrlSetOnEvent($okbutton, "OKButton") GUISetState(@SW_SHOW) While 1 Sleep(1000) ; Idle around WEnd Func OKButton() ;Note: at this point @GUI_CTRLID would equal $okbutton, ;and @GUI_WINHANDLE would equal $mainwindow MsgBox(0, "GUI Event", "You pressed OK!") EndFunc Func CLOSEClicked() ;Note: at this point @GUI_CTRLID would equal $GUI_EVENT_CLOSE, ;and @GUI_WINHANDLE would equal $mainwindow MsgBox(0, "GUI Event", "You clicked CLOSE! Exiting...") Exit EndFunc It's that simple. Obviously the more windows and controls you create the more complicated it gets but the above shows you the basics.

Advanced Operations and Multiple Windows


Control IDs are unique, even when you have multiple windows but how do we handle multiple windows? Here is an example similar to the one above but with another "dummy" window. #include <GUIConstantsEx.au3>

Opt("GUIOnEventMode", 1) ; Change to OnEvent mode $mainwindow = GUICreate("Hello World", 200, 100) GUISetOnEvent($GUI_EVENT_CLOSE, "CLOSEClicked") GUICtrlCreateLabel("Hello world! How are you?", 30, 10) $okbutton = GUICtrlCreateButton("OK", 70, 50, 60) GUICtrlSetOnEvent($okbutton, "OKButton") $dummywindow = GUICreate("Dummy window for testing ", 200, 100) GUISetOnEvent($GUI_EVENT_CLOSE, "CLOSEClicked") GUISwitch($mainwindow) GUISetState(@SW_SHOW) While 1 Sleep(1000) ; Idle around WEnd Func OKButton() ;Note: at this point @GUI_CTRLID would equal $okbutton MsgBox(0, "GUI Event", "You pressed OK!") EndFunc Func CLOSEClicked() ;Note: at this point @GUI_CTRLID would equal $GUI_EVENT_CLOSE, ;@GUI_WINHANDLE will be either $mainwindow or $dummywindow If @GUI_WINHANDLE = $mainwindow Then MsgBox(0, "GUI Event", "You clicked CLOSE in the main window! Exiting...") Exit EndIf EndFunc The first major change is the GUISwitch function call - when a new window is created it becomes the "default" window for future GUI operations (including control creation). In our case we want to work with the main "Hello World" window, not the test window, so we "switch". Some GUI functions allow you to use the window handle in the function call itself - these functions will do the switch automatically. In our example we could have done this with: GUISetState(@SW_SHOW, $mainwindow) Also notice that we used the same OnEvent function to handle the "close" button for both windows and then used @GUI_WINHANDLE to determine which window sent the message - then we only closed the GUI when the close button was clicked and the message came from the main window . You can just as easily use separate functions for each window if you wish.

COM Extensions to AutoIt


A short introduction

What is COM?
COM stands for "Component Object Model". It is the Microsoft way to interconnect software using a common interface. These interfaces are defined in a COM Object. Before COM, you had to know the exact implementation of a program before you could 'interface' with it. Using COM, you can now "talk" to its defined Object(s). The only things you have to know are the names of the Objects that are used and which 'properties' or 'methods' they have.

What are (Object) properties or methods?


These are the two basic characteristics of an Object. You can see a 'property' as the data storage of an Object. A 'method' can be seen as an internal function call to do something with the data.

Do I need COM in my AutoIt script?


It just depends. AutoIt has a lot of built-in functions and a huge library of UDF's. You can do most of your programming with these. However if you need special 'interfacing' to other applications, using COM might save you some lines of script. Scripters have to be aware that the existence of COM Objectsdepend HEAVILY on the Operating System AND the installed software. The examples below haveall been tested under a 'plain' Windows XP professional version with Microsoft Office 2000.

An example usage of COM in AutoIt


Let's say you want to minimize all open windows.You could do this using regular AutoIt functions like WinList and WinSetState. However, two lines of COM-code can give you the same result: $oShell = ObjCreate("shell.application") $oShell.MinimizeAll
Side note : The e x am ple is no longe r the shorte st way to m inim ize all windows afte r the introduction of the W inMinim ize All() function in AutoIt.

Onthe first line we create a new object called "shell.application". This is an internal Windows object, defined in shell32.dll. The pointer to this new object is assigned to the variable $oShell. $oShell is from now on an Object variable. Onthe second line, we use a Method called "MinimizeAll" to the oShell object. This will minimize all windows. All Windows versions have a huge amount of internal Objects for various purposes. And applications like Excel or Word have also their own set of Objects. However, it is sometimes difficult to get a list of all existing Objects defined on your system with their corresponding properties and methods. Searching at Microsoft.com or Google.com might give you some clues about the Object 'X' you want to use. For instance, you can find information about the "shell.application" object at: http://msdn.microsoft.com/en-us/library/bb774094.aspx

To get a peek on all objects currently installed on your system, the "OLE/COM Object Viewer" is a very helpful tool. This tool will be explained in a separate section below. Let's do another example. We would like to get a HTML source code from a certain web page. You could use the internal InetGet() function to save the result to a file and retrieve it back again with FileRead(). But these lines of code do the same: $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") $oHTTP.Open("GET","http://www.AutoItScript.com") $oHTTP.Send() $HTMLSource = $oHTTP.Responsetext The (string) variable $HTMLSource now contains the complete HTML code of the AutoItScript.com home page (that is, the top HTML-Frame). (Information about the "winhttp.winhttprequest" object can be found at: http://msdn.microsoft.com/en-us/library/aa384106.aspx ) Please mind this: The existence of Objects depend on the computer's operating system and installed programs. For example, the winhttp.winhttprequest.5.1 object only exists on computers that have at least Internet Explorer version 5 installed.When you are sharing scripts that use COM objects, be sure the objects exist on all computers. Object variables behave a bit different thanother types of AutoIt variables. An Object is not a real value, but a 'pointer' to something outside the script. So you can'tperform arithmetic's, nor equations on Object variables. When you assign an Object variable a different value, the 'pointer' will automatically be released. You can, for instance,force deletion of an Object by assigning it any number or any text value. $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") ; Object is created $oHTTP=0 ; Object is deleted You don't need to delete Objects when you are finished. If a script exits,AutoIt tries to release all active references to Objects that had been created in the script. Same thing happens when you had defined a local Object variableinside a function, and the function ends with a return.

Automation using COM


A very popular application of COM is to 'automate' programs. Instead of using the regular AutoIt functions like Send() or WinActivate(), you can make use of the Objects that are defined inside the program. Here is an example that 'automates' Microsoft Excel: $oExcel = ObjCreate("Excel.Application") ; Create an Excel Object $oExcel.Visible = 1; Let Excel show itself $oExcel.WorkBooks.Add ; Add a new workbook $oExcel.ActiveWorkBook.ActiveSheet.Cells(1,1).Value="test" ; Fill a cell sleep(4000) ;See the results for4 seconds $oExcel.ActiveWorkBook.Saved = 1 ; Simulate a save of the Workbook $oExcel.Quit ; Quit Excel

The complexity of controlling other programs depends on that specific program, not on the AutoIt script. If something does not work as expected you might need to consult the applications' documentation and not the AutoIt help.

SpecialStatements
In AutoIt, twospecial statements are designed for COM usage: WITH/ENDWITH and the FOR/IN/NEXT loop.

WITH..ENDWITH
The WITH/ENDWITH statement does not add functionality, but it makes your script easier to read. For instance, the previous example using Excel can also be written as: $oExcel = ObjCreate("Excel.Application"); Create an Excel Object WITH $oExcel .Visible = 1 ; Let Excel show itself .WorkBooks.Add ; Add a new workbook .ActiveWorkBook.ActiveSheet.Cells(1,1).Value="test" ; Fill a cell sleep(4000) ;See the results for4 seconds .ActiveWorkBook.Saved = 1 ; Simulate a save of the Workbook .Quit ; Quit Excel ENDWITH This example does not save you a lot of text, but when your object uses long lines of properties/methods, you can shorten it heavily within a WITH statement.

FOR..IN
The FOR...IN loop is required when using Collections. Collections are a special type of Object, that exist out of multiple sub-Objects. You could see them as Arrays (Actually, the FOR..IN statement also works on Array-type variables).

FOR..IN loop using an Array


Below is an example of an FOR..IN loop. This example uses a normal AutoIt array, so it has nothing to do with COM. It's just to show you the principle: $String = ""; A string for displaying purposes $aArray[0]="a"; $aArray[1]=0 ; $aArray[2]=1.3434 ; $aArray[3]="testestestest" ; We fill an array with several different example values.

FOR $Element IN $aArray ; Here it starts.. $String = $String & $Element & @CRLF NEXT ; Now Show the results to the user Msgbox(0,"For..IN Arraytest","Result: " & @CRLF & $String)

FOR..IN loop using an Object


In most cases you can't use 'normal' Object methods to retrieve the elements of a collection. In 'COM'-terms they say you have to 'enumerate' them. This is where the FOR..IN loop comes in. The Excel example below loops on cells A1:O16 on the current active sheet. If one of the cells has a value less than 5, the code replaces the value with 0 (zero): $oExcel = ObjCreate("Excel.Application") ; Create an Excel Object $oExcel.Visible = 1 ; Let Excel show itself $oExcel.WorkBooks.Add ; Add a new workbook dim $arr[16][16] ; for $i =0 to 15 ; for $j = 0 to 15 ; $arr[$i][$j] =$i ; next ; next These lines are just an example to create some cell contents.

$oExcel.activesheet.range("A1:O16").value = $arr ; Fill cells with example numbers sleep(2000) ; Wait a while before continuing For $cell in $oExcel.ActiveSheet.Range("A1:O16") If $cell.Value < 5 Then $cell.Value = 0 Endif Next $oExcel.ActiveWorkBook.Saved = 1 ; Simulate a save of the Workbook sleep(2000) ; Wait a while before closing $oExcel.Quit ; Quit Excel

Advanced COM usage


The following features of AutoItCOM requires profound knowledge of COM Events and COM Error handling. If you are a newbie to COM programming, please read some good COM documentation first. The bible of COM is the book called "Inside OLE 2" by Kraig Brockschmidt (Microsoft Press). You can also find some COM resources on the internet (not AutoIt related): http://msdn.microsoft.com/en-us/library/ms694363.aspx (introduction) http://www.garybeene.com/vb/tut-obj.htm (about Objects in Visual Basic) http://java.sun.com/docs/books/tutorial/java/concepts/ (Using objects in Java) http://msdn.microsoft.com/archive/en-us/dnarguion/html/drgui082399.asp (Object Events in C++) http://www.garybeene.com/vb/tut-err.htm (Error handling in Visual Basic )

COM Events
Normal COM Automation mainly uses one-way communication. You 'ask' the Object for any properties or results from a Method. However a COM Object can also 'talk back' to your script when it suits it. This could be very handy in cases you need to wait for some COM-related action to happen. Instead of writing a kind of loop, asking the Object if something interesting has happened, you can let the Object itself call a specific UDF in your script. Meanwhile you can do other things in your script (almost) simultaneously. Not all Object to support events. You have to read the Object documentation carefully whether it supports events or not. If it does, the second thing to know is the type of Events it supports. AutoItCOM can only receive 'dispatch' type events. Finally you have to know the names of the Events the Object could generate, including their arguments (if any). Only when you have all this information, you can start building an AutoIt script using COM Events. Below is a snippet from ascript that demonstrates how to receive Events from the Internet Explorer: $oIE=ObjCreate("InternetExplorer.Application.1") ; Create an Internet Explorer Object $EventObject=ObjEvent($oIE,"IEEvent_","DWebBrowserEvents") ; Start receiving Events. $oIE.url= "http://www.autoitscript.com"; Load an example web page ;From now on, the $oIE Object generates events during web page load. ;They are handled in the event functions shown below. ;Here you can let the script wait until the user wants to finish. ...(yourcode here)... $EventObject.stop $EventObject=0 $oIE.quit $oIE=0 Exit ; ; ; ; ; Tell IE we want to stop receiving Events Kill the Event Object Quit IE Remove IE from memory (not really necessary) End of main script

; A few Internet Explorer Event Functions. ; ; For the full list ofIE Event Functions, see theMSDN WebBrowser documentationat: ;http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.aspx Func IEEvent_StatusTextChange($Text) ; In the complete script (see link below)we show the contents in a GUI Edit box. GUICtrlSetData ( $GUIEdit, "IE Status text changed to: " & $Text & @CRLF, "append" ) EndFunc Func IEEvent_BeforeNavigate($URL, $Flags, $TargetFrameName, $PostData, $Headers, $Cancel) ; In the complete script (see link below)we show the contents in a GUI Edit box. ; Note: the declaration is different from the one on MSDN. GUICtrlSetData ( $GUIEdit, "BeforeNavigate: " & $URL & " Flags: " & $Flags & @CRLF,"append") EndFunc Click here to view the complete script. The main line in this script is: $EventObject=ObjEvent($oIE,"IEEvent_",...). This function takes the object $oIE and reroutes it's events to AutoIt functions whose names start with MYEvent_.The third parameter is optional. It is used when an Object has multiple Event interfaces and you don't want AutoIt to choose one automatically. The Object responsible for the continuous rerouting is $EventObject. This variable does not require any further attention, unless you want to stop the events. To stop rerouting Events, you can not just delete the variablelike $EventObject="". The reason is that the 'calling' Object is still holding a reference to this variable, and it won't loose it until the Object itself quits.You could solve this problem by killing the 'calling' Object, but you can alsotell the Object that you don't want to receive any events by using: $EventObject.Stop. Then you can (but not really necessary) kill theEvent by assigning it any value, like: $EventObject="" If you know the names of the Events $oIE fires, you can implement the Events you are interested in by creating AutoIt UDF's with the name IE Event_Eventname(optional arguments).Be sure you use the correct number of arguments andin theircorrect order as specified forTHAT Event function. Otherwiseyou might end upwithunexpectedvalues. If you don't know (for some reason) the names of the events, you canadd a UDF with only the prefix. In this example: Func IEEvent_($Eventname). When an event is received and no IEEvent_ Eventname UDF exists, this function will be called instead and the name of the event will be placed in the variable $Eventname. You don't have to implement ALL event functions. Those not implemented will just be ignored. More script examples using COM Event functions can be found in thetests directory in the AutoIt 3.1.1.xx beta ZIP distribution file, downloadable from:http://www.autoitscript.com/autoit3/files/beta/autoit/COM/ Limitations on COM Events in AutoIt Some Objects (like the 'WebBrowser') pass arguments to their Event Functions 'by reference'.This is intended to allow the user change these arguments and passing it back to the Object. However, AutoIt uses it's own variable scheme, which is not compatible to COM variables. This means that all values from Objects need to be converted into AutoIt variables, thus loosing the reference to the original memory space.Maybe in the near future we can solve this limitationfor you !

COM Error Handling

Using COM without proper error handling can be very tricky. Especially when you are not familiar with the Objects in your script. An AutoIt script will immediately stop execution when it detects a COM error. This is the default and also the safest setting. In this case you have to take measures in your script to prevent the error from happening. Only if there is no way to prevent a COM error, you could install an "Error Handler" in which you take action after the error has happened. It is not a solution to make a buggy script work properly. Neither does it catch non-COM related script errors (e.g. declaration and syntax errors). Error handling is implemented in the same way as a normal COM Event, using ObjEvent() and a user defined COM Event Function. The only difference is the usage of the fixed string "AutoIt.Error" as the name of the object. An example: Global $g_eventerror = 0; to be checked to know if com error occurs. Must be reset after handling. $oMyError = ObjEvent("AutoIt.Error","MyErrFunc") ; Install a custom error handler ; Performing a deliberate failure here (object does not exist) $oIE = ObjCreate("InternetExplorer.Application") $oIE.visible = 1 $oIE.bogus if $g_eventerror then Msgbox(0,"","the previous line got an error.") Exit

; This is my custom error handler Func MyErrFunc() $HexNumber=hex($oMyError.number,8) Msgbox(0,"","We intercepted a COM Error !" & @CRLF & _ "Number is: " & $HexNumber & @CRLF & _ "Windescription is: " & $oMyError.windescription ) $g_eventerror = 1 ; something to check for when this function returns Endfunc One thing is special about the Error Event Handler, and that is the Object it returns. This is an AutoIt Error Object that contains some useful properties and methods. It's implementation ispartly based on the"Err" Object in VB(script): Properties of the AutoIt Error Object: .number .windescription .source .description .helpfile .helpcontext .lastdllerror .scriptline Methods of the AutoIt Error Object: .raise Raises an error event, initiated by the user The Windows HRESULT value from a COM call The FormatWinError() text derived from .number Name of the Object generating the error(contents from ExcepInfo.source) Source Object's description of the error(contents from ExcepInfo.description) Source Object's helpfile for the error(contents from ExcepInfo.helpfile) Source Object's helpfile context id number (contents from ExcepInfo.helpcontext) The number returned from GetLastError() The script line on which the error was generated

.clear

Clears the contents of the Error Object (i.e. numbers to 0, strings to "")

A note for UDF writers You can only have ONE Error Event Handler active per AutoIt script. If you are writing UDF's containing COM functions, you can check if the user has an Error Handler installed as follows: $sFuncName = ObjEvent("AutoIt.Error") if $sFuncName <> "" thenMsgbox (0,"Test","User has installed Error Handler function: " & $sFuncName) If no Error Handler was active, you can temporarily install your own during the UDF call. However, you can never stop an existingError Handler without releasing the variable it had been assigned to. If the script author had installed a COM Error Handler, it's hisresponsibilityto use a properfunction thatwill also be able to catch COM errors generated by UDF's.

OLE/COM Object Viewer


The "OLE/COM Object Viewer" is a very handy tool to get a peek on all COM objects currently installed on your system. It is part of the Windows 2000 resource kit andcan be downloaded for freefrom: http://www.microsoft.com/downloads/details.aspx?familyid=5233b70d-d9b2-4cb5-aeb645664be858b6&displaylang=en The setup of this program isa bit awkward.It will not create any start menu icon for you. Instead, a file called oleview.exe will be installed in the C:\Program Files\Resource Kit directory (default install). When running oleview.exe, some systems will complain about a missing file called iviewers.dll. This file is required, but strangely enough not included in the latest setup.You can obtain this dll from an older version of oleview.exe at: http://download.microsoft.com/download/2/f/1/2f15a59b-6cd7-467b-8ff2f162c 3932235/ovi386.exe. It will install the files by default to the C:\MSTOOLS\BIN directory.You only need the file iviewer.dll. Copy it to the same directory where oleview.exe resides,then register the dll using the c ommand line: regsvr32 iviewers.dll. Let's do an example with the Oleviewer. Run it and follow this tree: Object Classes->Grouped by Component Category->Control->Microsoft Web Browser.

In the left column you see all COM Interfaces that have been defined for this object.We talk about those later. Take a closer look at the right column. It contains a lot ofinformation to use this object in an AutoIt script.Most important is the "VersionIndependentProgID". This is the name to be used in an ObjCreate, ObjGet or ObjEventfunction. Furthermore it contains the directory and filename that contains the object. This can be an EXE, a DLL or an OCX file. InProcServer32 means that the object runs in the same thread as your script (in-process). When you see LocalServer32, the object runs as a separate process. The object must also contain a type library (the lines following "TypeLib="), otherwise it can't be used in an AutoIt script. The interfaces in the left column are used for several ways of interacting with the object. Some are used for storage (IStorage, IPersist), others for embedding in a GUI (IOleObject, IOleControl). AutoIt usesthe IDispatch interface for automation. This interface 'exposes' all scriptable methods and propertiesthat the object supports. If it does not exist, you can't use the object in an AutoIt script. Let's take a look at this interface. Right-click on the name IDispatch and choose "View..." from the context menu. Then click the "View TypeInfo..." button. (Note: if this button is grayed out, you did not have registered the iviewers.dll file, or the object does not have a type library)

The "ITypeInfo Viewer" window does only show the information that is provided with the object. If the developer decides not to include a help file, you will only see the names of the method/properties and nothing else. The "Microsoft Web Browser"type libraryis however quite extensive. Just click an item in the left column, and a description will be shown at the right. Sometimes you have to browse through "Inherited Interfaces" to retrieve more methods for the object. The syntax of the described methods/properties are in C/C++ style.A propertydescribed as"HRESULT Resizable([in] VARIANT_BOOL pbOffline)", has to be rewritten inAutoIt like: $Resizable=$Object.Resizable ($Object holds the object createdwith ObjCreate or ObjGet).

COMmonly mixed up terms

These terms are commonly mixed up with COM, but have a different meaning: OOP = Object Oriented Programming. A programming technique in which software components are put together from reusable building blocks known as Objects. DDE = Dynamic Data Exc hange. You can say this is the predecessor of COM. It used IPC to transfer information and commands between different applications. OLE =Objec t Linking and Embedding In his first version, OLE was an extended version of DDE to 'embed' data from one program into another. The current generation of OLE is built on top of COM and is part of ActiveX. Automation = This is a way of manipulating another application's objects. It is used in OLE, ActiveX and COM. ActiveX = The next generation OLE with Automation, at first mainly developed to interface between applications over a network (especially web browsers). ActiveX is built on top of COM. DCOM=Distributed COM. A slight modification to COM, making it able to communicate between different physical computers. .NET (dot Net)= This is not really a piece of software, but an 'idea' from Microsoft to interconnect just about "everything" through (their) software."dot Net"is used mainly for Web-based services. COMmunist = This is not a supporter of COM, but someone who believes in communism (a theory that the common people should own all the property).

Keyword Reference
Below is a complete list of the keywords available in AutoIt. Click on a keyword name for a detailed description. Keyword False / True #c omments-start ContinueCase ContinueLoop Default Dim / Global / Loc al / Const Do...Until Enum Exit ExitLoop For...To...Step...Next For...In...Next Func...Return...EndFunc If...Then If...ElseIf...Else...EndIf #inc lude-once #inc lude #NoAutoIt3Execute #NoTrayIcon #OnAutoItStartRegister ReDim #RequireAdmin Select...Case...EndSelect Static While...WEnd With...EndWith Description Boolean values for use in logical expressions. Specify that an entire section of script should be commented out. Abort the current case and continue a case into the next case in a Select or Switch block. Continue a While/Do/For loop. Keyword value use in function call. Declare a variable, a constant, or create an array. Loop based on an expression. Enumerates constants. Terminates the script. Terminate a While/Do/For loop. Loop based on an expression. Enumerates elements in an Object collection or an array Defines a user-defined function that takes zero or more arguments and optionally returns a result. Conditionally run a single statement. Conditionally run statements. Specifies that the current file may only be included once. Includes a file in the current script. Specifies that the current compiled script cannot run with /AutoIt3ExecuteLine or /AutoIt3ExecuteScript switch. Indicates that the AutoIt tray icon will not be shown when the script starts. Registers a function to be called when AutoIt starts. Resize an existing array Specifies that the current script requires full administrator rights to run. Conditionally run statements. Declare a static variable or create a static array. Loop based on an expression. Used to reduce long references to object type variables

Switch...Case...EndSwitch Conditionally run statements.

Keyword Reference

#comments-start
Specify that an entire section of script should be commented out. #comments-start ... ... #comments-end Parameters None. Remarks 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! Related Example

#comments-start MsgBox(4096, "", "This won't be executed") MsgBox(4096, "", "Or this") #comments-end ;;; #cs MsgBox(4096, "", "This will print if '#cs' is commented out.") #ce

Keyword Reference

#include
Includes a file in the current script. #include "[path\]filename" #include <filename> Parameters The filename of the current script to include. Path is optional. This must be a string--it cannot be a variable. If "..." is used, the filename is taken to be relative to the current script. If <...> is used the filename is taken to be relative to include library directory (usually C:\Program Files\AutoIt3\Include). The include library contains many pre-written userfunctions for you to use!

filename

Remarks In an AutoIt script, other scripts can be included using the #include" command. If you include the same file containing a user-function more than once you will get a "Duplicate function" error. When writing an include file that may be used in this way, make sure that the top line contains #include-once to prevent that file from being included more than once. There is a special registry value that can be created at "HKEY_CURRENT_USER\Software\AutoIt v3\AutoIt" called "Include". It should be a REG_SZ (string) value. The contents of this value are a semi-colon delimited list of directories that should be searched for files when resolving #include's in addition to the standard locations. The search order used by AutoIt depends on which form of #include you use. The tables below show the order directories are searched using both forms. Using #inc lude <> Standard library The path of the currently running interpreter with "\Include" appended is searched. User-defined libraries The registry value mentioned above is read and each directory is searched in the order they appear in.

Script directory The directory of the currently executing script. Using #include "" (This is the reverse of #include <>). Script directory The directory of the currently executing script. User-defined libraries The registry value mentioned above is read and each directory is searched in the reverse order they appear in.

Standard library The path of the currently running interpreter with "\Include" appended is searched. A note about using the /AutoIt3ExecuteScript option. Since the standard library is searched for in the current interpreter's directory, the standard library functions will not be found; that library will only be found when run through AutoIt3.exe. It's recommended that you compile a script to the .a3x format before attempting to run it with /AutoIt3ExecuteScript. Aut2Exe uses the same algorithm as AutoIt3.exe with the only difference being it looks for the Include subdirectory as being in a sibling directory to itself (..\Include). If Opt("TrayIconDebug",1) only 64 include files name can be displayed in the traytooltip. for the other no filename will be displayed. Related #inc lude-once

Example

;;; TIME.AU3 ;;; MsgBox(0,"", "The time is " & @HOUR & ":" & @MIN & ":" & @SEC) ;;; SCRIPT.AU3 ;;; #include "TIME.AU3" MsgBox(0,"", "Example") #include "TIME.AU3" Exit ; Running script.au3 will output three message boxes: ; one with the time, one with 'Example', and another with the time.

Keyword Reference

#include-once
Specifies that the current file may only be included once. #include-once Parameters None. Remarks If you include the same file containing a user-function more than once, you will get a "Duplicate function" error. When writing an include file that may be used in this way, make sure that the top line contains #include-once to prevent that file from being included more than once. Related #inc lude Example

;;; LIBRARY.AU3 ;;; #include-once Func myFunc() MsgBox(0,"", "Hello from library.au3") EndFunc

;;; SCRIPT.AU3 ;;; #include "Library.au3" #include "Library.au3" ;throws an error if #include-once was not used MsgBox(0, "Example", "This is from 'script.au3' file") myFunc() Exit ; Running script.au3 will output the two message boxes: ; one saying "This is from 'script.au3' file" ; and another saying "Hello from library.au3"

Keyword Reference

#NoTrayIcon
Indicates that the AutoIt tray icon will not be shown when the script starts. #NoTrayIcon Parameters None. Remarks It is possible to use Opt("TrayIconHide", 1) to remove the AutoIt tray icon but it will still be visible for a second when the script starts. Placing the #NoTrayIcon directive at the top of your script will stop the icon from being shown at startup. You may still turn the icon back on later in the script using Opt("TrayIconHide", 0) Related TrayIconHide (Option) Example

#NoTrayIcon MsgBox(4096,"Click OK","Show the tray icon for 5 seconds...") Opt("TrayIconHide", 0) ;un-hide the icon Sleep(5000)

Keyword Reference

#OnAutoItStartRegister
Registers a function to be called when AutoIt starts. #OnAutoItStartRegister "function" Parameters function Remarks Related Example The name of the user function to call.

#OnAutoItStartRegister "MyTestFunc" #OnAutoItStartRegister "MyTestFunc2" Sleep(1000) Func MyTestFunc() MsgBox(64, "Start Results 2", 'Start Message from MyTestFunc()') EndFunc Func MyTestFunc2() MsgBox(64, "Start Results 3", 'Start Message from MyTestFunc()') EndFunc

Keyword Reference

#NoAutoIt3Execute
Specifies that the current compiled script cannot run with /AutoIt3ExecuteLine or /AutoIt3ExecuteScript switch. #NoAutoIt3Execute Parameters None. Remarks Launching a compiled script is terminated with exit code = -1 if /AutoIt3ExecuteLine or /AutoIt3ExecuteScript are used. Related None.

Keyword Reference

#RequireAdmin
Specifies that the current script requires full administrator rights to run. #RequireAdmin Parameters None. Remarks This function was primarily aimed at allowing AutoIt scripts to work correctly with Windows Vista User Account Control (UAC) (However, will also work on Windows 2000 and Windows XP). For more details see AutoIt on Windows Vista. As this function launch a new process, some functions as Consolewrite() cannot be captured (Scite will not display anything). Related IsAdmin Example

#RequireAdmin MsgBox(4096,"Info","Now running with admin rights")

Keyword Reference

Func...Return...EndFunc
Defines a user-defined function that takes zero or more arguments and optionally returns a result. Func functioname ( [Const] [ByRef] $param1, ..., [Const] [ByRef] $paramN, $optionalpar1 = value, ...) ... [Return [value]] EndFunc Parameters The parameters are set by you. You later call the function like any other built-in function. Remarks The Const keyword is optional and indicates that the value of the parameter will not change during the execution of the function. A variable declared Const can only be passed to a function using a Const parameter. The ByRef keyword indicates the parameter should be treated as a reference to the original object. The default behavior copies the parameter into a new variable however ByRef links the new variable to the original parameter. ByRef is typically preferred when a function expects large amounts of data, such as a large array, where copying all the data would impose a significant performance penalty. Note that not only a named variable can be passed for a ByRef parameter; unnamed temporary variables, such as function return values, may be passed as ByRef parameters as well. A literal can not be passed to a ByRef parameter. If using both keywords ByRef and Const with a function parameter, the order of the keywords is not important, so long as they are both in front of the variable they modify. Entire arrays can be passed to functions (and returned from them) by simply using the array name without any brackets. Arrays should be passed to user-defined functions using the ByRef keyword to avoid the overhead of copying all the data in the array. Optional parameters are defined by assigning a default value to them. The value may be a global variable, macro or literal value. Optional parameters always appear last in the function definition. All parameters added after the first optional parameter must also be optional. Inside the function, the number of parameters given when the function was called can be retrieved with the @NUMPARAMS macro (see example 2). Use the Return keyword to exit the function. Unlike built-in functions, user-defined functions return 0 unless another return value is specified. Note that function declarations cannot appear inside other function declarations. Related Dim/Global/Loc al, #inc lude, Const Example

Opt('MustDeclareVars', 1) Example1() Example2() ; example1 Func Example1() ; Sample script with three user-defined functions ; Notice the use of variables, ByRef, and Return

Local $foo = 2 Local $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)) EndFunc ;==>Example1 Func swap(ByRef $a, ByRef $b) ;swap the contents of two variables Local $t $t = $a $a = $b $b = $t EndFunc 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 ;End of sample script 1 ; example2 Func Example2() ; Sample scriptusing @NumParams macro Test_Numparams(1,2,3,4,5,6,7,8,9,10,11,12,13,14) EndFunc ;==>Example2 Func Test_Numparams($v1 = 0, $v2 = 0, $v3 = 0, $v4 = 0, $v5 = 0, $v6 = 0, $v7 = 0, $v8 = 0, $v9 = 0, _ $v10 = 0, $v11 = 0, $v12 = 0, $v13 = 0, $v14 = 0, $v15 = 0, $v16 = 0, $v17 = 0, $v18 = 0, $v19 = 0) Local $val For $i = 1 To @NumParams $val &= Eval("v" & $i) & " " Next MsgBox(0, "@NumParams example", "@NumParams =" & @NumParams & @CRLF & @CRLF & $val) EndFunc ;End of sample script 2

Keyword Reference

Dim / Global / Local / Const


Declare a variable, a constant, or create an array. Dim [Const] $variable [ = initializer ] Dim [Const] $array[subscript 1]...[subscript n] [ = initializer ] Parameters const $variable initializer subscript Remarks The Dim/Loc al/Global keywords perform similar func tions: 1. Declare a variable before you use it (similar to VBScript) 2. Create an array Note: In AutoIt you can create a variable simply by assigning a value ($myvar = 0) but many people like to explicitly declare them. If AutoItSetOption("MustDeclareVars", 1) is active, then variables must be declared prior to use. You can also declare multiple variables on a single line: Dim $a, $b, $c And initialize the variables: Dim $a = 2, $b = 10, $c = 20 [optional] If present, the Const keyword creates a constant rather than a variable. The name of the variable/constant to declare. The value that will be initially assigned to the variable. A Const must include the initializer. The initializer can be a function call. The number of elements to create for the array dimension, indexed 0 to n-1.

Creating constants can be done in a similar way: Const $a = 2, $b = 10, $c = 20 Dim Const $d = 21, $e = Exp(1) Local Const $f = 5, $g = 7, $h = -2 Once created, you cannot change the value of a constant. Also, you cannot change an existing variable into a constant.

To initialize an array, specify the values for each element inside square brackets, separated by commas. For multiple dimensions, nest the initializers. You can specify fewer elements in the initializer than declared, but not more. Function calls can also be placed in the initializers of an array. If the function call returns an array, then the one array element will contain that returned array. Dim $Array1[12]=[3, 7.5, "string"], $array[5] = [8, 4, 5, 9, 1] Dim $Grid[2][4]=[["Paul", "Jim", "Richard", "Louis"], [485.44, 160.68, 275.16, 320.00]] Dim $Test[5] = [3, 1, StringSplit("Abe|Jack|Bobby|Marty", "|"), Cos(0)]

The difference between Dim, Local and Global is the scope in which they are created: Dim = Local scope if the variable name doesn't already exist globally (in which case it reuses the global variable!) Global = Forces creation of the variable in the Global scope Local = Forces creation of the variable in the Local/Function scope

You should use Local or Global, instead of Dim, to explicitly state which scope is desired for a variable/constant/array. When using variables, the local scope is checked first and then the global scope second. When creating arrays you are limited to up to 64 dimensions and/or a total of 16 million elements. A unique feature in AutoIt is the ability to copy arrays like this: $myc opy = $myarray In this case $mycopy will be an exact copy of $myarray and will have the same dimensions - no Dim statement is required to size the array first. If AutoItSetOption("MustDeclareVars", 1) is active then the variable $mycopy would still need to be declared first, but would not need to be sized. If the variable $mycopy was already an array or single value it will be erased before the copy takes place. To erase an array (maybe because it is a large global array and you want to free the memory), simply assign a single value to it: $array = 0 This will free the array and convert it back to the single value of 0. Declaring the same variable name again will erase all array values and reset the dimensions to the new definition. Declaring a variable with a simple value in the same scope will not change the value in the variable. If you declare a variable with the same name as a parameter, using Local inside a user function, an error will occur. Global can be used to assign to global variables inside a function, but if a local variable (or parameter) has the same name as a global variable, the local variable will be the only one used. It is recommended that local and global variables have distinct names. Related UBound, ReDim, Static, AutoItSetOption Example

; Example 1 - Declaring variables Dim $x, $y = 23, $z Global $_PI = 3.14159, $RADIUS Local $_daysWorking = 5 ; Example 2 - Declaring arrays Dim $weeklyWorkSchedule[$_daysWorking] Global $chessBoard[8][8] Local $mouseCoordinates[2], $windowStats[4] ; Example 3 - Declaring constant variables Const $x1 = 11, $y1 = 23, $z1 = 55 Global Const $PI = 3.14159, $E = 2.71828 Local Const $daysWorking = 5

Keyword Reference

ContinueCase
Abort the current case and continue a case into the next case in a Select or Switch block. ContinueCase Parameters None. Remarks Normally in a Select or Switch block, a case ends when the next Case statement is encountered. Executing the ContinueCase will tell AutoIt to stop executing the current case and start executing the next case. Trying to execute ContinueCase outside of a Select or Switch will cause a fatal error. Related Select...EndSelect, Switch...EndSwitch Example $msg = "" $szName = InputBox(Default, "Please enter a word.", "", " M", Default, Default, Default, Default, 10) Switch @error Case 2 $msg = "Timeout " ContinueCase Case 1; Continuing previous case $msg &= "Cancellation" Case 0 Switch $szName Case "a", "e", "i", "o", "u" $msg = "Vowel" Case "QP" $msg = "Mathematics" Case "Q" to "QZ" $msg = "Science" Case Else $msg = "Others" EndSwitch Case Else $msg = "Something went horribly wrong." EndSwitch MsgBox(0, Default, $msg)

Keyword Reference

ContinueLoop
Continue a While/Do/For loop. ContinueLoop [level] Parameters level Remarks ContinueLoop will continue execution of the loop at the expression testing statement (that is the While, Until or Next statement). A negative level or zero value has no effect. Even though any program that uses ContinueLoop can be rewritten using If-ElseIf-EndIf statements, ContinueLoop can make long scripts easier to understand. Be careful with While/Do loops; you can create infinite loops by using ContinueLoop incorrectly. Related ExitLoop, For, While, Do Example [optional] The level of the loop to restart. The default is 1 (meaning the current loop).

;Print all numbers from 1 to 10 except number 7 For $i = 1 to 10 If $i = 7 Then ContinueLoop MsgBox(0, "The value of $i is:", $i) Next ;Example of using level is needed.

Keyword Reference

Default
Keyword value use in function call. $var = Default Parameters None. Remarks This keyword should not be used in a general computation expression. AutoIt will not detect such situations because it has too much of a performance penalty. When used in parameter passing, the behavior is specified in the corresponding AutoIt function documentation. For UDF's, it is the scripter's responsiblity to check if the parameter has been set to Default and to perform the desired behavior in this situation. If used, the passed parameter will be set to the Default keyword and not to an optional parameter value, if defined. Related IsKeyWord Example

WinMove("[active]","",default, default, 200,300) ; just resize the active window (no move) MyFunc2(Default,Default) Func MyFunc2($Param1 = Default, $Param2 = 'Two', $Param3 = Default) If $Param1 = Default Then $Param1 = 'One' If $Param3 = Default Then $Param3 = 'Three' MsgBox(0, 'Params', '1 = ' & $Param1 & @LF & _ '2 = ' & $Param2 & @LF & _ '3 = ' & $Param3) EndFunc

Keyword Reference

Do...Until
Loop based on an expression. Do statements ... Until <expression> Parameters expression Remarks 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. Related ContinueLoop, ExitLoop Example $i = 0 Do MsgBox(0, "Value of $i is:", $i) $i = $i + 1 Until $i = 10 The statements in between Do and Until are executed until the expression is true.

Keyword Reference

Enum
Enumerates constants. [scope] Enum [Step <stepval>] <constantlist> Parameters scope stepval constantlist Remarks By default, the first constant will be 0 and the rest will be incremented by 1 from there. When using the multiply operator to step, the first constant will be assigned 1 and the rest will be multiplied based on the previous constant value. Constants can be explicitly assigned by any valid statement. Related Example Global Enum $E1VAR1, $E1VAR2, MsgBox(4096, "", "Expect 0: " MsgBox(4096, "", "Expect 1: " MsgBox(4096, "", "Expect 2: " $E1VAR3 & $E1VAR1) & $E1VAR2) & $E1VAR3) [optional] The scope the Enum should be placed in, either Local, Global, Dim or none. If none, Dim behavior is used. [optional] The default step is to add 1. Other possible step methods are: *n, +n, -n where n is a whole number. A list constants to be enumerated.

Global Enum $E2VAR1 = 10, $E2VAR2, $E2VAR3 = 15 MsgBox(4096, "", "Expect 10: " & $E2VAR1) MsgBox(4096, "", "Expect 11: " & $E2VAR2) MsgBox(4096, "", "Expect 15: " & $E2VAR3) Global Enum Step MsgBox(4096, "", MsgBox(4096, "", MsgBox(4096, "", *2 $E3VAR1, $E3VAR2, $E3VAR3 "Expect 1: " & $E3VAR1) "Expect 2: " & $E3VAR2) "Expect 4: " & $E3VAR3)

Keyword Reference

Exit
Terminates the script. Exit [return code] Parameters [optional] Integer that sets the script's return code. This code can be used by Windows or the DOS variable %ERRORLEVEL%. The default is 0. Scripts normally set an errorlevel of 0 if the script executed properly; error levels 1 and above typically indicate that the script did not execute properly.

return code

Remarks The parameter, if included, can be enclosed in parentheses. Thus, the following are equivalent: Exit, Exit 0, and Exit(0). However, Exit() is invalid. The code can be retrieved in an OnAutoItExitRegister function by @EXITCODE. Related ExitLoop, OnAutoItExitRegister Example

;First Example Exit ;Second Example ; Terminate script if no command-line arguments If $CmdLine[0] = 0 Then Exit(1) ;Third Example ; Open file specified as first command-line argument $file = FileOpen($CmdLine[1], 0) ; Check if file opened for reading OK If $file = -1 Then Exit(2) ; If file is empty then exit (script is successful) $line = FileReadLine($file) If @error = -1 Then Exit ;code to process file goes here FileClose($file) Exit ;is optional if last line of script

Keyword Reference

ExitLoop
Terminate a While/Do/For loop. ExitLoop [level] Parameters level Remarks A negative level or zero value has no effect. ExitLoop will break out of a While, Do or For loop. ExitLoop is useful when you would otherwise need to perform error checking in both the loop-test and the loopbody. Related ContinueLoop, Exit, For, Do, While Example $sum = 0 While 1 ;use infinite loop since ExitLoop will get called $ans = InputBox("Running total=" & $sum, _ " Enter a positive number. (A negative number exits)") If $ans < 0 Then ExitLoop $sum = $sum + $ans WEnd MsgBox(0,"The sum was", $sum) [optional] The number of loop levels to exit from. The default is 1 (meaning the current loop).

Keyword Reference

False / True
Boolean values for use in logical expressions. $var = False $var = True Parameters None. Remarks These keywords should not be used in expressions as AutoIt will not detect this 'misuse' and the results will be unpredictable. Related Example $bool= False if NOT $bool = true Then Msgbox(0,"Bool comparison", "OK")

Keyword Reference

For...To...Step...Next
Loop based on an expression. For <variable> = <start> To <stop> [Step <stepval>] statements ... Next Parameters variable start stop stepval Remarks The Variable will be created automatically with a LOCAL scope, even when MustDeclareVars is on. 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 Related ContinueLoop, ExitLoop Example For $i = 5 to 1 Step -1 MsgBox(0, "Count down!", $i) Next MsgBox(0,"", "Blast Off!") The variable used for the count. The initial numeric value of the variable. The final numeric value of the variable. [optional] The numeric value (possibly fractional) that the count is increased by each loop. Default is 1.

Keyword Reference

For...In...Next
Enumerates elements in an Object collection or an array For <$Variable> In <expression> statements ... Next Parameters Variable expression Remarks The Variable will be created automatically with a LOCAL scope, even when MustDeclareVars is on. If the expression is an Object collection with no elements, or an multi-dimensional array, the loop will be skipped and the Variable will contain an empty string. If the expression is not an Object nor an Array, the script stops with an error, unless a COM Error handler had been configured. Autoit Array's are read-only when using For...In. While you can assign the variable inside the For...In loop a value, this change is not reflected in the array itself. To modify the contents of an array during enumeration, use a For...To loop. For...In...Next statements may be nested. Related With...EndWith Example A variable to which an element is being assigned Must be an expression resulting in an Object, or an Array with at least one element

;Using an Array Dim $aArray[4] $aArray[0]="a" $aArray[1]=0 $aArray[2]=1.3434 $aArray[3]="test" $string = "" FOR $element IN $aArray $string = $string & $element & @CRLF NEXT Msgbox(0,"For..IN Arraytest","Result is: " & @CRLF & $string) ;Using an Object Collection $oShell = ObjCreate("shell.application") $oShellWindows=$oShell.windows if Isobj($oShellWindows) then $string="" for $Window in $oShellWindows $String = $String & $Window.LocationName & @CRLF

next msgbox(0,"","You have the following windows open:" & @CRLF & $String) else msgbox(0,"","you have no open shell windows.") endif

Keyword Reference

If...Then
Conditionally run a single statement. If <expression> Then statement Parameters expression Remarks This version of the If statement is used to execute a single statement without the overhead of an EndIf. The expression can contain the boolean operators of AND, OR, and NOT as well as the logical operators <, <=, >, >=, =, ==, and <> grouped with parentheses as needed. Related If...Else...EndIf, Select...Case...EndSelect, Switch...EndSwitch Example If the expression is true, the statement is executed.

;Terminates script if no command-line arguments If $CmdLine[0] = 0 Then Exit ;Alternative: If $CmdLine[0] = 0 Then Exit EndIf

Keyword Reference

If...ElseIf...Else...EndIf
Conditionally run statements. If <expression> Then statements ... [ElseIf expression-n Then [elseif statements ... ]] ... [Else [else statements] ... EndIf Parameters expression Remarks If statements may be nested. The expression can contain the boolean operators of AND, OR, and NOT as well as the logical operators <, <=, >, >=, =, ==, and <> grouped with parentheses as needed. Related If...Then, Select...Case...EndSelect, Switch...EndSwitch Example If $var > 0 Then MsgBox(4096,"", "Value is positive.") ElseIf $var < 0 Then MsgBox(4096,"", "Value is negative.") Else If StringIsXDigit ($var) Then MsgBox(4096,"", "Value might be hexadecimal!") Else MsgBox(4096,"", "Value is either a string or is zero.") EndIf 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.

Keyword Reference

ReDim
Resize an existing array ReDim $array[subscript 1]...[subscript n] Parameters $array subscript Remarks The ReDim keyword is similar to Dim, except that ReDim preserves the values in the array instead of removing the values while resizing an array. The number of dimensions must remain the same, or the old array will be forgotten during the ReDim. The array will retain the scope (Global or Local) that it had prior to resizing. Related Dim, UBound Example The name of the array to resize. The number of elements to create for the array dimension, indexed 0 to n-1.

; Example Resizing an array Dim $I, $K, $T, $MSG Dim $X[4][6], $Y[4][6] For $I = 0 To 3 For $K = 0 To 5 $T = Int(Random(20) + 1) ;Get random numbers between 1 and 20 $X[$I][$K] = $T $Y[$I][$K] = $T Next Next ReDim $X[3][8] Dim $Y[3][8] $MSG = "" For $I = 0 To UBound($X, 1) - 1 For $K = 0 To UBound($X, 2) - 1 If $K > 0 Then $MSG = $MSG & ", " $MSG = $MSG & $X[$I][$K] Next $MSG = $MSG & @CR Next MsgBox(0, "ReDim Demo", $MSG) $MSG = "" For $I = 0 To UBound($Y, 1) - 1 For $K = 0 To UBound($Y, 2) - 1 If $K > 0 Then $MSG = $MSG & ", " $MSG = $MSG & $Y[$I][$K] Next $MSG = $MSG & @CR Next MsgBox(0, "ReDim Demo", $MSG)

Keyword Reference

Select...Case...EndSelect
Conditionally run statements. Select Case <expression> statement1 ... [Case statement2 ...] [Case Else statementN ...] EndSelect Parameters Case <expression> Remarks Select statements may be nested. The expression can contain the boolean operators of AND, OR, and NOT as well as the logical operators <, <=, >, >=, =, ==, and <> grouped with parentheses as needed. Related If...Then, If...Else...EndIf, Switch...EndSwitch, ContinueCase Example $var = 0 $var2= "" Select Case $var = 1 MsgBox(0, "", "First Case expression was true") Case $var2 = "test" MsgBox(0, "", "Second Case expression was true") Case Else MsgBox(0, "", "No preceding case was true!") 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.

Warning: This feature is experimental. It may not work, may contain bugs or may be changed or removed without notice. DO NOT REPORT BUGS OR REQUEST NEW FEATURES FOR THIS FEATURE. USE AT YOUR OWN RISK.
Keyword Reference

Static
Declare a static variable or create a static array. Static [Scope] $variable [ = initializer ] Static [Scope] $array[subscript 1]...[subscript n] [ = initializer ] Parameters Scope $variable initializer subscript Remarks The Static keyword can appear on the line before the optional scope specifier, or after. e.g. Local Static or Static Local are both acceptable. If the scope modifier Local is used, then the static variable is visible and usable only in the function in which it is declared. If the scope modifier Global is used, then the static variable is visible and usable in all parts of the script; in this regard, a Global Static has very little difference from a Global variable. If the scope modifier is not used, then the static variable will be created in the local scope; in this way, Static is similar to Dim. The difference between Local and Static is variable lifetime. Local variables are only stored while the function is called and are visible only within the function in which they are declared; when the function returns, all its local variables are released. Static variables are likewise visible only in the function in which they are declared, but they continue to exist, retaining their last value, after the function finishes execution. When looking for variables, the local scope is checked first and then the global scope second. The Static keyword performs similar functions to the Global/Local/Dim keywords. 1. They all declare a variable before you use it. 2. They all can create an array. An optional modifier, Local or Global that indicates where the variable is visible. The name of the static variable to declare. The value that will be initially assigned to the variable. The initializer can be a function call of involve mathematical or string operations. This initializer is only evaluated the first time this variable declaration is encountered. The number of elements to create for the array dimension, indexed 0 to n-1.

Note: Static variables must be declared using the Static keyword prior to use, no matter how AutoItSetOption ("MustDeclareVars") is set. Static variables can not be Const. You can also declare multiple static variables on a single line:

Static $a, $b, $c And initialize the variables: Static $a = 2, $b = 10, $c = 20

When initializing a static variable, the initialization value is evaluated and assigned only the first time, when the variable is created. On all subsequent passes, the initializer is ignored. See Local for more information about using arrays, which has all the same functionality as in Local, except for: 1. Reinitalizing a Static variable has no effect. 2. Changing the size of a Static array is treated like a ReDim. 3. You can not change a static variable to a local or global variable nor vice-versa.

If you want to resize an array, always use Static to do so, not Redim. Related Local, UBound, ReDim, AutoItSetOption Example

; Static variables examples. Opt("MustDeclareVars", 1) Func Test1() Static $STbFirstPass = 1 If $STbFirstPass Then $STbFirstPass = 0 ; Perform tasks for the first time through EndIf ; Other things the function should do EndFunc ;==>Test1 Func Accumulate($State) Static $Values[9] Local $I If IsNumber($State) Then Switch $State Case -1 ; Reset For $I = 0 To 8 $Values[$I] = 0 Next Return True Case -2 Return $Values Case 0 To UBound($Values) - 1 $Values[$State] += 1 Return $Values[$State] Case Else If $State < 0 Then SetError(1, 0) Return False Else Static $Values[$State + 1] ; Resize the array to accomodate the new value $Values[$State] = 1

Return 1 EndIf EndSwitch Else SetError(2, 0) EndIf EndFunc ;==>Accumulate Global $I Test1() For $I = 1 To 99 Accumulate(Random(0, 20, 1)) Next For $I In Accumulate(-2) ConsoleWrite($I & ", ") Next ConsoleWrite("\n"); Test1()

Keyword Reference

Switch...Case...EndSwitch
Conditionally run statements. Switch <expression> Case <value> [To <value>] [,<value> [To <value>] ...] statement1 ... [Case <value> [To <value>] [,<value> [To <value>] ...] statement2 ...] [Case Else statementN ...] EndSwitch Parameters <expression> <value> To <value> <value> Remarks If no cases match the Switch value, then the Case Else section, if present, is executed. If no cases match and Case Else is not defined, then none of the code inside the Switch structure, other than the condition, will be executed. Switch statements may be nested. Related If...Then, If...Else...EndIf, Select...EndSelect, ContinueCase Example Switch @HOUR Case 6 To 11 $msg = "Good Morning" Case 12 To 17 $msg = "Good Afternoon" Case 18 To 21 $msg = "Good Evening" Case Else $msg = "What are you still doing up?" EndSwitch MsgBox(0, Default, $msg) An expression that returns a value. The value from the expression is then compared against the values of each case until a match is found. This expression is always evaluted exactly once each time through the structure. The case is executed if the expression is between the two values. The case is executed if the expression matches the value.

Keyword Reference

With...EndWith
Used to reduce long references to object type variables With <expression> statements ... EndWith Parameters expression Remarks With...EndWith statements may NOT be nested. Related For...In...Next Example Must be an object type expression

$oExcel = ObjCreate("Excel.Application") $oExcel.visible =1 $oExcel.workbooks.add With $oExcel.activesheet .cells(2,2).value = 1 .range("A1:B2").clear EndWith $oExcel.quit

Keyword Reference

While...WEnd
Loop based on an expression. While <expression> statements ... WEnd Parameters expression Remarks 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. Related ContinueLoop, ExitLoop Example $i = 0 While $i <= 10 MsgBox(0, "Value of $i is:", $i) $i = $i + 1 WEnd If the expression is true the following statements up to the WEnd statement are executed. This loop continues until the expression is false.

Macro Reference
Below is an alphabetized list of all the macros available in AutoIt. Macro @AppDataCommonDir @AppDataDir @AutoItExe @AutoItPID @AutoItVersion @AutoItX64 @COM_EventObj @CommonFilesDir @Compiled @ComputerName @ComSpec @CPUArch @CR @CRLF @DesktopCommonDir @DesktopDir @DesktopHeight @DesktopWidth @DesktopDepth @DesktopRefresh @DocumentsCommonDir @error @exitCode @exitMethod @extended @FavoritesCommonDir @FavoritesDir @GUI_CtrlId @GUI_CtrlHandle @GUI_DragId @GUI_DragFile @GUI_DropId @GUI_WinHandle @HomeDrive @HomePath Description path to Application Data path to current user's Application Data The full path and filename of the AutoIt executable currently running. For compiled scripts it is the path of the compiled script. PID of the process running the script. Version number of AutoIt such as 3.0.81.0 Returns 1 if the script is running under the native x64 version of AutoIt. Object the COM event is being fired on. Only valid in a COM event Function. path to Common Files folder Returns 1 if script is a compiled executable; otherwise, returns 0. Computer's network name. value of %comspec%, the SPECified secondary COMmand interpreter; primarily for c ommand line uses, e.g. Run(@ComSpec & " /k help | more") Returns "X86" when the CPU is a 32-bit CPU and "X64" when the CPU is 64-bit. Carriage return, Chr(13); sometimes used for line breaks. = @CR & @LF ;occasionally used for line breaks. path to Desktop path to current user's Desktop Height of the desktop screen in pixels. (vertical resolution) Width of the desktop screen in pixels. (horizontal resolution) Depth of the desktop screen in bits per pixel. Refresh rate of the desktop screen in hertz. path to Documents Status of the error flag. See the SetError function. Exit code as set by Exit statement. Exit method. See the Func OnAutoItExitRegister(). Extended function return - used in certain functions such as StringReplace. path to Favorites path to current user's Favorites Last click control identifier. Only valid in an event Function. See the GUICtrlSetOnEvent function. Last click control handle. Only valid in an event Function. See the GUICtrlSetOnEvent function. Drag control identifier. Only valid on Drop Event. See the GUISetOnEvent function. Filename of the file being dropped. Only valid on Drop Event. See the GUISetOnEvent function. Drop control identifier. Only valid on Drop Event. See the GUISetOnEvent function. Last click GUI window handle. Only valid in an event Function. See the GUICtrlSetOnEvent function. Drive letter of drive containing current user's home directory. Directory part of current user's home directory. To get the full path, use in conjunction with @HomeDrive.

@HomeShare @HOUR @HotKeyPressed @IPAddress1 @IPAddress2 @IPAddress3 @IPAddress4 @KBLayout @LF @LogonDNSDomain @LogonDomain @LogonServer @MDAY @MIN @MON @MSEC @MUILang @MyDocumentsDir @NumParams @OSArch @OSBuild @OSLang @OSServicePack @OSType @OSVersion @ProgramFilesDir @ProgramsCommonDir @ProgramsDir @ScriptDir @ScriptFullPath @ScriptLineNumber @ScriptName @SEC @StartMenuCommonDir @StartMenuDir @StartupCommonDir @StartupDir @SW_DISABLE @SW_ENABLE @SW_HIDE @SW_LOCK

Server and share name containing current user's home directory. Hours value of clock in 24-hour format. Range is 00 to 23 Last hotkey pressed. See the HotKeySet function. IP address of first network adapter. Tends to return 127.0.0.1 on some computers. IP address of second network adapter. Returns 0.0.0.0 if not applicable. IP address of third network adapter. Returns 0.0.0.0 if not applicable. IP address of fourth network adapter. Returns 0.0.0.0 if not applicable. Returns code denoting Keyboard Layout. See Appendix for possible values. Line feed, Chr(10); typically used for line breaks. Logon DNS Domain. Logon Domain. Logon server. Current day of month. Range is 01 to 31 Minutes value of clock. Range is 00 to 59 Current month. Range is 01 to 12 Milliseconds value of clock. Range is 00 to 999 Returns code denoting Multi Language if available (Vista is OK by default). See Appendix for possible values. path to My Documents target Number of parameters used to call the user functions Returns one of the following: "X86", "IA64", "X64" - this is the architecture type of the currently running operating system. Returns the OS build number. For example, Windows 2003 Server returns 3790 Returns code denoting OS Language. See Appendix for possible values. Service pack info in the form of "Service Pack 3". Returns "WIN32_NT" for NT/2000/XP/2003/Vista/2008/Win7/2008R2. Returns one of the following: "WIN_2008R2", "WIN_7", "WIN_2008", "WIN_VISTA", "WIN_2003", "WIN_XP", "WIN_XPe", "WIN_2000". path to Program Files folder path to Start Menu's Programs folder path to current user's Programs (folder on Start Menu) Directory containing the running script. (Result does not contain a trailing backslash) Equivalent to @ScriptDir & "\" & @ScriptName Line number of the currently executed script line. Useful for debug statements specially when a function is call you can pass the caller line number. (Not significant in complied script) Long filename of the running script. Seconds value of clock. Range is 00 to 59 path to Start Menu folder path to current user's Start Menu path to Startup folder current user's Startup folder Disables the window. Enables the window. Hides the window and activates another window. Lock the window to avoid repainting.

@SW_MAXIMIZE @SW_MINIMIZE @SW_RESTORE @SW_SHOW @SW_SHOWDEFAULT @SW_SHOWMAXIMIZED @SW_SHOWMINIMIZED @SW_SHOWMINNOACTIVE @SW_SHOWNA @SW_SHOWNOACTIVATE @SW_SHOWNORMAL @SW_UNLOCK @SystemDir @TAB @TempDir @TRAY_ID @TrayIconFlashing @TrayIconVisible @UserProfileDir @UserName @WDAY @WindowsDir @WorkingDir @YDAY @YEAR

Maximizes the specified window. Minimizes the specified window and activates the next top-level window in the Z order. Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when restoring a minimized window. Activates the window and displays it in its current size and position. Sets the show state based on the SW_ value specified by the program that started the application. Activates the window and displays it as a maximized window. Activates the window and displays it as a minimized window. Displays the window as a minimized window. This value is similar to @SW_SHOWMINIMIZED, except the window is not activated. Displays the window in its current size and position. This value is similar to @SW_SHOW, except the window is not activated. Displays a window in its most recent size and position. This value is similar to @SW_SHOWNORMAL, except the window is not activated. Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time. Unlock windows to allow painting. path to Windows' System (or System32) folder Tab character, Chr(9) Path to the temporary files folder. Last clicked item identifier during a TraySet(Item)OnEvent action. Returns 1 if tray icon is flashing; otherwise, returns 0. Returns 1 if tray icon is visible; otherwise, returns 0. Path to current user's Profile folder. ID of the currently logged on user. Numeric day of week. Range is 1 to 7 which corresponds to Sunday through Saturday. path to Windows folder Current/active working directory. (Result does not contain a trailing backslash) Current day of year. Range is 001 to 366 (or 001 to 365 if not a leap year) Current four-digit year

Macro Reference - AutoIt Related


Below is a list of AutoIt-related macros. The full list of macros can be found here. Macro @compiled @error @exitCode @exitMethod @extended @NumParams @ScriptName @ScriptDir @ScriptFullPath @ScriptLineNumber @WorkingDir @AutoItExe @AutoItPID @AutoItVersion @AutoItX64 @COM_EventObj @GUI_CtrlId @GUI_CtrlHandle @GUI_DragID @GUI_DragFile @GUI_DropID @GUI_WinHandle @HotKeyPressed Description Returns 1 if script is a compiled executable; otherwise, returns 0. Status of the error flag. See the SetError function. Exit code as set by Exit statement. See the Func OnAutoItExitRegister(). Extended function return - used in certain functions such as StringReplace. Number of parameters used in calling the user function. Filename of the running script. Directory containing the running script. (Result does not contain a trailing backslash) Equivalent to @ScriptDir & "\" & @ScriptName Line number currently being executed. Useful for debug statements specially when a function is call you can pass the caller line number. (Not significant in compiled script) Current/active working directory. (Result does not contain a trailing backslash) The full path and filename of the AutoIt executable currently running. For compiled scripts it is the path of the compiled script. PID of the process in which the script is running. Version number of AutoIt such as 3.0.102.0 Returns 1 if the script is running under the native x64 version of AutoIt. Object the COM event is being fired on. Only valid in a COM event Function. Last click GUI Control identifier. Only valid in an event Function. See the GUICtrlSetOnEvent function. Last click GUI Control handle. Only valid in an event Function. See the GUICtrlSetOnEvent function. Drag GUI Control identifier. Only valid on Drop Event. See the GUISetOnEvent function. Filename of the file being dropped. Only valid on Drop Event. See the GUISetOnEvent function. Drop GUI Control identifier. Only valid on Drop Event. See the GUISetOnEvent function. Last click GUI Window handle. Only valid in an event Function. See the GUICtrlSetOnEvent function. Last HotKey pressed. See the HotkeySet function

For use with the WinSetState, Run, RunWait, FileCreateShortcut and FileGetShortcut functions: @SW_DISABLE @SW_ENABLE @SW_HIDE @SW_LOCK @SW_MAXIMIZE @SW_MINIMIZE Disables the window. Enables the window. Hides the window and activates another window. Lock window to avoid painting. Maximizes the specified window. Minimizes the specified window and activates the next top-level window in the Z order. Activates and displays the window. If the window is minimized or maximized, the

@SW_RESTORE @SW_SHOW @SW_SHOWDEFAULT @SW_SHOWMAXIMIZED @SW_SHOWMINIMIZED @SW_SHOWMINNOACTIVE @SW_SHOWNA @SW_SHOWNOACTIVATE @SW_SHOWNORMAL @SW_UNLOCK @TRAY_ID @TrayIconFlashing @TrayIconVisible @CR @LF @CRLF @TAB

system restores it to its original size and position. An application should specify this flag when restoring a minimized window. Activates the window and displays it in its current size and position. Sets the show state based on the SW_ value specified by the program that started the application. Activates the window and displays it as a maximized window. Activates the window and displays it as a minimized window. Displays the window as a minimized window. This value is similar to @SW_SHOWMINIMIZED, except the window is not activated. Displays the window in its current size and position. This value is similar to @SW_SHOW, except the window is not activated. Displays a window in its most recent size and position. This value is similar to @SW_SHOWNORMAL, except the window is not activated. Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time. Unlock windows to allow painting. Last clicked item identifier during a TraySet(Item)OnEvent action. Returns 1 if tray icon is flashing; otherwise, returns 0. Returns 1 if tray icon is visible; otherwise, returns 0. Carriage return, Chr(13); sometimes used for line breaks. Line feed, Chr(10); typically used for line breaks. = @CR & @LF ;occasionally used for line breaks. Tab character, Chr(9)

Macro Reference - Directory


Below is a list of Directory macros. Note that paths do not contain a trailing backslash. The full list of macros can be found here. Macro Macros for "All Users" data. @AppDataCommonDir @DesktopCommonDir path to Application Data path to Desktop Description

@DocumentsCommonDir path to Documents @FavoritesCommonDir @ProgramsCommonDir @StartMenuCommonDir @StartupCommonDir path to Favorites path to Start Menu's Programs folder path to Start Menu folder path to Startup folder

Macros for Current User data. @AppDataDir @DesktopDir @MyDocumentsDir @FavoritesDir @ProgramsDir @StartMenuDir @StartupDir @UserProfileDir path to current user's Application Data path to current user's Desktop path to My Documents target path to current user's Favorites path to current user's Programs (folder on Start Menu) path to current user's Start Menu current user's Startup folder Path to current user's Profile folder.

Other macros for the computer system: @HomeDrive @HomePath @HomeShare @LogonDNSDomain @LogonDomain @LogonServer @ProgramFilesDir @CommonFilesDir @WindowsDir @SystemDir @TempDir @ComSpec Drive letter of drive containing current user's home directory. Directory part of current user's home directory. To get the full path, use in conjunction with @HomeDrive. Server and share name containing current user's home directory. Logon DNS Domain. Logon Domain. Logon server. path to Program Files folder path to Common Files folder path to Windows folder path to Windows' System (or System32) folder path to the temporary files folder value of %comspec%, the SPECified secondary COMmand interpreter; primarly for c ommand line uses, e.g. Run(@ComSpec & " /k help | more")

Macro Reference - System Info


Below is a list of System information macros. The full list of macros can be found here. Macro @CPUArch @KBLayout @MUILang @OSArch @OSLang @OSType @OSVersion @OSBuild @OSServicePack @ComputerName @UserName @IPAddress1 @IPAddress2 @IPAddress3 @IPAddress4 @DesktopHeight @DesktopWidth @DesktopDepth @DesktopRefresh Description Returns "X86" when the CPU is a 32-bit CPU and "X64" when the CPU is 64-bit. Returns code denoting Keyboard Layout. See Appendix for possible values. Returns code denoting Multi Language if available (Vista is OK by default). See Appendix for possible values. Returns one of the following: "X86", "IA64", "X64" - this is the architecture type of the currently running operating system. Returns code denoting OS Language. See Appendix for possible values. Returns "WIN32_NT" for NT/2000/XP/2003/Vista/2008/Win7/2008R2. Returns one of the following:"WIN_2008R2", "WIN_7", "WIN_2008", "WIN_VISTA", "WIN_2003", "WIN_XP", "WIN_XPe", "WIN_2000". Returns the OS build number. For example, Windows 2003 Server returns 3790 Service pack info in the form of "Service Pack 3" or, for Windows 95, it may return "B" Computer's network name. ID of the currently logged on user. IP address of first network adapter. Tends to return 127.0.0.1 on some computers. IP address of second network adapter. Returns 0.0.0.0 if not applicable. IP address of third network adapter. Returns 0.0.0.0 if not applicable. IP address of fourth network adapter. Returns 0.0.0.0 if not applicable. Height of the desktop screen in pixels. (vertical resolution) Width of the desktop screen in pixels. (horizontal resolution) Depth of the desktop screen in bits per pixel. Refresh rate of the desktop screen in hertz.

Macro Reference - Time And Date


Below is a list of Time and Date macros. Notice that most return values are two-digits long. The full list of macros can be found here. Macro @MSEC @SEC @MIN @HOUR @MDAY @MON @YEAR @WDAY @YDAY Description Milliseconds value of clock. Range is 00 to 999 Seconds value of clock. Range is 00 to 59 Minutes value of clock. Range is 00 to 59 Hours value of clock in 24-hour format. Range is 00 to 23 Current day of month. Range is 01 to 31 Current month. Range is 01 to 12 Current four-digit year Numeric day of week. Range is 1 to 7 which corresponds to Sunday through Saturday. Current day of year. Range is 001 to 366 (or 001 to 365 if not a leap year)

Function Reference
Below is a complete list of the functions available in AutoIt. Click on a function name for a detailed description. Function Abs ACos AdlibRegister AdlibUnRegister Asc AscW ASin Assign ATan AutoItSetOption AutoItWinGetTitle AutoItWinSetTitle Beep Binary BinaryLen BinaryMid BinaryToString BitAND BitNOT BitOR BitRotate BitShift BitXOR Bloc kInput Break Call CDTray Ceiling Chr ChrW ClipGet ClipPut ConsoleRead ConsoleWrite ConsoleWriteError ControlClic k ControlCommand ControlDisable ControlEnable Description Calculates the absolute value of a number. Calculates the arcCosine of a number. Registers an Adlib function. Unregisters an adlib function. Returns the ASCII code of a character. Returns the unicode code of a character. Calculates the arcsine of a number. Assigns a variable by name with the data. Calculates the arctangent of a number. Changes the operation of various AutoIt functions/parameters. Retrieves the title of the AutoIt window. Changes the title of the AutoIt window. Plays back a beep to the user. Returns the binary representation of an expression. Returns the number of bytes in a binary variant. Extracts a number of bytes from a binary variant. Converts a binary variant into a string. Performs a bitwise AND operation. Performs a bitwise NOT operation. Performs a bitwise OR operation. Performs a bit shifting operation, with rotation. Performs a bit shifting operation. Performs a bitwise exclusive OR (XOR) operation. Disable/enable the mouse and keyboard. Enables or disables the users' ability to exit a script from the tray icon menu. Calls a user-defined function contained in a string parameter. Opens or closes the CD tray. Returns a number rounded up to the next integer. Returns a character corresponding to an ASCII code. Returns a character corresponding to a unicode code. Retrieves text from the clipboard. Writes text to the clipboard. Read from the STDIN stream of the AutoIt script process. Writes data to the STDOUT stream. Some text editors can read this stream as can other programs which may be expecting data on this stream. Writes data to the STDERR stream. Some text editors can read this stream as can other programs which may be expecting data on this stream. Sends a mouse click command to a given control. Sends a command to a control. Disables or "grays-out" a control. Enables a "grayed-out" control.

ControlFocus ControlGetFocus ControlGetHandle ControlGetPos ControlGetText ControlHide ControlListView ControlMove ControlSend ControlSetText ControlShow ControlTreeView Cos Dec DirCopy DirCreate DirGetSize DirMove DirRemove DllCall DllCallbac kFree DllCallbac kGetPtr DllCallbac kRegister DllClose DllOpen DllStructCreate DllStructGetData DllStructGetPtr DllStructGetSize DllStructSetData DriveGetDrive DriveGetFileSystem DriveGetLabel DriveGetSerial DriveGetType DriveMapAdd DriveMapDel DriveMapGet DriveSetLabel DriveSpaceFree DriveSpaceTotal DriveStatus EnvGet EnvSet EnvUpdate

Sets input focus to a given control on a window. Returns the ControlRef# of the control that has keyboard focus within a specified window. Retrieves the internal handle of a control. Retrieves the position and size of a control relative to it's window. Retrieves text from a control. Hides a control. Sends a command to a ListView32 control. Moves a control within a window. Sends a string of characters to a control. Sets text of a control. Shows a control that was hidden. Sends a command to a TreeView32 control. Calculates the cosine of a number. Returns a numeric representation of a hexadecimal string. Copies a directory and all sub-directories and files (Similar to xcopy). Creates a directory/folder. Returns the size in bytes of a given directory. Moves a directory and all sub-directories and files. Deletes a directory/folder. Dynamically calls a function in a DLL. Frees a previously created handle created with DllCallbackRegister. Returns the pointer to a callback function that can be passed to the Win32 API. Creates a user-defined DLL Callback function. Closes a previously opened DLL. Opens a DLL file for use in DllCall. Creates a C/C++ style structure to be used in DllCall. Returns the data of an element of the struct. Returns the pointer to the struct or an element in the struct. Returns the size of the struct in bytes. Sets the data in of an element in the struct. Returns an array containing the enumerated drives. Returns File System Type of a drive. Returns Volume Label of a drive, if it has one. Returns Serial Number of a drive. Returns drive type. Maps a network drive. Disconnects a network drive. Retrieves the details of a mapped drive. Sets the Volume Label of a drive. Returns the free disk space of a path in Megabytes. Returns the total disk space of a path in Megabytes. Returns the status of the drive as a string. Retrieves an environment variable. Writes an environment variable. Refreshes the OS environment.

Eval Execute Exp FileChangeDir FileClose FileCopy FileCreateNTFSLink FileCreateShortcut FileDelete FileExists FileFindFirstFile FileFindNextFile FileFlush FileGetAttrib FileGetEncoding FileGetLongName FileGetPos FileGetShortcut FileGetShortName FileGetSize FileGetTime FileGetVersion FileInstall FileMove FileOpen FileOpenDialog FileRead FileReadLine FileRecycle FileRecycleEmpty FileSaveDialog FileSelectFolder FileSetAttrib FileSetPos FileSetTime FileWrite FileWriteLine Floor FtpSetProxy GUICreate GUICtrlCreateAvi GUICtrlCreateButton GUICtrlCreateChec kbox GUICtrlCreateCombo GUICtrlCreateDate

Return the value of the variable defined by an string. Execute an expression. Calculates e to the power of a number. Changes the current working directory. Closes a previously opened text file. Copies one or more files. Creates an NTFS hardlink to a file or a directory Creates a shortcut (.lnk) to a file. Delete one or more files. Checks if a file or directory exists. Returns a search "handle" according to file search string. Returns a filename according to a previous call to FileFindFirstFile. Flushes the file's buffer to disk. Returns a code string representing a file's attributes. Determines the text encoding used in a file. Returns the long path+name of the path+name passed. Retrieves the current file position. Retrieves details about a shortcut. Returns the 8.3 short path+name of the path+name passed. Returns the size of a file in bytes. Returns the time and date information for a file. Returns the "File" version information. Include and install a file with the compiled script. Moves one or more files Opens a text file for reading or writing. Initiates a Open File Dialog. Read in a number of characters from a previously opened text file. Read in a line of text from a previously opened text file. Sends a file or directory to the recycle bin. Empties the recycle bin. Initiates a Save File Dialog. Initiates a Browse For Folder dialog. Sets the attributes of one or more files. Sets the current file position. Sets the timestamp of one of more files. Append a text/data to the end of a previously opened file. Append a line of text to the end of a previously opened text file. Returns a number rounded down to the closest integer. Sets the internet proxy to use for ftp access. Create a GUI window. Creates an AVI video control for the GUI. Creates a Button control for the GUI. Creates a Checkbox control for the GUI. Creates a ComboBox control for the GUI. Creates a date control for the GUI.

GUICtrlCreateContextMenu Creates a context menu for a control or entire GUI window.

GUICtrlCreateDummy GUICtrlCreateEdit GUICtrlCreateGraphic GUICtrlCreateGroup GUICtrlCreateIcon GUICtrlCreateInput GUICtrlCreateLabel GUICtrlCreateList GUICtrlCreateListView GUICtrlCreateListViewItem GUICtrlCreateMenu GUICtrlCreateMenuItem GUICtrlCreateMonthCal GUICtrlCreateObj GUICtrlCreatePic GUICtrlCreateProgress GUICtrlCreateRadio GUICtrlCreateSlider GUICtrlCreateTab GUICtrlCreateTabItem GUICtrlCreateTreeView GUICtrlCreateUpdown GUICtrlDelete GUICtrlGetHandle GUICtrlGetState GUICtrlRead GUICtrlRec vMsg GUICtrlSendMsg GUICtrlSendT oDummy GUICtrlSetBkColor GUICtrlSetColor GUICtrlSetCursor GUICtrlSetData GUICtrlSetDefBkColor GUICtrlSetDefColor GUICtrlSetFont GUICtrlSetGraphic GUICtrlSetImage GUICtrlSetLimit GUICtrlSetOnEvent GUICtrlSetPos GUICtrlSetResizing GUICtrlSetState

Creates a Dummy control for the GUI. Creates an Edit control for the GUI. Creates a Graphic control for the GUI. Creates a Group control for the GUI. Creates an Icon control for the GUI. Creates an Input control for the GUI. Creates a static Label control for the GUI. Creates a List control for the GUI. Creates a ListView control for the GUI. Creates a ListView item. Creates a Menu control for the GUI. Creates a MenuItem control for the GUI. Creates a month calendar control for the GUI. Creates an ActiveX control in the GUI. Creates a Picture control for the GUI. Creates a Progress control for the GUI. Creates a Radio button control for the GUI. Creates a Slider control for the GUI. Creates a Tab control for the GUI. Creates a TabItem control for the GUI. Creates a TreeView control for the GUI. Creates an UpDown control for the GUI. Deletes a control. Returns the handle for a control and some special (item) handles (Menu, ContextMenu, TreeViewItem). Gets the current state of a control Read state or data of a control. Send a message to a control and retrieve information in lParam. Send a message to a control. Sends a message to a Dummy control. Sets the background color of a control. Sets the text color of a control. Sets the mouse cursor icon for a particular control. Modifies the data for a control. Sets the default background color of all the controls of the GUI window. Sets the default text color of all the controls of the GUI window. Sets the font for a control. Modifies the data for a control. Sets the bitmap or icon image to use for a control. Limits the number of characters/pixels for a control. Defines a user-defined function to be called when a control is clicked. Changes the position of a control within the GUI window. Defines the resizing method used by a control. Changes the state of a control.

GUICtrlCreateTreeViewItem Creates a TreeViewItem control for the GUI.

GUICtrlRegisterListViewSort Register a user defined function for an internal listview sorting callback function.

GUICtrlSetStyle GUICtrlSetTip GUIDelete GUIGetCursorInfo GUIGetMsg GUIGetStyle GUIRegisterMsg GUISetAccelerators GUISetBkColor GUISetCoord GUISetCursor GUISetFont GUISetHelp GUISetIcon GUISetOnEvent GUISetState GUISetStyle GUIStartGroup GUISwitch Hex HotKeySet HttpSetProxy HttpSetUserAgent HWnd InetClose InetGet InetGetInfo InetGetSize InetRead IniDelete IniRead IniReadSection IniReadSec tionNames IniRenameSec tion IniWrite IniWriteSection InputBox Int IsAdmin IsArray IsBinary IsBool IsDeclared IsDllStruct IsFloat

Changes the style of a control. Sets the tip text associated with a control. Deletes a GUI window and all controls that it contains. Gets the mouse cursor position relative to GUI window. Polls the GUI to see if any events have occurred. Retrieves the styles of a GUI window. Register a user defined function for a known Windows Message ID (WM_MSG). Sets the accelerator table to be used in a GUI window. Sets the background color of the GUI window. Sets absolute coordinates for the next control. Sets the mouse cursor icon for a GUI window. Sets the default font for a GUI window. Sets an executable file that will be run when F1 is pressed. Sets the icon used in a GUI window. Defines a user function to be called when a system button is clicked. Changes the state of a GUI window. Changes the styles of a GUI window. Defines that any subsequent controls that are created will be "grouped" together. Switches the current window used for GUI functions. Returns a string representation of an integer or of a binary type converted to hexadec imal. Sets a hotkey that calls a user function. Sets the internet proxy to use for http access. Sets the user-agent string sent with InetGet() and InetRead() requests. Converts an expression into an HWND handle. Closes a handle returned from InetGet(). Downloads a file from the internet using the HTTP, HTTPS or FTP protocol. Returns detailed data for a handle returned from InetGet(). Returns the size (in bytes) of a file located on the internet. Downloads a file from the internet using the HTTP, HTTPS or FTP protocol. Deletes a value from a standard format .ini file. Reads a value from a standard format .ini file. Reads all key/value pairs from a section in a standard format .ini file. Reads all sections in a standard format .ini file. Renames a section in a standard format .ini file. Writes a value to a standard format .ini file. Writes a section to a standard format .ini file. Displays an input box to ask the user to enter a string. Returns the integer (whole number) representation of an expression. Checks if the current user has full administrator privileges. Checks if a variable is an array type. Checks if a variable or expression is a binary type. Checks if a variable's base type is boolean. Check if a variable has been declared. Checks if a variable is a DllStruct type. Checks if a variable or expression is a float-type.

IsHWnd IsInt IsKeyword IsNumber IsObj IsPtr IsString Log MemGetStats Mod MouseClick MouseClic kDrag MouseDown MouseGetCursor MouseGetPos MouseMove MouseUp MouseWheel MsgBox Number ObjCreate ObjEvent ObjGet ObjName OnAutoItExitRegister OnAutoItExitUnRegister Ping PixelChec ksum PixelGetColor PixelSearch PluginClose PluginOpen ProcessClose ProcessExists ProcessGetStats ProcessList ProcessSetPriority ProcessWait ProcessWaitClose ProgressOff ProgressOn ProgressSet Ptr Random RegDelete RegEnumKey

Checks if a variable's base type is a pointer and window handle. Checks if a variable or expression is an integer type. Checks if a variable is a keyword (for example, Default). Checks if a variable's base type is numeric. Checks if a variable or expression is an object type. Checks if a variable's base type is a pointer. Checks if a variable is a string type. Calculates the natural logarithm of a number. Retrieves memory related information. Performs the modulus operation. Perform a mouse click operation. Perform a mouse click and drag operation. Perform a mouse down event at the current mouse position. Returns the cursor ID Number for the current Mouse Cursor. Retrieves the current position of the mouse cursor. Moves the mouse pointer. Perform a mouse up event at the current mouse position. Moves the mouse wheel up or down. NT/2000/XP ONLY. Displays a simple message box with optional timeout. Returns the numeric representation of an expression. Creates a reference to a COM object from the given classname. Handles incoming events from the given Object. Retrieves a reference to a COM object from an existing process or filename. Returns the name or interface description of an Object Registers a function to be called when AutoIt exits. UnRegisters a function that was called when AutoIt exits. Pings a host and returns the roundtrip-time. Generates a checksum for a region of pixels. Returns a pixel color according to x,y pixel coordinates. Searches a rectangle of pixels for the pixel color provided. Close a plugin file Open a plugin file. Terminates a named process. Checks to see if a specified process exists. Returns an array about Memory or IO infos of a running process. Returns an array listing the currently running processes (names and PIDs). Changes the priority of a process Pauses script execution until a given process exists. Pauses script execution until a given process does not exist. Turns Progress window off. Creates a customizable progress bar window. Sets the position and/or text of a previously created Progress bar window. Converts an expression into a pointer variant. Generates a pseudo-random float-type number. Deletes a key or value from the registry. Reads the name of a subkey according to it's instance.

RegEnumVal RegRead RegWrite Round Run RunAs RunAsWait RunWait Send SendKeepActive SetError SetExtended ShellExecute ShellExecuteWait Shutdown Sin Sleep SoundPlay SoundSetWaveVolume SplashImageOn SplashOff SplashTextOn Sqrt SRandom StatusbarGetText StderrRead StdinWrite StdioClose StdoutRead String StringAddCR StringCompare StringFormat StringFromASCIIArray StringInStr StringIsAlNum StringIsAlpha StringIsASCII StringIsDigit StringIsFloat StringIsInt StringIsLower

Reads the name of a value according to it's instance. Reads a value from the registry. Creates a key or value in the registry. Returns a number rounded to a specified number of decimal places. Runs an external program. Runs an external program under the context of a different user. Runs an external program under the context of a different user and pauses script execution until the program finishes. Runs an external program and pauses script execution until the program finishes. Sends simulated keystrokes to the active window. Attempts to keep a specified window active during Send(). Manually set the value of the @error macro. Manually set the value of the @extended macro. Runs an external program using the ShellExecute API. Runs an external program using the ShellExecute API and pauses script execution until it finishes. Shuts down the system. Calculates the sine of a number. Pause script execution. Play a sound file. Sets the system wave volume by percent. Creates a customizable image popup window. Turns SplashText or SplashImage off. Creates a customizable text popup window. Calculates the square-root of a number. Set Seed for random number generation. Retrieves the text from a standard status bar control. Reads from the STDERR stream of a previously run child process. Writes a number of characters to the STDIN stream of a previously run child process. Closes all resources associated with a process previously run with STDIO redirection. Reads from the STDOUT stream of a previously run child process. Returns the string representation of an expression. Takes a string and prefixes all linefeed characters ( Chr(10) ) with a carriage return character ( Chr(13) ). Compares two strings with options. Returns a formatted string (similar to the C sprintf() function). Converts an array of ASCII codes to a string. Checks if a string contains a given substring. Checks if a string contains only alphanumeric characters. Checks if a string contains only alphabetic characters. Checks if a string contains only ASCII characters in the range 0x00 - 0x7f (0 127). Checks if a string contains only digit (0-9) characters. Checks if a string is a floating point number. Checks if a string is an integer. Checks if a string contains only lowercase characters.

StringIsSpace StringIsUpper StringIsXDigit StringLeft StringLen StringLower StringMid StringRegExp StringRegExpReplac e StringReplace StringRight StringSplit StringStripCR StringStripWS StringToASCIIArray StringToBinary StringTrimLeft StringTrimRight StringUpper Tan TCPAccept TCPCloseSocket TCPConnect TCPListen TCPNameToIP TCPRecv TCPSend TCPShutdown, UDPShutdown TCPStartup, UDPStartup T imerDiff TimerInit ToolTip TrayCreateItem TrayCreateMenu TrayGetMsg TrayItemDelete TrayItemGetHandle TrayItemGetState TrayItemGetText TrayItemSetOnEvent TrayItemSetState TrayItemSetText TraySetClick TraySetIcon TraySetOnEvent

Checks if a string contains only whitespace characters. Checks if a string contains only uppercase characters. Checks if a string contains only hexadecimal digit (0-9, A-F) characters. Returns a number of characters from the left-hand side of a string. Returns the number of characters in a string. Converts a string to lowercase. Extracts a number of characters from a string. Check if a string fits a given regular expression pattern. Replace text in a string based on regular expressions. Replaces substrings in a string. Returns a number of characters from the right-hand side of a string. Splits up a string into substrings depending on the given delimiters. Removes all carriage return values ( Chr(13) ) from a string. Strips the white space in a string. Converts a string to an array containing the ASCII code of each character. Converts a string into binary data. Trims a number of characters from the left hand side of a string. Trims a number of characters from the right hand side of a string. Converts a string to uppercase. Calculates the tangent of a number. Permits an incoming connection attempt on a socket. Closes a TCP socket. Create a socket connected to an existing server. Creates a socket listening for an incoming connection. Converts an Internet name to IP address. Receives data from a connected socket. Sends data on a connected socket. Stops TCP/UDP services. Starts TCP or UDP services. Returns the difference in time from a previous call to TimerInit(). Returns a timestamp (in millisec onds). Creates a tooltip anywhere on the screen. Creates a menuitem control for the tray. Creates a menu control for the tray menu. Polls the tray to see if any events have occurred. Deletes a menu/item control from the tray menu. Returns the handle for a tray menu(item). Gets the current state of a control. Gets the itemtext of a tray menu/item control. Defines a user-defined function to be called when a tray item is clicked. Sets the state of a tray menu/item control. Sets the itemtext of a tray menu/item control. Sets the clickmode of the tray icon - what mouseclicks will display the tray menu. Loads/Sets a specified tray icon. Defines a user function to be called when a special tray action happens.

TraySetPauseIcon TraySetState TraySetToolTip TrayTip UBound UDPBind UDPCloseSocket UDPOpen UDPRec v UDPSend VarGetType WinActivate WinActive WinClose WinExists WinFlash WinGetCaretPos WinGetClassList WinGetClientSize WinGetHandle WinGetPos WinGetProcess WinGetState WinGetText WinGetTitle WinKill WinList WinMenuSelectItem WinMinimizeAll WinMinimizeAllUndo WinMove WinSetOnTop WinSetState WinSetTitle WinSetTrans WinWait WinWaitActive WinWaitClose WinWaitNotActive

Loads/Sets a specified tray pause icon. Sets the state of the tray icon. (Re)Sets the tooltip text for the tray icon. Displays a balloon tip from the AutoIt Icon. (2000/XP only) Returns the size of array dimensions. Create a socket bound to an incoming connection. Close a UDP socket. Open a socket connected to an existing server . Receives data from a opened socket Sends data on an opened socket Returns the internal type representation of a variant. Activates (gives focus to) a window. Checks to see if a specified window exists and is currently active. Closes a window. Checks to see if a specified window exists. Flashes a window in the taskbar. Returns the coordinates of the caret in the foreground window Retrieves the classes from a window. Retrieves the size of a given window's client area. Retrieves the internal handle of a window. Retrieves the position and size of a given window. Retrieves the Process ID (PID) associated with a window. Retrieves the state of a given window. Retrieves the text from a window. Retrieves the full title from a window. Forces a window to close. Retrieves a list of windows. Invokes a menu item of a window. Minimizes all windows. Undoes a previous WinMinimizeAll function. Moves and/or resizes a window. Change a window's "Always On Top" attribute. Shows, hides, minimizes, maximizes, or restores a window. Changes the title of a window. Sets the transparency of a window. (Windows 2000/XP or later) Pauses execution of the script until the requested window exists. Pauses execution of the script until the requested window is active. Pauses execution of the script until the requested window does not exist. Pauses execution of the script until the requested window is not active.

Function Notes
Many functions contain optional parameters that can be omitted. If you wish to specify an optional parameter, however, all preceding parameters must be specified! For example, consider Run ( "filename", ["workingdir" [, flag]] ). If you wish to specify the flag, you must specify a workingdir. Many Win___ functions contain an optional parameter "text". This parameter is intended to help differentiate between windows that have identical titles. Some functions indicate success/failure as a return value; others indicate it by setting the @error flag. Some do both.... @error = 0 ;is always success Return = varies, but is typically non-zero for success to allow easy to read code... If someUserFunc() then ;...function worked If Not someUserFunc() then ;...function failed $x = FileReadLine("C:\someFile.txt") If @error = -1 Then ;end-of-file was reached If a function can set the @error flag, you should always check it before using a return value - if @error indicates an error then the function return value is generally undefined... @error is always set to 0 when entering in a function. When the documentation states that the return value = none, AutoIt always returns a value to avoid errors. 1 is usually the value returned, but you should not depend on this return value. When an optional parameter needs to be defined and is preceded by one or more optional parameters, the default value must be given. This may be "" for a string parameter and -1 for other types. Some functions like StringInStr or StringReplace require 0. See the corresponding optional parameter description.

Environment functions Reference


Below is a complete list of the functions available in AutoIt. Click on a function name for a detailed description. Function ClipGet ClipPut EnvGet EnvSet EnvUpdate MemGetStats Description Retrieves text from the clipboard. Writes text to the clipboard. Retrieves an environment variable. Writes an environment variable. Refreshes the OS environment. Retrieves memory related information.

Function Reference

ClipGet
Retrieves text from the clipboard. ClipGet ( ) Parameters None. Return Value Success: Failure: Returns a string containing the text on the clipboard. Sets @error to 1 if clipboard is empty to 2 if contains a non-text entry. to 3 or 4 if cannot access the clipboard. Remarks When multiple selecting file/dir are stored in the clipboard, the filename/dirname are returned as texts separated by @LF. Related ClipPut Example

$bak = ClipGet() MsgBox(0, "Clipboard contains:", $bak) ClipPut($bak & "additional text") MsgBox(0, "Clipboard contains:", ClipGet())

Function Reference

ClipPut
Writes text to the clipboard. ClipPut ( "value" ) Parameters value Return Value Success: Failure: Remarks Any existing clipboard contents are overwritten. An empty string "" will empty the clipboard. Related ClipGet Example Returns 1. Returns 0. The text to write to the clipboard.

ClipPut("I am copied to the clipboard")

Function Reference

EnvGet
Retrieves an environment variable. EnvGet ( "envvariable" ) Parameters envvariable Return Value Returns the requested variable (or a blank string if the variable does not exist). Remarks None. Related EnvSet, EnvUpdate Example Name of the environment variable to get such as "TEMP" or "PATH".

$var = EnvGet("PATH") MsgBox(4096, "Path variable is:", $var)

Function Reference

EnvSet
Writes an environment variable. EnvSet ( "envvariable" [, "value"] ) Parameters envvariable value Return Value Success: Failure: Remarks A environment variable set in this way will only be accessible to programs that AutoIt spawns (Run, RunWait). Once AutoIt closes, the variables will cease to exist. Related EnvGet, EnvUpdate Example Returns not 0. Returns 0. Name of the environment variable to set. [optional] Value to set the environment variable to. If a value is not used the environment variable will be deleted.

EnvSet("MYENV", "this is a test")

Function Reference

EnvUpdate
Refreshes the OS environment. EnvUpdate ( ) Parameters None. Return Value Success: Failure: Remarks Similar effect as logging off and then on again. For example, changes to the %path% environment might not take effect until you call EnvUpdate (or you logoff/reboot). Related EnvGet, EnvSet Example None. Sets @error to 1.

EnvUpdate()

Function Reference

MemGetStats
Retrieves memory related information. MemGetStats ( ) Parameters None. Return Value Returns a seven-element array containing the memory information: $array[0] $array[1] $array[2] $array[3] $array[4] $array[5] $array[6] = Memory Load (Percentage of memory in use) = Total physical RAM = Available physical RAM = Total Pagefile = Available Pagefile = Total virtual = Available virtual

All memory sizes are in kilobytes. Remarks None. Related None. Example

$mem = MemGetStats() MsgBox(0, "Total physical RAM (KB):", $mem[1])

File, Directory and Disk functions Reference


Below is a complete list of the functions available in AutoIt. Click on a function name for a detailed description. Function ConsoleRead ConsoleWrite ConsoleWriteError DirCopy DirCreate DirGetSize DirMove DirRemove DriveGetDrive DriveGetFileSystem DriveGetLabel DriveGetSerial DriveGetType DriveMapAdd DriveMapDel DriveMapGet DriveSetLabel DriveSpaceFree DriveSpaceTotal DriveStatus FileChangeDir FileClose FileCopy FileCreateNTFSLink FileCreateShortcut FileDelete FileExists FileFindFirstFile FileFindNextFile FileFlush FileGetAttrib FileGetEncoding FileGetLongName Description Read from the STDIN stream of the AutoIt script process. Writes data to the STDOUT stream. Some text editors can read this stream as can other programs which may be expecting data on this stream. Writes data to the STDERR stream. Some text editors can read this stream as can other programs which may be expecting data on this stream. Copies a directory and all sub-directories and files (Similar to xcopy). Creates a directory/folder. Returns the size in bytes of a given directory. Moves a directory and all sub-directories and files. Deletes a directory/folder. Returns an array containing the enumerated drives. Returns File System Type of a drive. Returns Volume Label of a drive, if it has one. Returns Serial Number of a drive. Returns drive type. Maps a network drive. Disconnects a network drive. Retrieves the details of a mapped drive. Sets the Volume Label of a drive. Returns the free disk space of a path in Megabytes. Returns the total disk space of a path in Megabytes. Returns the status of the drive as a string. Changes the current working directory. Closes a previously opened text file. Copies one or more files. Creates an NTFS hardlink to a file or a directory Creates a shortcut (.lnk) to a file. Delete one or more files. Checks if a file or directory exists. Returns a search "handle" according to file search string. Returns a filename according to a previous call to FileFindFirstFile. Flushes the file's buffer to disk. Returns a code string representing a file's attributes. Determines the text encoding used in a file. Returns the long path+name of the path+name passed.

FileGetPos FileGetShortcut FileGetShortName FileGetSize FileGetTime FileGetVersion FileInstall FileMove FileOpen FileOpenDialog FileRead FileReadLine FileRecycle FileRecycleEmpty FileSaveDialog FileSelectFolder FileSetAttrib FileSetPos FileSetTime FileWrite FileWriteLine IniDelete IniRead IniReadSection IniReadSec tionNames IniRenameSec tion IniWrite IniWriteSection

Retrieves the current file position. Retrieves details about a shortcut. Returns the 8.3 short path+name of the path+name passed. Returns the size of a file in bytes. Returns the time and date information for a file. Returns the "File" version information. Include and install a file with the compiled script. Moves one or more files Opens a text file for reading or writing. Initiates a Open File Dialog. Read in a number of characters from a previously opened text file. Read in a line of text from a previously opened text file. Sends a file or directory to the recycle bin. Empties the recycle bin. Initiates a Save File Dialog. Initiates a Browse For Folder dialog. Sets the attributes of one or more files. Sets the current file position. Sets the timestamp of one of more files. Append a text/data to the end of a previously opened file. Append a line of text to the end of a previously opened text file. Deletes a value from a standard format .ini file. Reads a value from a standard format .ini file. Reads all key/value pairs from a section in a standard format .ini file. Reads all sections in a standard format .ini file. Renames a section in a standard format .ini file. Writes a value to a standard format .ini file. Writes a section to a standard format .ini file.

Function Reference

ConsoleRead
Read from the STDIN stream of the AutoIt script process. ConsoleRead ( [peek = false[, binary = false ]]) Parameters peek binary Return Value Success: Failure: Remarks ConsoleRead reads from the console standard input stream of the AutoIt script process, which is normally used by console applications to read input from a parent process. ConsoleRead does not block, it will return immediately. In order to get all data, it must be called in a loop. Peeking on the stream does not remove the data from the buffer, however, it does return the available data as normal. By default, data is returned in text format. By using the binary option, the data will be returned in binary format. Related ConsoleWrite, ConsoleWriteError, Run Example Returns the data read. @extended contains the number of bytes read. Sets @error to non-zero if EOF is reached, STDIN is not connected for the process or other error. [optional] If true the function does not remove the read characters from the stream. [optional] If true the function reads the data as binary instead of text (default is text).

; Compile this script to "ConsoleRead.exe". ; Open a command prompt to the directory where ConsoleRead.exe resides. ; Type the following on the command line: ; echo Hello! | ConsoleRead.exe ; ; When invoked in a console window, the above command echos the text "Hello!" ; but instead of dispalying it, the | tells the console to pipe it to the STDIN stream ; of the ConsoleRead.exe process. If Not @Compiled Then MsgBox(0, "", "This script must be compiled in order to properly demonstrate it's functionality.") Exit -1 EndIf Local $data While True $data &= ConsoleRead() If @error Then ExitLoop Sleep(25) WEnd MsgBox(0, "", "Received: " & @CRLF & @CRLF & $data)

Function Reference

ConsoleWrite
Writes data to the STDOUT stream. Some text editors can read this stream as can other programs which may be expecting data on this stream. ConsoleWrite ( "data" ) Parameters data Return Value The amount of data written. If writing binary, the number of bytes written, if writing text, the number of characters written. Remarks The purpose for this function is to write to the STDOUT stream. Many popular text editors can read this stream. Scripts compiled as Console applications also have a STDOUT stream. This does not write to a DOS console unless the script is compiled as a console application.. Characters are converted to ANSI before being written. Binary data is written as-is. It will not be converted to a string. To print the hex representation of binary data, use the String() function to explicitly cast the data to a string. Related ConsoleWriteError, ConsoleRead Example Local $var = "Test" ConsoleWrite("var=" & $var & @CRLF) ; Running this in a text editor which can trap console output should produce "var=Test" The data you wish to output. This may either be text or binary.

Function Reference

ConsoleWriteError
Writes data to the STDERR stream. Some text editors can read this stream as can other programs which may be expecting data on this stream. ConsoleWriteError ( "data" ) Parameters data Return Value The amount of data written. If writing binary, the number of bytes written, if writing text, the number of characters written. Remarks The purpose for this function is to write to the STDERR stream. Many popular text editors can read this stream. Scripts compiled as Console applications also have a STDERR stream. This does not write to a DOS console unless the script is compiled as a console application.. Characters are converted to ANSI before being written. Binary data is written as-is. It will not be converted to a string. To print the hex representation of binary data, use the String() function to explicitly cast the data to a string. Related ConsoleWrite, ConsoleRead Example Local $var = "Test" ConsoleWriteError("var=" & $var & @CRLF) ; Running this in a text editor which can trap console output should produce "var=Test" The data you wish to output. This may either be text or binary.

Function Reference

DirCopy
Copies a directory and all sub-directories and files (Similar to xcopy). DirCopy ( "source dir", "dest dir" [, flag] ) Parameters source dir dest dir flag Return Value Success: Failure: Remarks If the destination directory structure doesn't exist, it will be created (if possible). Related DirRemove, FileCopy Example Returns 1. Returns 0 if there is an error copying the directory. Path of the source directory (with no trailing backslash). e.g. "C:\Path1" Path of the destination dir (with no trailing backslash). e.g. "C:\Path_Copy" [optional] this flag determines whether to overwrite file if they already exist: 0 = (default) do not overwrite existing files 1 = overwrite existing files

DirCopy(@MyDocumentsDir, "C:\Backups\MyDocs", 1)

Function Reference

DirCreate
Creates a directory/folder. DirCreate ( "path" ) Parameters path Return Value Success: Failure: Remarks This function will also create all parent directories given in "path" if they do not already exist. Related DirRemove, FileCopy Example Returns 1. Returns 0 if there is an error creating the directory. Path of the directory to create.

DirCreate("C:\Test1\Folder1\Folder2")

Function Reference

DirGetSize
Returns the size in bytes of a given directory. DirGetSize ( "path" [, flag] ) Parameters path The directory path to get the size from, e.g. "C:\Windows". [optional] this flag determines the behaviour and result of the function, and can be a combination of the following: 0 = (default) 1 = Extended mode is On -> returns an array that contains extended information (see Remarks). 2 = Don't get the size of files in subdirectories (recursive mode is Off)

flag

Return Value Success: Failure: Remarks If the script is paused then this function is paused too and will only continue when the script continues! If you use the extended mode then the array returned from this function is a single dimension array containing the following elements: $array[0] = Size $array[1] = Files count $array[2] = Dirs Count Related None. Example Returns >= 0 the sizes Returns -1 and sets @error to 1 if the path doesn't exist.

$size = DirGetSize(@HomeDrive) Msgbox(0,"","Size(MegaBytes):" & Round($size / 1024 / 1024)) $size = DirGetSize(@WindowsDir, 2) Msgbox(0,"","Size(MegaBytes):" & Round($size / 1024 / 1024)) $timer = TimerInit() $size = DirGetSize("\\10.0.0.1\h$",1) $diff = Round(TimerDiff($timer) / 1000) ; time in seconds If IsArray($size) Then Msgbox(0,"DirGetSize-Info","Size(Bytes):" & $size[0] & @LF _ & "Files:" & $size[1] & @LF & "Dirs:" & $size[2] & @LF _ & "TimeDiff(Sec):" & $diff) EndIf

Function Reference

DirMove
Moves a directory and all sub-directories and files. DirMove ( "source dir", "dest dir" [, flag] ) Parameters source dir dest dir flag Return Value Success: Failure: Remarks If the source and destination are on different volumes or UNC paths are used then a copy/delete operation will be performed rather than a move. If the destination already exists and the overwrite flag is specified then the source directory will be moved inside the destination. Because AutoIt lacks a "DirRename" function, use DirMove to rename a folder! Related DirRemove, FileMove Example Returns 1. Returns 0 if there is an error moving the directory. Path of the source directory (with no trailing backslash). e.g. "C:\Path1" Path of the destination dir (with no trailing backslash). e.g. "C:\Path_Copy" [optional] this flag determines whether to overwrite files if they already exist: 0 = (default) do not overwrite existing files 1 = overwrite existing files

DirMove(@MyDocumentsDir, "C:\Backups\MyDocs")

Function Reference

DirRemove
Deletes a directory/folder. DirRemove ( "path" [, recurse] ) Parameters path recurse Return Value Success: Failure: Remarks Some dir attributes can make the removal impossible. Related DirCreate, FileRecycle, DirCopy, DirMove, FileDelete Example Returns 1. Returns 0 if there is an error removing the directory (or if directory does not exist). Path of the directory to remove. [optional] Use this flag to specify if you want to delete sub-directories too. 0 = (default) do not remove files and sub-directories 1 = remove files and subdirectories (like the DOS DelTree command)

; Delete C:\Test1 and all subdirs and files DirRemove("C:\Test1", 1)

Function Reference

DriveGetDrive
Returns an array containing the enumerated drives. DriveGetDrive ( "type" ) Parameters type Return Value Success: Failure: Remarks None. Related DriveGetFileSystem, DriveGetLabel, DriveGetSerial, DriveGetType, DriveSetLabel, DriveSpaceFree, DriveSpaceTotal, DriveStatus Example Returns an array of strings (drive letter followed by colon) of drives found. The zeroth array element contains the number of drives. Returns "" and sets @error to 1. Type of drive to find: "ALL", "CDROM", "REMOVABLE", "FIXED", "NET WORK", "RAMDISK", or "UNKNOWN"

$var = DriveGetDrive( "all" ) If NOT @error Then MsgBox(4096,"", "Found " & $var[0] & " drives") For $i = 1 to $var[0] MsgBox(4096,"Drive " & $i, $var[$i]) Next EndIf

Function Reference

DriveGetFileSystem
Returns File System Type of a drive. DriveGetFileSystem ( "path" ) Parameters path Return Value Success: Failure: Returns the File System Type of the drive as a string; see table below. Sets @error to 1. Path of drive to receive information from.

Return Value 1 (numeric) "FAT" "FAT32" "NTFS" "NWFS" "CDFS" "UDF" Remarks

Interpretation Drive does NOT contain media (CD, Floppy, Zip) or media is unformatted (RAW). Typical file system for drives under ~500 MB such as Floppy, RAM disks, USB "pen" drives, etc. Typical file system for Windows 9x/Me hard drives. Typical file system for Windows NT/2000/XP hard drives. Typical file system for Novell Netware file servers. Typically indicates a CD (or an ISO image mounted as a virtual CD drive). Typically indicates a DVD.

The list of possible return values might be incomplete. Related DriveGetDrive, DriveGetLabel, DriveGetSerial, DriveGetType, DriveSetLabel, DriveSpaceFree, DriveSpaceTotal, DriveStatus Example

$var = DriveGetFileSystem( "c:\" ) MsgBox(4096,"File System Type:", $var)

Function Reference

DriveGetLabel
Returns Volume Label of a drive, if it has one. DriveGetLabel ( "path" ) Parameters path Return Value Success: Failure: Remarks None. Related DriveGetDrive, DriveGetFileSystem, DriveGetSerial, DriveGetType, DriveSetLabel, DriveSpaceFree, DriveSpaceTotal, DriveStatus Example Returns the Volume Label of the drive as a string. Sets @error to 1. Path of drive to receive information from.

$var = DriveGetLabel( "c:\" ) MsgBox(4096,"Volume Label: ",$var)

Function Reference

DriveGetSerial
Returns Serial Number of a drive. DriveGetSerial ( "path" ) Parameters path Return Value Success: Failure: Remarks The value returned is not the hardware serial number as found on the label of the drive, it is the Windows Volume ID for the drive. Related DriveGetDrive, DriveGetFileSystem, DriveGetLabel, DriveGetType, DriveSetLabel, DriveSpaceFree, DriveSpaceTotal, DriveStatus Example Returns the Serial Number of the drive as a string. Sets @error to 1. Path of drive to receive information from.

$var = DriveGetSerial( "c:\" ) MsgBox(4096, "Serial Number: ", $var)

Function Reference

DriveGetType
Returns drive type. DriveGetType ( "path" ) Parameters path Return Value Success: Failure: Remarks The list of possible return values might be incomplete. Related DriveGetDrive, DriveGetFileSystem, DriveGetLabel, DriveGetSerial, DriveSetLabel, DriveSpaceFree, DriveSpaceTotal, DriveStatus, CDTray Example Returns the type of drive: "Unknown", "Removable", "Fixed", "Network", "CDROM", "RAMDisk" Returns "" and sets @error to 1. Path of drive to receive information from.

$var = DriveGetType( "c:\" ) MsgBox(4096, "Drive Type:", $var)

Function Reference

DriveMapAdd
Maps a network drive. DriveMapAdd ( "device", "remote share" [, flags [, "user" [, "password"]]] ) Parameters device remote share flags user password Return Value Success: Failure: Remarks When the function fails (returns 0) @error contains extended information: 1 = Undefined / Other error. @extended set with Windows API return 2 = Access to the remote share was denied 3 = The device is already assigned 4 = Invalid device name 5 = Invalid remote share 6 = Invalid password Note: When using "*" for the device parameter the drive letter selected will be returned instead of 1 or 0, e.g. "U:". If there was an error using "*" then a blank string "" will be returned. If defined the user/password will be presented to the remote computer that will validate the credential. Related DriveMapDel, DriveMapGet Example Returns 1. (See Remarks) Returns 0 if a new mapping could not be created and sets @error (see below). (See Remarks) The device to map, for example "O:" or "LPT1:". If you pass a blank string for this parameter a connection is made but not mapped to a specific drive. If you specify "*" an unused drive letter will be automatically selected. The remote share to connect to in the form "\\server\share". [optional] A combination of the following: 0 = default 1 = Persistent mapping 8 = Show authentication dialog if required [optional] The username to use to connect. In the form "username" or "domain\username". [optional] The password to use to connect.

; Map X drive to \\myserver\stuff using current user DriveMapAdd("X:", "\\myserver\stuff") ; Map X drive to \\myserver2\stuff2 using the user "jon" from "domainx" with password "tickle" DriveMapAdd("X:", "\\myserver2\stuff2", 0, "domainx\jon", "tickle")

Function Reference

DriveMapDel
Disconnects a network drive. DriveMapDel ( "drive" ) Parameters drive Return Value Success: Failure: Remarks If a connection has no drive letter mapped you may use the connection name to disconnect, e.g. \\server\share Related DriveMapAdd, DriveMapGet Example Returns 1. Returns 0 if the disconnection was unsuccessful. The device to disconnect, e.g. "O:" or "LPT1:".

; Map X drive to \\myserver\stuff using current user DriveMapAdd("X:", "\\myserver\stuff") ; Disconnect DriveMapDel("X:")

Function Reference

DriveMapGet
Retrieves the details of a mapped drive. DriveMapGet ( "device" ) Parameters device Return Value Success: Failure: Remarks None. Related DriveMapAdd, DriveMapDel Example Returns details of the mapping, e.g. \\server\share Returns a blank string "" and sets @error to 1. The device (drive or printer) letter to query, e.g. "O:" or "LPT1:"

; Map X drive to \\myserver\stuff using current user DriveMapAdd("X:", "\\myserver\stuff") ; Get details of the mapping MsgBox(0, "Drive X: is mapped to", DriveMapGet("X:"))

Function Reference

DriveSetLabel
Sets the Volume Label of a drive. DriveSetLabel ( "path", "label" ) Parameters path label Return Value Success: Failure: Remarks Most hard drives have a maximum label length of 11 characters, and DriveSetLabel will fail if max length is exceeded. Also, FAT32 partition labels tend to revert to all capital letters. Related DriveGetDrive, DriveGetFileSystem, DriveGetLabel, DriveGetSerial, DriveGetType, DriveSpaceFree, DriveSpaceTotal, DriveStatus Example Returns 1. Returns 0. Path of drive to change. New volume label for the drive. (11 characters is usually max length)

DriveSetLabel("C:\", "New_Label")

Function Reference

DriveSpaceFree
Returns the free disk space of a path in Megabytes. DriveSpaceFree ( "path" ) Parameters path Return Value Success: Failure: Remarks DriveSpaceFree may even work when a complete directory path (that exists) is given. However, a file path won't work. Use the Round function if the return value is too precise. Related DriveGetDrive, DriveGetFileSystem, DriveGetLabel, DriveGetSerial, DriveGetType, DriveSetLabel, DriveSpaceTotal, DriveStatus Example Returns free disk space in Megabytes as a float number. Returns 0 and sets @error to 1. Path of drive to receive information from.

$var = DriveSpaceFree( "c:\" ) MsgBox(4096, "Free space on C:", $var & " MB")

Function Reference

DriveSpaceTotal
Returns the total disk space of a path in Megabytes. DriveSpaceTotal ( "path" ) Parameters path Return Value Success: Failure: Remarks DriveSpaceTotal may even work when a complete directory path (that exists) is given. However, a file path won't work. Related DriveGetDrive, DriveGetFileSystem, DriveGetLabel, DriveGetSerial, DriveGetType, DriveSetLabel, DriveSpaceFree, DriveStatus, FileGetSize Example Returns diskspace in Megabytes as a float number. Sets @error to 1. Path of drive to receive information from.

$var = DriveSpaceTotal( "c:\" ) MsgBox(4096, "Total Space on C:", $var & " MB")

Function Reference

DriveStatus
Returns the status of the drive as a string. DriveStatus ( "path" ) Parameters path Return Value Value UNKNOWN READY NOTREADY INVALID Remarks The list of possible return values may be incomplete. DriveStatus may even work when a complete directory path (which exists) is given. However, a file path won't work. Related DriveGetDrive, DriveGetFileSystem, DriveGetLabel, DriveGetSerial, DriveGetType, DriveSetLabel, DriveSpaceFree, DriveSpaceTotal, CDTray, FileExists Example Interpretation Drive may be unformatted (RAW). Typical of hard drives and drives that contain removable media. Typical of floppy and CD drives that do not contain media. May indicate the drive letter does not exist or that a mapped network drive is inaccessible. Path of drive to receive information from.

$var = DriveStatus( "c:\" ) MsgBox(4096,"Status",$var)

Function Reference

FileChangeDir
Changes the current working directory. FileChangeDir ( "path" ) Parameters path Return Value Success: Failure: Remarks None. Related @WorkingDir Example Returns 1. Returns 0 if working directory not changed. The path to make the current working directory.

FileChangeDir(@WindowsDir)

Function Reference

FileClose
Closes a previously opened text file. FileClose ( filehandle ) Parameters filehandle Return Value Success: Failure: Remarks Upon termination, AutoIt automatically closes any files it opened, but calling FileClose is still a good idea. This function is also used to close search handles as returned by FileFindFirstFile(). Related FileFindFirstFile, FileOpen, FileFindNextFile, FileFlush Example Returns 1. Returns 0 if the filehandle is invalid. The handle of a file, as returned by a previous call to FileOpen.

$handle = FileOpen("test.txt", 0) FileClose($handle)

Function Reference

FileCopy
Copies one or more files. FileCopy ( "source", "dest" [, flag] ) Parameters source dest The source path of the file(s) to copy. Wildcards are supported. The destination path of the copied file(s). [optional] this flag determines whether to overwrite files if they already exist. Can be a combination of the following: 0 = (default) do not overwrite existing files 1 = overwrite existing files 8 = Create destination directory structure if it doesn't exist (See Remarks).

flag

Return Value Success: Failure: Remarks The destination directory must already exist, except using with flag value '8'. For instance the combined flag '9' (1 + 8) overwrites the target file and pre-checks for the destination directory structure and if it doesn't exist creates it automatically. See FileFindFirstFile for a discussion of wildcards. Some file attributes can make the overwriting impossible. Related FileMove, FileDelete, DirCopy, DirCreate Example Returns 1. Returns 0.

FileCopy("C:\*.au3", "D:\mydir\*.*") ; Method to copy a folder (with its contents) DirCreate("C:\new") FileCopy("C:\old\*.*", "C:\new\") FileCopy("C:\Temp\*.txt", "C:\Temp\TxtFiles\", 8) ; RIGHT - 'TxtFiles' is now the target directory and the file names are given by the source names FileCopy("C:\Temp\*.txt", "C:\Temp\TxtFiles\", 9) ; Flag = 1 + 8 (overwrite + create target directory structure) ; Copy the txt-files from source to target and overwrite target files with same name

Function Reference

FileCreateNTFSLink
Creates an NTFS hardlink to a file or a directory FileCreateNTFSLink ( "source", "hardlink" [, flag] ) Parameters source hardlink flag Path of the source to which the hardlink will be created. Path of the hardlink. [optional] this flag determines whether to overwrite link if they already exist. Can be a combination of the following: 0 = (default) do not overwrite existing link 1 = overwrite existing link

Return Value Success: Failure: Remarks The destination directory must already exist. This function works only on volume with NTFS File system. If the source is a file, the hardlink must be on the same volume. If the source is a directory cross volume is allowed. FileDelete or FileMove can be used on hardlink. To manage the link with the explorer you can use the shell extension NTFSLink Related FileCreateShortcut Example Returns 1. Returns 0.

FileChangeDir(@ScriptDir) DirCreate('dir') FileWriteLine("test.txt","test") MsgBox(0,"Hardlink", FileCreateNTFSLink("test.txt", "dir\test.log", 1))

Function Reference

FileCreateShortcut
Creates a shortcut (.lnk) to a file. FileCreateShortcut ( "file", "lnk" [, "workdir" [, "args" [, "desc" [, "icon" [, "hotkey" [, icon number [, state]]]]]]] ) Parameters file lnk workdir args desc icon hotkey ic on number state Return Value Success: Failure: Remarks Hotkeys for windows shortcuts are of the following form: Ctrl+Alt+X, Ctrl+Shift+X, Shift+Alt+X, Ctrl+NumPadKey, or Alt+NumPadKey where X represents a letter, number, punctuation, or function key. If you specify an invalid form, Windows typically defaults to Ctrl+Alt Note that Windows distinguishes number pad keys from regular number and punctuation keys. FileCreateShortcut allows you to create Ctrl+X and Alt+X shortcuts (which Windows normally only allows when X is a NumPadKey); however, you should avoid these assignments as they may conflict with standard application hotkeys. Windows prohibits ESC, ENTER, TAB, SPACEBAR, PRINT SCREEN, SHIFT, or BACKSPACE from being used in hotkeys. FileCreateShortcut does not require a valid target, workdir, icon, or hotkey in order to "successfully" create the LNK file; however, the destination of the LNK file must be valid! If the hotkey you choose is already in use, your new shortcut takes precedence. Also, if you create a shortcut with the same path\name as as a pre-existing shortcut, it gets overwritten with your new version. Related FileGetShortcut, FileCreateNTFSLink Example Returns 1. Returns 0 if lnk cannot be created. Full path and file name of file to create shortcut to. Full path and file name of the shortcut. [optional] Working directory. [optional] Additional file arguments. [optional] File Description. [optional] Full Path/File name of icon to use. [optional] Hotkey - same as the Send() key format. [optional] The icon instance to use (usually 0) [optional] The state the shortcut is launched in. Use either @SW_SHOWNORMAL, @SW_SHOWMINNOACTIVE or @SW_SHOWMAXIMIZED

; Sets a shortcut with ctrl+alt+t hotkey FileCreateShortcut(@WindowsDir & "\Explorer.exe",@DesktopDir & "\Shortcut Test.lnk",@WindowsDir,"/e,c:\", "This is an Explorer link;-)", @SystemDir & "\shell32.dll", "^!t", "15", @SW_MINIMIZE)

Function Reference

FileDelete
Delete one or more files. FileDelete ( "path" ) Parameters Path Return Value Success: Failure: Remarks Note: If the "path" passed to FileDelete is a folder, the files therein will be deleted just as if you had used the *.* mask. See FileFindFirstFile for a discussion of wildcards. Some file attributes can make the deletion impossible. Related FileCopy, FileMove, FileRecycle, DirRemove, FileRecycleEmpty Example Return 1. Returns 0 if files are not deleted or do not exist. The path of the file(s) to delete. Wildcards are supported.

FileDelete("D:\*.tmp")

Function Reference

FileExists
Checks if a file or directory exists. FileExists ( "path" ) Parameters Path Return Value Success: Failure: Remarks FileExists returns 0 if you specify a floppy drive which does not contain a disk. Related FileGetAttrib, DriveStatus Example Returns 1. Returns 0 if path/file does not exist. The directory or file to check.

If FileExists("C:\autoexec.bat") Then MsgBox(4096, "C:\autoexec.bat File", "Exists") Else MsgBox(4096,"C:\autoexec.bat File", "Does NOT exists") EndIf If FileExists("C:\") Then MsgBox(4096, "C:\ Dir ", "Exists") Else MsgBox(4096,"C:\ Dir" , "Does NOT exists") EndIf If FileExists("D:") Then MsgBox(4096, "D: Drive", "Exists") Else MsgBox(4096,"D: Drive", "Does NOT exists") EndIf

Function Reference

FileFindFirstFile
Returns a search "handle" according to file search string. FileFindFirstFile ( "filename" ) Parameters filename Return Value Success: Failure: Remarks The search string is not case sensitive. Wildcards: In general, * denotes zero or more characters, and ? denotes zero or one character. If your file search string contains only wildcards (or is "*.*"), then see the example below for the return value! You can use only one wildcard in the filename part or in the extension part i.e. a*.b?. ?? seems equivalent to * (not described in Microsoft documentation). When using a 3-char extension any extension starting with those 3 chars will match, .e.g. "*.log" will match "test.log_1". (not described either in Microsoft documentation). When you have finished searching with the FileFind... functions you must call FileClose() to release the search handle. Directory name are return according to the wildcards if any. Related FileClose, FileFindNextFile Example Returns a search "handle" for use with subsequent FileFindNextFile functions. Returns -1 if error occurs. If the Folder is empty the @error is set to 1. File search string. (* and ? wildcards accepted)

; Shows the filenames of all files in the current directory. $search = FileFindFirstFile("*.*") ; Check if the search was successful If $search = -1 Then MsgBox(0, "Error", "No files/directories matched the search pattern") Exit EndIf While 1 $file = FileFindNextFile($search) If @error Then ExitLoop MsgBox(4096, "File:", $file) WEnd ; Close the search handle FileClose($search)

Function Reference

FileFindNextFile
Returns a filename according to a previous call to FileFindFirstFile. FileFindNextFile ( search ) Parameters search Return Value Success: Failure: Remarks A previous call to FileFindFirstFile is necessary to setup the search and get a search handle. Every subsequent call to FileFindNextFile will return the next file found according to the search string supplied to FileFindFirstFile. When @error = 1, no more files found matching the original search string. When you have finished searching with the FileFind... functions you must call FileClose() to release the search handle. Related FileClose, FileFindFirstFile Example Returns a filename according to a previous call to FileFindFirstFile, @extended set to 1 if filename is a directory. Sets @error to 1 if no more files/directories match the search. The search handle, as returned by FileFindFirstFile.

; Shows the filenames of all files in the current directory $search = FileFindFirstFile("*.*") ; Check if the search was successful If $search = -1 Then MsgBox(0, "Error", "No files/directories matched the search pattern") Exit EndIf While 1 $file = FileFindNextFile($search) If @error Then ExitLoop MsgBox(4096, "File:", $file) WEnd ; Close the search handle FileClose($search)

Function Reference

FileFlush
Flushes the file's buffer to disk. FileFlush ( handle ) Parameters handle Return Value Success: Failure: Remarks A file is flushed when it's handle is closed or when Windows internal buffer is full. This function forces an immediate flushing of the buffer. This function can only be used with file handles returned from FileOpen(). Related FileClose, FileOpen, FileWrite, FileWriteLine, FileSetPos Example Local Const $sFile = "test.txt" Local $hFile = FileOpen($sFile, 1) ; Check if file opened for writing OK If $hFile = -1 Then MsgBox(0, "Error", "Unable to open file.") Exit EndIf ; Write something to the file. FileWriteLine($hFile, "Line1") ; Run notepad to show that the file is empty because it hasn't been flushed yet. RunWait("notepad.exe " & $sFile) ; Flush the file to disk. FileFlush($hFile) ; Run notepad again to show that the contents of the file are now flushed to disk. RunWait("notepad.exe " & $sFile) ; Close the handle. FileClose($hFile) ; Clean up the temporary file. FileDelete($sFile) Returns true if the buffer was flushed (or did not need to be flushed). Returns false. A handle to a file previously opened with FileOpen().

Function Reference

FileGetAttrib
Returns a code string representing a file's attributes. FileGetAttrib ( "filename" ) Parameters filename Return Value Success: Failure: Remarks String returned could contain a combination of these letters "RASHNDOCT": "R" = READONLY "A" = ARCHIVE "S" = SYSTEM "H" = HIDDEN "N" = NORMAL "D" = DIRECT ORY "O" = OFFLINE "C" = COMPRESSED (NTFS compression, not ZIP compression) "T" = TEMPORARY Related FileGetTime, FileSetAttrib, FileExists, FileGetSize, FileSetTime Example Returns a code string representing a files attributes. Returns "" (blank string) and sets @error to 1. Filename (or directory) to check.

$attrib = FileGetAttrib("c:\boot.ini") If @error Then MsgBox(4096,"Error", "Could not obtain attributes.") Exit Else If StringInStr($attrib, "R") Then MsgBox(4096,"", "File is read-only.") EndIf EndIf ; Display full attribute information in text form ; Arrays rely upon the fact that each capital letter is unique ; Figuring out how this works is a good string exercise... $input = StringSplit("R,A,S,H,N,D,O,C,T",",") $output = StringSplit("Read-only /, Archive /, System /, Hidden /" & _ ", Normal /, Directory /, Offline /, Compressed /, Temporary /", ",") For $i = 1 to 9 $attrib = StringReplace($attrib, $input[$i], $output[$i], 0, 1) ; last parameter in StringReplace means case-sensitivity Next $attrib = StringTrimRight($attrib, 2) ;remove trailing slash MsgBox(0,"Full file attributes:", $attrib)

Function Reference

FileGetEncoding
Determines the text encoding used in a file. FileGetEncoding ( "filehandle/filename" [, mode] ) Parameters filehandle/filename mode Return Value Success: Returns the file encoding using similar values to the FileOpen function: 0 = ANSI 32 = UTF16 Little Endian. 64 = UTF16 Big Endian. 128 = UTF8 (with BOM). 256 = (without BOM). Failure: Remarks If a filename is given rather than a file handle - the file will be opened and closed during the function call. Note: Do not mix filehandles and filenames, i.e., don't FileOpen a file and then use a filename in this function. Use either filehandles or filenames in your routines, not both! If a file handle is used then the "mode" parameter has no effect - the mode used for FileOpen takes precedence. Related FileOpen, FileRead, FileReadLine, FileWrite, FileWriteLine Returns -1. The handle of a file, as returned by a previous call to FileOpen. Alternatively you may use a string filename as the first parameter. [optional] The UTF8 detection mode to use. 1 = Check entire file for UTF8 sequences (default) 2 = Check first part of file for UTF8 sequences (the same as FileOpen uses by default)

Function Reference

FileGetLongName
Returns the long path+name of the path+name passed. FileGetLongName ( "file" [, flag] ) Parameters file flag Return Value Success: Failure: Remarks None. Related FileGetShortName Example Returns the long path+name of the path+name passed. Returns the parameter and sets @error to 1. full path and file name to convert [optional] if 1 file can have relative dir, e.g. "..\file.txt"

$a = FileGetLongName(@HomeDrive & "\PROGRA~1\") msgbox(0,"long file name", $a) ;$a is probably "x:\Program Files"

Function Reference

FileGetPos
Retrieves the current file position. FileGetPos ( handle ) Parameters handle Return Value Success: Failure: Remarks Failure returns 0 but 0 is also a valid file position so check @error to determine error conditions. Related FileSetPos, FileRead, FileReadLine, FileWrite, FileWriteLine, FileOpen Example Returns the position offset from the beginning of the file (First index is 0). Returns 0 and sets @error. A handle to a file previously opened with FileOpen().

#include <Constants.au3> Local Const $sFile = "test.txt" Local $hFile = FileOpen($sFile, 2) ; Check if file opened for writing OK If $hFile = -1 Then MsgBox(0, "Error", "Unable to open file.") Exit EndIf ; Write something to the file. FileWriteLine($hFile, "Line1") FileWriteLine($hFile, "Line2") FileWriteLine($hFile, "Line3") ; Flush the file to disk. FileFlush($hFile) ; Check file position and try to read contents for current position. MsgBox(0, "", "Position: " & FileGetPos($hFile) & @CRLF & "Data: " & @CRLF & FileRead ($hFile)) ; Now, adjust the position to the beginning. Local $n = FileSetPos($hFile, 0, $FILE_BEGIN) ; Check file position and try to read contents for current position. MsgBox(0, "", "Position: " & FileGetPos($hFile) & @CRLF & "Data: " & @CRLF & FileRead ($hFile)) ; Close the handle. FileClose($hFile)

; Clean up the temporary file. FileDelete($sFile)

Function Reference

FileGetShortcut
Retrieves details about a shortcut. FileGetShortcut ( "lnk" ) Parameters lnk Return Value Success: Failure: Remarks The array returned from this function is a single dimension array containing the following elements: $array[0] = Shortcut target path $array[1] = Working direc tory $array[2] = Arguments $array[3] = Desc ription $array[4] = Ic on filename $array[5] = Ic on index $array[6] = The shortcut state (@SW_SHOWNORMAL, @SW_SHOWMINNOACTIVE, @SW_SHOWMAXIMIZED) Related FileCreateShortcut Example Returns an array that contains the shortcut information. See Remarks. Sets @error to 1 if the shortcut could not be accessed. Full path and file name of the shortcut.

; Sets a shortcut with ctrl+alt+t hotkey FileCreateShortcut(@WindowsDir & "\Explorer.exe",@DesktopDir & "\Shortcut Test.lnk",@WindowsDir,"/e,c:\", "This is an Explorer link;-)", @SystemDir & "\shell32.dll", "^!t", "15", @SW_MINIMIZE) ; Read in the path of a shortcut $details = FileGetShortcut(@DesktopDir & "\Shortcut Test.lnk") MsgBox(0, "Path:", $details[0])

Function Reference

FileGetShortName
Returns the 8.3 short path+name of the path+name passed. FileGetShortName ( "file" [, flag] ) Parameters file flag Return Value Success: Failure: Remarks The file need to exist as there is no way to known the exact ~i if several file have the same 8 first characters. Related FileGetLongName Example Returns the 8.3 short path+name of the path+name passed. Returns the parameter and sets @error to 1. full path and file name to convert [optional] if 1 file can have relative dir, e.g. "..\file.txt"

$a = FileGetShortName(@HomeDrive & "\Program Files") msgbox(0,"long file name", $a) ;$a is probably "x:\PROGRA~1"

Function Reference

FileGetSize
Returns the size of a file in bytes. FileGetSize ( "filename" ) Parameters filename Return Value Success: Failure: Remarks Does not work on directories. Divide result by 1024 to get kilobyte equivalent, or divide by 1048576 to get megabyte equivalent. Related FileGetAttrib, FileGetTime, DriveSpaceTotal, FileGetVersion Example Returns the size of the file in bytes. Returns 0 and set the @error to 1. Filename to check.

$size = FileGetSize("AutoIt.exe")

Function Reference

FileGetTime
Returns the time and date information for a file. FileGetTime ( "filename" [, option [, format]] ) Parameters filename option Filename to check. [optional] Flag to indicate which timestamp 0 = Modified (default) 1 = Created 2 = Accessed [optional] to specify type of return 0 = return an array (default) 1 = return a string YYYYMMDDHHMMSS

format Return Value Success: Failure: Remarks

Returns an array or string that contains the file time information. See Remarks. Returns 0 and sets @error to 1.

The array is a single dimension array containing six elements: $array[0] = year (four digits) $array[1] = month (range 01 - 12) $array[2] = day (range 01 - 31) $array[3] = hour (range 00 - 23) $array[4] = min (range 00 - 59) $array[5] = sec (range 00 - 59) Notice that return values are zero-padded. Related FileGetSize, FileGetAttrib, FileGetVersion, FileSetTime, FileSetAttrib Example

$t = FileGetTime(@Windowsdir & "\Notepad.exe", 1) If Not @error Then $yyyymd = $t[0] & "/" & $t[1] & "/" & $t[2] MsgBox(0, "Creation date of notepad.exe", $yyyymd) EndIf

Function Reference

FileGetVersion
Returns the "File" version information. FileGetVersion ( "filename" [,"stringname"] ) Parameters filename stringname Return Value Success: Failure: Remarks stringname can be the basic one as : Comments, InternalName, ProductName, CompanyName, LegalCopyright, ProductVersion, FileDesc ription, LegalTrademarks, PrivateBuild, FileVersion, OriginalFilename, Spec ialBuild Or a special one "CompiledScript" which is set for a compiled script. FileGetVersion(@AutoItExe, "CompiledScript") will return "AutoIt v3 Script : 3, 2, 1, 2". Another special stringname is "DefaultLangCodepage" can be used to retrieve the default language and codepage. The language and codepage can be used if needed to differentiate the "stringname" i.e. "080904b0 \Comments" (see MSDN StringFileInfo in VerQueryValue function). Related FileGetSize, FileGetTime Example Returns a string containing the version information, e.g. "3.0.81.0". Returns "0.0.0.0" if no version information (or other error) or "" when retrieving a stringname, and sets @error to 1. Filename to check. [optional] name of the field to be retrieved from the header version file info.

$ver = FileGetVersion("Explorer.exe") MsgBox(0, "Explorer version", $ver)

Function Reference

FileInstall
Include and install a file with the compiled script. FileInstall ( "source", "dest" [, flag] ) Parameters source dest flag Return Value Success: Failure: Remarks The FileInstall function is designed to include files into a compiled AutoIt script. These included files can then be "extracted" during execution of the compiled script if the statement is executed. Keep in mind that files such as images can greatly increase the size of a compiled script. The source file must be specified using a string literal and can not be a variable, a calculation nor function call. The file must be able to be found during compiling, however variables, calculations and function calls do not get resolved until the script itself is running, long after compiling, making them unsuitable to define the source file. The source cannot contain wildcards. When this function is used from a non-compiled script, a copy operation is performed instead (to allow for easy testing pre-c ompilation). Files maintain their original creation/modification timestamps when installed. The destination directory path must already exist before this function is called, or the FileInstall will fail, returning 0 and not creating the file, nor path. See DirCreate() for information about creating the directory path. The file attributes on an existing file may prevent the file from being overwritten. Use FileDelete() or FileSetAttrib() to ensure the file can be installed without issue. Related DirCreate, FileDelete, FileSetAttrib Example Returns 1. Returns 0. The source path of the file to compile. This must be a literal string; it cannot be a variable or the result of a function call. It can be a relative path (using .\ or ..\ in the path) to the source file (.au3). The destination path of the file with trailing backslash if only the directory is used. This can be a variable. [optional] this flag determines whether to overwrite files if they already exist: 0 = (default) do not overwrite existing files 1 = overwrite existing files

; Include a bitmap found in "C:\test.bmp" with the compiled program and put it in "D:\mydir\test.bmp" when it is run $b = True If $b = True Then FileInstall("C:\test.bmp", "D:\mydir\test.bmp")

Function Reference

FileMove
Moves one or more files FileMove ( "source", "dest" [, flag] ) Parameters source dest The source path and filename of the file to move. (* wildcards are supported) The destination path and filename of the moved file. (* wildcards are supported) [optional] this flag determines whether to overwrite files if they already exist: Can be a combination of the following: 0 = (default) do not overwrite existing files 1 = overwrite existing files 8 = Create destination directory structure if it doesn't exist (See Remarks).

flag

Return Value Success: Failure: Remarks If the source and destination paths are on different volumes a copy and delete operation is performed rather than a move. Because AutoIt lacks a "FileRename" function, use FileMove to rename a file! The destination directory must already exist, except using with flag value '8'. For instance the combined flag '9' (1 + 8) overwrites the target file and prechecks for the destination directory structure and if it doesn't exist creates it automatically. Some file attributes can make the overwriting impossible. Related FileCopy, FileDelete, FileRecycle, DirMove Example Returns 1. Returns 0 if source cannot be moved or if dest already exists and flag=0.

FileMove("C:\foo.au3", "D:\mydir\bak.au3") ; Second example: ; uses flags '1' (owerwriting) and '8' (autocreating target dir structure) together ; moves all txt-files from temp to txtfiles and prechecks if ; target directory structure exists, if not then automatically creates it FileMove(@TempDir & "\*.txt", @TempDir & "\TxtFiles\", 9)

Function Reference

FileOpen
Opens a text file for reading or writing. FileOpen ( "filename" [, mode ] ) Parameters filename Filename of the text file to open. [optional] Mode to open the file in. Can be a combination of the following: 0 = Read mode (default) 1 = Write mode (append to end of file) 2 = Write mode (erase previous contents) 8 = Create directory structure if it doesn't exist (See Remarks). 16 = Force binary mode (See Remarks). 32 = Use Unicode UTF16 Little Endian reading and writing mode. Reading does not override existing BOM. 64 = Use Unicode UTF16 Big Endian reading and writing mode. Reading does not override existing BOM. 128 = Use Unicode UTF8 (with BOM) reading and writing mode. Reading does not override existing BOM. 256 = Use Unicode UTF8 (without BOM) reading and writing mode. 16384 = When opening for reading and no BOM is present, use full file UTF8 detection. If this is not used then only the initial part of the file is checked for UTF8. The folder path must already exist (except using mode '8' - See Remarks).

mode

Return Value Success: Failure: Remarks Returns a file "handle" for use with subsequent file functions. Returns -1 if error occurs.

The file handle must be closed with the FileClose() function. A file may fail to open due to access rights or attributes. The default mode when writing text is ANSI - use the unicode flags to change this. When writing unicode files the Windows default mode (and the fastest in AutoIt due to the least conversion) is UTF16 Little Endian (mode 32). Opening a file in write mode creates the file if it does not exist. Directories are not created unless the correct flag is used. When reading and writing via the same file handle, the FileSetPos() function must be used to update the current file position.

Related FileClose, FileFlush, FileRead, FileReadLine, FileWrite, FileWriteLine, FileGetPos, FileSetPos Example

$file = FileOpen("test.txt", 0) ; Check if file opened for reading OK

If $file = -1 Then MsgBox(0, "Error", "Unable to open file.") Exit EndIf FileClose($file)

; Another sample which automatically creates the directory structure $file = FileOpen("test.txt", 10) ; which is similar to 2 + 8 (erase + create dir) If $file = -1 Then MsgBox(0, "Error", "Unable to open file.") Exit EndIf FileClose($file)

Function Reference

FileOpenDialog
Initiates a Open File Dialog. FileOpenDialog ( "title", "init dir", "filter" [, options [, "default name" [, hwnd]]] ) Parameters title init dir filter Title text of the Dialog GUI. Initial directory selected in the GUI file tree. File type single filter such as "All (*.*)" or "Text files (*.txt)" or multiple filter groups such as "All (*.*)|Text files (*.txt)" (See Remarks). [optional] Dialog Options: To use more than one option, add the required values together. 1 = File Must Exist (if user types a filename) 2 = Path Must Exist (if user types a path, ending with a backslash) 4 = Allow MultiSelect 8 = Prompt to Create New File (if does not exist) [optional] Suggested file name for the user to open. Default is blank (""). [optional] The window handle to use as the parent for this dialog.

options

default name hwnd Return Value Success: Failure: @error: Remarks

Returns the full path of the file(s) chosen. Results for multiple selections are "Directory|file1|file2|..." Sets @error 1 - File selection failed. 2 - Bad file filter

Separate the file filters with a semicolon as shown in the example. Multiple groups of filters are separated by a pipe "|". If default name is given, options must also be given. If none of the options are wanted, use 0 for options. Special Windows folders (such as "My Documents") can sometimes be set as the init dir; see Appendix. @WorkingDir is changed on successful return. Related FileSaveDialog, FileSelectFolder, StringSplit Example $message = "Hold down Ctrl or Shift to choose multiple files." $var = FileOpenDialog($message, @WindowsDir & "\", "Images (*.jpg;*.bmp)", 1 + 4 ) If @error Then MsgBox(4096,"","No File(s) chosen") Else $var = StringReplace($var, "|", @CRLF) MsgBox(4096,"","You chose " & $var) EndIf

; Multiple filter group $message = "Hold down Ctrl or Shift to choose multiple files." $var = FileOpenDialog($message, @WindowsDir & "", "Images (*.jpg;*.bmp)|Videos (*.avi;*.mpg)", 1 + 4 ) If @error Then MsgBox(4096,"","No File(s) chosen") Else $var = StringReplace($var, "|", @CRLF) MsgBox(4096,"","You chose " & $var) EndIf

Function Reference

FileRead
Read in a number of characters from a previously opened text file. FileRead ( "filehandle/filename" [, count] ) Parameters filehandle/filename count Return Value Success: Special: Failure: Remarks If a filename is given rather than a file handle - the file will be opened and closed during the function call - for parsing large text files this will be much slower than using filehandles. Note: Do not mix filehandles and filenames, i.e., don't FileOpen a file and then use a filename in this function. Use either filehandles or filenames in your routines, not both! Both ANSI and UTF16/UTF8 text formats can be read - AutoIt will automatically determine the type. A file can be read as binary(byte) data by using FileOpen with the binary flag - in this case count is in bytes rather than characters. Related FileOpen, FileReadLine, FileWrite, FileWriteLine, String, FileSetPos, FileGetPos Example Returns the binary/string read. @extended is set to the number of bytes/characters returned. Sets @error to -1 if end-of-file is reached. Sets @error to 1 if file not opened in read mode or other error. The handle of a file, as returned by a previous call to FileOpen. Alternatively you may use a string filename as the first parameter. [optional] The number of characters to read. Default read the entire file.

$file = FileOpen("test.txt", 0) ; Check if file opened for reading OK If $file = -1 Then MsgBox(0, "Error", "Unable to open file.") Exit EndIf ; Read in 1 character at a time until the EOF is reached While 1 $chars = FileRead($file, 1) If @error = -1 Then ExitLoop MsgBox(0, "Char read:", $chars) Wend FileClose($file)

Function Reference

FileReadLine
Read in a line of text from a previously opened text file. FileReadLine ( "filehandle/filename" [, line] ) Parameters filehandle/filename line Return Value Success: Special: Failure: Remarks Returns the text of the line read, any newline characters ( CHR(10) or @LF ) at the end of a line read in are automatically stripped. If no line number to read is given, the "next" line will be read. ("Next" for a newly opened file is initially the first line.) If a filename is given rather than a file handle - the file will be opened and closed during the function call - for parsing large text files this will be much slower than using filehandles. Note: Do not mix filehandles and filenames, i.e., don't FileOpen a file and then use a filename in this function. Use either filehandles or filenames in your routines, not both! From a performance standpoint it is a bad idea to read line by line specifying "line" parameter whose value is incrementing by one. This forces AutoIt to reread the file from the beginning until it reach the specified line. Both ANSI and UTF16/UTF8 text formats can be read - AutoIt will automatically determine the type. Related IniRead, FileOpen, FileRead, FileWrite, FileWriteLine, FileSetPos, FileGetPos Example Returns a line of text. Sets @error to -1 if end-of-file is reached. Sets @error to 1 if file not opened in read mode or other error. The handle of a file, as returned by a previous call to FileOpen. Alternatively you may use a string filename as the first parameter. [optional] The line number to read. The first line of a text file is line 1 (not zero), last line is -1.

$file = FileOpen("test.txt", 0) ; Check if file opened for reading OK If $file = -1 Then MsgBox(0, "Error", "Unable to open file.") Exit EndIf ; Read in lines of text until the EOF is reached While 1 $line = FileReadLine($file) If @error = -1 Then ExitLoop MsgBox(0, "Line read:", $line) Wend FileClose($file)

Function Reference

FileRecycle
Sends a file or directory to the recycle bin. FileRecycle ( "source" ) Parameters source Return Value Success: Failure: Remarks See FileFindFirstFile for a discussion of wildcards. To remove a directory, simply give the path without a trailing backslash. Related FileDelete, FileRecycleEmpty, DirRemove, FileMove Example Returns 1. Returns 0 (typically meaning the file is in use or does not exist). The source path of the file(s) or directory to Recycle. Wildcards are supported.

FileRecycle("C:\*.tmp")

Function Reference

FileRecycleEmpty
Empties the recycle bin. FileRecycleEmpty ( ["source"] ) Parameters source Return Value Success: Failure: Remarks For this function to work IE4+ must be available. Related FileDelete, FileRecycle Example Returns 1. Returns 0 (the recycle bin cannot be emptied - see below). [optional] The rootpath to empty - if omitted the recycle bin for all drives is emptied.

FileRecycleEmpty("C:\")

Function Reference

FileSaveDialog
Initiates a Save File Dialog. FileSaveDialog ( "title", "init dir", "filter" [, options [, "default name" [, hwnd]]] ) Parameters title init dir filter options default name hwnd Return Value Success: Failure: @error: Remarks Separate the file filters with a semicolon as shown in the example. Multiple groups of filters are separated by a pipe "|". If default name is given, options must also be given. If none of the options are wanted, use 0 for options. Special Windows folders (such as "My Documents") can sometimes be set as the init dir; see Appendix. @WorkingDir is changed on successful return. Related FileOpenDialog, FileSelectFolder Example $MyDocsFolder = "::{450D8FBA-AD25-11D0-98A8-0800361B1103}" $var = FileSaveDialog( "Choose a name.", $MyDocsFolder, "Scripts (*.aut;*.au3)", 2) ; option 2 = dialog remains until valid path/file selected If @error Then MsgBox(4096,"","Save cancelled.") Else MsgBox(4096,"","You chose " & $var) EndIf Returns the full path of the file chosen. Results for multiple selections are "Directory|file1|file2|..." Sets @error 1 - File selection failed. 2 - Bad file filter Title text of the Dialog GUI. Initial directory selected in the GUI file tree. File type single filter such as "All (*.*)" or "Text files (*.txt)" or multiple filter groups such as "All (*.*)|Text files (*.txt)" (See Remarks). [optional] 2 = Path Must Exist (if user types a path, ending with a backslash) 16 = Prompt to OverWrite File [optional] File name to suggest to the user to save the file with. Default is blank (""). [optional] The window handle to use as the parent for this dialog.

; Multiple filter group $var = FileSaveDialog( "Choose a name.", $MyDocsFolder, "Scripts (*.aut;*.au3)|Text files

(*.ini;*.txt)", 2) ; option 2 = dialog remains until valid path/file selected If @error Then MsgBox(4096,"","Save cancelled.") Else MsgBox(4096,"","You chose " & $var) EndIf

Function Reference

FileSelectFolder
Initiates a Browse For Folder dialog. FileSelectFolder ( "dialog text", "root dir" [, flag [, "initial dir" [, hwnd]]] ) Parameters dialog text root dir flag initial dir hwnd Return Value Success: Failure: Remarks The root dir will be chosen if the initial dir (if given) does not exist. A nonexistent root dir will also cause the Desktop folder to be root. The "Create Folder Button" option may require Windows XP with IE6 in order to work. Special Windows folders (such as "My Documents") can be set as root by using the right CLSID detailed in the Appendix. UNC paths are not supported. If you think that user's may choose files on a UNC path then the path needs to be mapped as a drive first. Related FileSaveDialog, FileOpenDialog Example Returns full path of the folder chosen. Returns "" (blank string) and sets @error to 1 if user cancels/closes the window. Text greeting in dialog. Root directory of GUI file tree. Use "" for Desktop to be root. [optional] 1 = Show Create Folder Button (requires IE6.0 or later) 2 = Use New Dialog Style (requires IE5.0 or later) 4 = Show Edit Control (to type a foldername) [optional] Initial/start directory that will be selected if exist. Default is blank (""). [optional] The window handle to use as the parent for this dialog.

$var = FileSelectFolder("Choose a folder.", "")

Function Reference

FileSetAttrib
Sets the attributes of one or more files. FileSetAttrib ( "file pattern", "+-RASHNOT" [, recurse] ) Parameters file pattern +-RASHNOT recurse Return Value Success: Failure: Remarks The file pattern cannot contain spaces! The attributes that can be modified with the function are + or -: "R" = READONLY "A" = ARCHIVE "S" = SYSTEM "H" = HIDDEN "N" = NORMAL "O" = OFFLINE "T" = TEMPORARY (Note that you cannot set the compressed/directory attributes with this function.) Related FileGetAttrib, FileGetTime, FileSetTime Example Returns 1. Returns 0 if encountered any errors. File(s) to change, e.g. C:\*.au3, C:\Dir Attribute(s) to set/clear. e.g. "+A", "+RA-SH" [optional] If this is set to 1, then directories are recursed into. Default is 0 (no recursion).

;mark all .au3 files in current directory as read-only and system If Not FileSetAttrib("*.au3", "+RS") Then MsgBox(4096,"Error", "Problem setting attributes.") EndIf ;make all .bmp files in C:\ and sub-directories writable and archived If Not FileSetAttrib("C:\*.bmp", "-R+A", 1) Then MsgBox(4096,"Error", "Problem setting attributes.") EndIf

Function Reference

FileSetPos
Sets the current file position. FileSetPos ( handle, offset, origin ) Parameters handle offset A handle to a file previously opened with FileOpen(). The offset to move from the origin. This value may be positive or negative. Negative values move backwards from the origin. Must be one of the following: 0 - Beginning of the file ($FILE_BEGIN from Constants.au3). 1 - Current position ($FILE_CURRENT from Constants.au3). 2 - End of the file ($FILE_END from Constants.au3).

origin

Return Value Success: Failure: Remarks Include Constants.au3 in your script to use the symbolic name in parentheses to specify the origin. Using FileSetPos() it is possible to both read and write to the same file. When attempting to read and write to the same file, always call FileFlush() between each write and read operation. Moving the pointer to the middle of the data can be used to overwrite data. Related FileGetPos, FileFlush, FileRead, FileReadLine, FileWrite, FileWriteLine, FileOpen Example True if the operation succeeded. False.

#include <Constants.au3> Local Const $sFile = "test.txt" Local $hFile = FileOpen($sFile, 2) ; Check if file opened for writing OK If $hFile = -1 Then MsgBox(0, "Error", "Unable to open file.") Exit EndIf ; Write something to the file. FileWriteLine($hFile, "Line1") FileWriteLine($hFile, "Line2") FileWriteLine($hFile, "Line3") ; Flush the file to disk. FileFlush($hFile) ; Check file position and try to read contents for current position. MsgBox(0, "", "Position: " & FileGetPos($hFile) & @CRLF & "Data: " & @CRLF & FileRead ($hFile))

; Now, adjust the position to the beginning. Local $n = FileSetPos($hFile, 0, $FILE_BEGIN) ; Check file position and try to read contents for current position. MsgBox(0, "", "Position: " & FileGetPos($hFile) & @CRLF & "Data: " & @CRLF & FileRead ($hFile)) ; Close the handle. FileClose($hFile) ; Clean up the temporary file. FileDelete($sFile)

Function Reference

FileSetTime
Sets the timestamp of one of more files. FileSetTime ( "file pattern", "time" [, type [, recurse] ] ) Parameters file pattern time type recurse Return Value Success: Failure: Remarks Using a date earlier than 1980-01-01 will have no effect. Trying to change a timestamp on read-only files will result in a error. Related FileGetTime, FileGetAttrib, FileSetAttrib Example Returns 1. Returns 0 if error changing timestamp(s). File(s) to change, e.g. C:\*.au3, C:\Dir The new time to set in the format "YYYYMMDDHHMMSS" (Year, month, day, hours (24hr clock), seconds). If the time is blank "" then the current time is used. [optional] The timestamp to change: 0 = Modified (default), 1 = Created, 2 = Accessed [optional] If this is set to 1, then directories are recursed into. Default is 0 (no recursion).

;change file.au3's "modified" timestamp to 1st Nov 2003 and current time $var = FileSetTime("file.au3", "20031101")

Function Reference

FileWrite
Append a text/data to the end of a previously opened file. FileWrite ( "filehandle/filename", "text/data" ) Parameters filehandle/filename text/data Return Value Success: Failure: Remarks The file must be opened in write mode or the FileWrite command will fail. If a filename is given rather than a file handle, the file will be opened and closed during the function call. For parsing large text files this will be much slower than using filehandles. However, filename will be created if it does not already exist. Note: Do not mix filehandles and filenames, i.e., don't FileOpen a file and then use a filename in this function. Either use filehandles or filenames in your routines, not both. When writing text AutoIt will write using ANSI by default. To write in Unicode mode the file must be opened with FileOpen() and the relevant flags. If the data is a binary type variant (and not text) it will be written to the file byte by byte. Binary operation can also be forced by using Fileopen with the binary flag. Related FileFlush, FileOpen, FileRead, FileReadLine, FileWriteLine, Binary, FileSetPos, FileGetPos Example Returns 1. Returns 0 if file not opened in writemode, file is read only, or file cannot otherwise be written to. The handle of a file, as returned by a previous call to FileOpen. Alternatively, you may use a string filename as the first parameter. The text/data to write to the file. The text is written as is - no @CR or @LF characters are added. See remark for data type.

$file = FileOpen("test.txt", 1) ; Check if file opened for writing OK If $file = -1 Then MsgBox(0, "Error", "Unable to open file.") Exit EndIf FileWrite($file, "Line1") FileWrite($file, "Still Line1" & @CRLF) FileWrite($file, "Line2") FileClose($file)

Function Reference

FileWriteLine
Append a line of text to the end of a previously opened text file. FileWriteLine ( "filehandle/filename", "line" ) Parameters filehandle/filename line Return Value Success: Failure: Remarks The text file must be opened in write mode or the FileWriteLine command will fail. If a filename is given rather than a file handle, the file will be opened and closed during the function call. For parsing large text files this will be much slower than using filehandles. However, filename will be created if it does not already exist. Note: Do not mix filehandles and filenames, i.e., don't FileOpen a file and then use a filename in this function. Either use filehandles or filenames in your routines, not both. When writing text AutoIt will write using ANSI by default. To write in Unicode mode the file must be opened with FileOpen() and the relevant flags. The text to write cannot contain Chr(0) characters as the output is truncated. FileWrite() using a file opened in binary mode must be used to write such characters. Related FileFlush, FileOpen, FileRead, FileReadLine, FileWrite, FileSetPos, FileGetPos Example Returns 1. Returns 0 if file not opened in writemode, file is read only, or file cannot otherwise be written to. The handle of a file, as returned by a previous call to FileOpen. Alternatively, you may use a string filename as the first parameter. The line of text to write to the text file. If the line does NOT end in @CR or @LF then a DOS linefeed (@CRLF) will be automatically added.

$file = FileOpen("test.txt", 1) ; Check if file opened for writing OK If $file = -1 Then MsgBox(0, "Error", "Unable to open file.") Exit EndIf FileWriteLine($file, "Line1") FileWriteLine($file, "Line2" & @CRLF) FileWriteLine($file, "Line3") FileClose($file)

Function Reference

IniDelete
Deletes a value from a standard format .ini file. IniDelete ( "filename", "section" [, "key"] ) Parameters filename section key Return Value Success: Failure: Remarks A standard ini file looks like: [SectionName] Key=Value Related IniRead, IniWrite, IniReadSection, IniReadSec tionNames, IniRenameSec tion, IniWriteSection Example Returns 1. Returns 0 if the INI file does not exist or if the file is read-only. The filename of the .ini file. The section name in the .ini file. [optional] The key name in the .ini file to delete. If the key name is not given the entire section is deleted. The Default keyword may also be used which will cause the section to be deleted.

IniDelete("C:\Temp\myfile.ini", "section2", "key")

Function Reference

IniRead
Reads a value from a standard format .ini file. IniRead ( "filename", "section", "key", "default" ) Parameters filename section key default Return Value Success: Failure: Remarks A standard ini file looks like: [SectionName] Key=Value Related IniDelete, IniWrite, FileReadLine, IniReadSection, IniReadSec tionNames, IniRenameSec tion, IniWriteSection Example Returns the requested key value. Returns the default string if requested key not found. The filename of the .ini file. The section name in the .ini file. The key name in the in the .ini file. The default value to return if the requested key is not found.

$var = IniRead("C:\Temp\myfile.ini", "section2", "key", "NotFound") MsgBox(4096, "Result", $var)

Function Reference

IniReadSection
Reads all key/value pairs from a section in a standard format .ini file. IniReadSection ( "filename", "section" ) Parameters filename section Return Value Success: Failure: Remarks A standard ini file looks like: [SectionName] Key=Value The number of elements returned will be in $result[0][0]. If an @error occurs, no array is created. Only the first 32767 chars are taken in account in an section due to Win9x compatibility. Related IniDelete, IniWrite, IniRead, IniReadSec tionNames, IniRenameSec tion, IniWriteSection Example Returns a 2 dimensional array where element[n][0] is the key and element[n][1] is the value. Sets @error=1 if unable to read the section (The INI file may not exist or the section may not exist) The filename of the .ini file. The section name in the .ini file.

$var = IniReadSection("C:\Temp\myfile.ini", "section2") If @error Then MsgBox(4096, "", "Error occurred, probably no INI file.") Else For $i = 1 To $var[0][0] MsgBox(4096, "", "Key: " & $var[$i][0] & @CRLF & "Value: " & $var[$i][1]) Next EndIf

Function Reference

IniReadSectionNames
Reads all sections in a standard format .ini file. IniReadSectionNames ( "filename" ) Parameters filename Return Value Success: Failure: Remarks A standard ini file looks like: [SectionName] Key=Value The number of elements returned will be in $result[0]. If an @error occurs, no array is created. Only the first 32767 chars are taken in account in an section due to Win9x compatibility. Related IniDelete, IniWrite, IniRead, IniReadSection, IniRenameSec tion, IniWriteSection Example Returns an array of all section names in the INI file. Sets @error on failure. The filename of the .ini file.

$var = IniReadSectionNames(@WindowsDir & "\win.ini") If @error Then MsgBox(4096, "", "Error occurred, probably no INI file.") Else For $i = 1 To $var[0] MsgBox(4096, "", $var[$i]) Next EndIf

Function Reference

IniRenameSection
Renames a section in a standard format .ini file. IniRenameSection ( "filename", "section", "new section" [, flag] ) Parameters filename section new section flag Return Value Success: Failure: Remarks A standard ini file looks like: [SectionName] Key=Value Related IniRead, IniDelete, IniWrite, IniReadSection, IniReadSec tionNames, IniWriteSection Example Non-zero. 0 and may set @error if the section couldn't be overwritten (flag = 0 only). The filename of the .ini file. The section name in the .ini file. The new section name. [optional] 0 (Default) - Fail if "new section" already exists. 1 - Overwrite "new section". This will erase any existing keys in "new section"

$res = IniRenameSection(@ScriptDir & "My.ini", "MySection", "MyNewSection")

Function Reference

IniWrite
Writes a value to a standard format .ini file. IniWrite ( "filename", "section", "key", "value" ) Parameters filename section key value Return Value Success: Failure: Remarks A standard ini file looks like: [SectionName] Key=Value If file does not exist, it is created. Any directories that do not exist, will not be created. Keys and/or sections are added to the end and are not sorted in any way."? When writing a value that is quoted, the quotes are stripped. In order to write the quote marks to the value, you must double up the quoting. For example: ""This is a test"" will produce "This is a test" in the file. Leading and trailing whitespace is stripped. In order to preserve the whitespace, the string must be quoted. For example, " this is a test" will preserve the whitespace but per above, the quotation marks are stripped. Multi-line values are not possible. Related IniDelete, IniRead, IniReadSection, IniReadSec tionNames, IniWriteSection, IniRenameSec tion Example Returns 1. Returns 0 if file is read-only. The filename of the .ini file. The section name in the .ini file. The key name in the in the .ini file. The value to write/change.

IniWrite("C:\Temp\myfile.ini", "section2", "key", "this is a new value")

Function Reference

IniWriteSection
Writes a section to a standard format .ini file. IniWriteSection ( "filename", "section", "data" [, index ] ) Parameters filename section data The filename of the .ini file. The section name in the .ini file. The data to write. The data can either be a string or an array. If the data is a string, then each key=value pair must be delimited by @LF. If the data is an array, the array must be 2dimensional and the second dimension must be 2 elements. [optional] If an array is passed as data, this specifies the index to start writing from. By default, this is 1 so that the return value of IniReadSection() can be used immediately. For manually created arrays, this value may need to be different depending on how the array was created. This parameter is ignored if a string is passed as data.

index

Return Value Success: Failure: Remarks A standard ini file looks like: [SectionName] Key=Value If file does not exist, it is created. Any directories that do not exist, will not be created. Keys and/or sections are added to the end and are not sorted in any way."? If the section being written already exists, it's contents will be overwritten. Related IniDelete, IniRead, IniReadSection, IniReadSec tionNames, IniWrite, IniRenameSec tion Example Returns 1. Returns 0. The function will set @error to 1 if the data format is invalid.

; This is the INI file we will write to. It will be created on the Desktop. $sIni = @DesktopDir & "\AutoIt-Test.ini" ; Demonstrate creating a new section using a string as input. $sData = "Key1=Value1" & @LF & "Key2=Value2" & @LF & "Key3=Value3" IniWriteSection($sIni, "Section1", $sData) ; Demonstrate creating a new section using an array as input. $aData1 = IniReadSection($sIni, "Section1"); Read in what we just wrote above. For $i = 1 To UBound($aData1) - 1 $aData1[$i][1] &= "-" & $i ; Change the data some Next IniWriteSection($sIni, "Section2", $aData1); Write to a new section. ; Demonstrate creating an array manually and using it as input. Dim $aData2[3][2] = [ [ "FirstKey", "FirstValue" ], [ "SecondKey", "SecondValue" ], [ "ThirdKey", "ThirdValue" ] ]

; Since the array we made starts at element 0, we need to tell IniWriteSection() to start writing from element 0. IniWriteSection($sIni, "Section3", $aData2, 0)

Graphic and Sound functions Reference


Below is a complete list of the functions available in AutoIt. Click on a function name for a detailed description. Function Beep PixelChec ksum PixelGetColor PixelSearch SoundPlay SoundSetWaveVolume Description Plays back a beep to the user. Generates a checksum for a region of pixels. Returns a pixel color according to x,y pixel coordinates. Searches a rectangle of pixels for the pixel color provided. Play a sound file. Sets the system wave volume by percent.

Function Reference

Beep
Plays back a beep to the user. Beep ( [ Frequency [, Duration ]] ) Parameters Frequency Duration Return Value Always returns 1 regardless of success. Remarks None. Related SoundPlay Example [optional] The frequency of the beep in hertz. Can be anywhere from 37 through 32,767 (0x25 through 0x7FFF). Default is 500 Hz. [optional] The length of the beep in milliseconds. Default = 1000 ms.

; plays back a beep noise, at the frequency 500 for 1 second Beep(500, 1000)

Function Reference

PixelChecksum
Generates a checksum for a region of pixels. PixelChecksum ( left, top, right, bottom [, step [, hwnd [, mode]]] ) Parameters left top right bottom step hwnd mode Return Value Success: Failure: Remarks A checksum only allows you to see if "something" has changed in a region - it does not tell you exactly what has changed. Previous versions were extremely slow, however the function is now significantly faster. Using the step parameter is no longer recommended. The performance gain from using a larger step is not nearly as noticeable since the function is faster all around. Also, the larger the step, the less reliable the checksum becomes when used to detect small changes in the region. CRC32 checksum is a little slower than ADLDER but detect better pixel variation. Related PixelGetColor, PixelCoordMode (Option), PixelSearch Example Returns the checksum value of the region. Returns 0. left coordinate of rectangle. top coordinate of rectangle. right coordinate of rectangle. bottom coordinate of rectangle. [optional] Instead of checksumming each pixel use a value larger than 1 to skip pixels (for speed). E.g. A value of 2 will only check every other pixel. Default is 1. It is not recommended to use a step value greater than 1. [optional] Window handle to be used. [optional] default 0 ADLER checksum, 1 CRC32 Checksum.

; Wait until something changes in the region 0,0 to 50,50 ; Get initial checksum $checksum = PixelChecksum(0,0, 50,50) ; Wait for the region to change, the region is checked every 100ms to reduce CPU load While $checksum = PixelChecksum(0,0, 50, 50) Sleep(100) WEnd MsgBox(0, "", "Something in the region has changed!")

Function Reference

AutoItSetOption
Changes the operation of various AutoIt functions/parameters. AutoItSetOption ( "option" [, param] ) Parameters option param The option to change. See Remarks. [optional] The value to assign to the option. The type and meaning vary by option. See remarks below. If the param is not provided, then the function just returns the value already assigned to the option. The keyword Default can be used for the parameter to reset the option to its default value.

Return Value Success: Failure: Remarks You may use Opt() as an alternative to AutoItSetOption(). Options are as follows: Returns the value of the previous setting for the option. Sets @error to non-zero. Failure will occur if the parameters are invalid (such as an option that doesn't exist).

Option

Param Sets the way coords are used in the caret functions, either absolute coords or coords relative to the current active window: 0 = relative coords to the active window 1 = absolute screen coordinates (default) 2 = relative coords to the client area of the active window Changes how literal strings and % symbols are interpreted. By default strings are treated literally, this option allows you to use %environment% variables inside strings, e.g., "The temp directory is: %temp%". 1 = expand environment variables (similar to AutoIt v2) 0 = do not expand environment variables (default) Without this option the usual way would be: "The temp directory is: " & EnvGet("temp") Changes how literal strings and variable/macro ($ and @) symbols are interpreted. By default strings are treated literally, this option allows you to use variables and macros inside strings, e.g., "The value of var1 is $var1$". 1 = expand variables (when in this mode and you want to use a literal $ or @ then double it up: "This is a single dollar $$ sign". 0 = do not expand variables (default) When ESC is pressed on a GUI the $GUI_EVENT_CLOSE message is sent. This option toggles this behavior on and off. 1 = Send the $GUI_EVENT_CLOSE message when ESC is pressed (default). 0 = Don't send the $GUI_EVENT_CLOSE message when ESC is pressed. Alters the position of a control defined by GUICtrlSetPos. 1 = absolute coordinates (default) still relative to the dialog box. 0 = relative position to the start of the last control (upper left corner). 2 = cell positionining relative to current cell. A -1 for left or top parameter don't increment the start. So next line is -1,offset; next cell is offset,-1; current cell is -1,-1. Obviously "offset" cannot be -1 which reserved to indicate the no increment. But if you can use a multiple of the width you choose to skip or go back.

CaretCoordMode

ExpandEnvStrings

ExpandVarStrings

GUICloseOnESC

GUICoordMode

GUIDataSeparatorChar GUIOnEventMode

Define the character which delimits subitems in GUICtrlSetData. The default character is '|'. Enable/disable OnEvent functions notifications. 0 = (default) disable. 1 = enable. Change default resizing for a control. 0 = (default) keep default control resizing. <1024 = anytype of resizing see GUICtrlSetResizing. Change special event behavior or GUI function return values. 0 = (default) Windows behavior on click on Minimize,Restore, Maximize, Resize. 1 = suppress windows behavior on minimize, restore or maximize click button or window resize. Just sends the notification. Alters the length of the brief pause in between mouse clicks. Time in milliseconds to pause (default=10). Alters the length a click is held down before release. Time in milliseconds to pause (default=10). Alters the length of the brief pause at the start and end of a mouse drag operation. Time in milliseconds to pause (default=250). Sets the way coords are used in the mouse functions, either absolute coords or coords relative to the current active window: 0 = relative coords to the active window 1 = absolute screen coordinates (default) 2 = relative coords to the client area of the active window If this option is used then all variables must be pre-declared with Dim, Local or Global before they can be used - removes the chance for misspelled variables causing bugs. 1 = Variables must be pre-declared 0 = Variables don't need to be pre-declared (default) Sets the way coords are used in the pixel functions, either absolute coords or coords relative to the window defined by hwnd (default active window): 0 = relative coords to the defined window 1 = absolute screen coordinates (default) 2 = relative coords to the client area of the defined window Specifies if AutoIt attaches input threads when using Send() function. When not attaching (default mode=0) detecting the state of capslock/scrolllock and numlock can be unreliable under NT4. However, when you specify attach mode=1 the Send("{... down/up}") syntax will not work and there may be problems with sending keys to "hung" windows. ControlSend() ALWAYS attaches and is not affected by this mode. 0 = don't attach (default) 1 = attach Specifies if AutoIt should store the state of capslock before a Send function and restore it afterwards. 0 = don't store/restore 1 = store and restore (default) Alters the the length of the brief pause in between sent keystrokes. A value of 0 removes the delay completely. Time in milliseconds to pause (default=5). Alters the length of time a key is held down before being released during a keystroke. For applications that take a while to register keypresses (and many games) you may need to raise this value from the default. A value of 0 removes the delay completely. Time in milliseconds to pause (default=5). Defines the time before TCP functions stop if no communication. Time in milliseconds before timeout (default=100). Script pauses when click on tray icon. 0 = no pause 1 = pause (default). If there is no DefaultMenu no pause will occurs. If enabled shows the current script line in the tray icon tip to help debugging. 0 = no debug information (default) 1 = show debug Hides the AutoIt tray icon. Note: The icon will still initially appear ~750 milliseconds. 0 = show icon (default)

GUIResizeMode

GUIEventOptions

MouseClic kDelay MouseClic kDownDelay MouseClic kDragDelay

MouseCoordMode

MustDeclareVars

PixelCoordMode

SendAttachMode

SendCapslockMode

SendKeyDelay

SendKeyDownDelay

TCPTimeout TrayAutoPause

TrayIconDebug

TrayIconHide

1 = hide icon Extend the behaviour of the script tray icon/menu. This can be done with a combination (adding) of the following values. 0 = default menu items (Script Paused/Exit) are appended to the usercreated menu; usercreated checked items will automatically unchecked; if you double click the tray icon then the controlid is returned which has the "Default"-style (default). 1 = no default menu 2 = user created checked items will not automatically unchecked if you click it 4 = don't return the menuitemID which has the "default"-style in the main contextmenu if you double click the tray icon 8 = turn off auto check of radio item groups Enable/disable OnEvent functions notifications for the tray. 0 = (default) disable 1 = enable Specifies if hidden window text can be "seen" by the window matching functions. 0 = Do not detect hidden text (default) 1 = Detect hidden text Allows the window search routines to search child windows as well as top-level windows. 0 = Only search top-level windows (default) 1 = Search top-level and child windows Alters the method that is used to match window text during search operations. 1 = Complete / Slow mode (default) 2 = Quic k mode In quick mode AutoIt can usually only "see" dialog text, button text and the captions of some controls. In the default mode much more text can be seen (for instance the contents of the Notepad window). If you are having performance problems when performing many window searches then changing to the "quick" mode may help. Alters the method that is used to match window titles during search operations. 1 = Match the title from the start (default) 2 = Match any substring in the title 3 = Exact title match 4 = Advanced mode, see Window Titles & Text (Advanced) -1 to -4 = force lower case match according to other type of match. Alters how long a script should briefly pause after a successful window-related operation. Time in milliseconds to pause (default=250).

TrayMenuMode

TrayOnEventMode

WinDetectHiddenText

WinSearc hChildren

WinTextMatchMode

WinTitleMatchMode

WinWaitDelay

Related Many! Example

; copy any you want to change ;default value is listed first Opt("CaretCoordMode", 1) ;1=absolute, 0=relative, 2=client Opt("ExpandEnvStrings", 0) ;0=don't expand, 1=do expand Opt("ExpandVarStrings", 0) ;0=don't expand, 1=do expand Opt("GUICloseOnESC", 1) ;1=ESC closes, 0=ESC won't close Opt("GUICoordMode", 1) ;1=absolute, 0=relative, 2=cell Opt("GUIDataSeparatorChar","|");"|" is the default Opt("GUIOnEventMode", 0) ;0=disabled, 1=OnEvent mode enabled Opt("GUIResizeMode", 0) ;0=no resizing, <1024 special resizing Opt("GUIEventOptions",0) ;0=default, 1=just notification, 2=GuiCtrlRead tab index Opt("MouseClickDelay", 10) ;10 milliseconds Opt("MouseClickDownDelay", 10) ;10 milliseconds Opt("MouseClickDragDelay", 250) ;250 milliseconds Opt("MouseCoordMode", 1) ;1=absolute, 0=relative, 2=client Opt("MustDeclareVars", 0) ;0=no, 1=require pre-declare

Opt("PixelCoordMode", 1) ;1=absolute, 0=relative, 2=client Opt("SendAttachMode", 0) ;0=don't attach, 1=do attach Opt("SendCapslockMode", 1) ;1=store and restore, 0=don't Opt("SendKeyDelay", 5) ;5 milliseconds Opt("SendKeyDownDelay", 1) ;1 millisecond Opt("TCPTimeout",100) ;100 milliseconds Opt("TrayAutoPause",1) ;0=no pause, 1=Pause Opt("TrayIconDebug", 0) ;0=no info, 1=debug line info Opt("TrayIconHide", 0) ;0=show, 1=hide tray icon Opt("TrayMenuMode",0) ;0=append, 1=no default menu, 2=no automatic check, 4=menuitemID not return Opt("TrayOnEventMode",0) ;0=disable, 1=enable Opt("WinDetectHiddenText", 0) ;0=don't detect, 1=do detect Opt("WinSearchChildren", 1) ;0=no, 1=search children also Opt("WinTextMatchMode", 1) ;1=complete, 2=quick Opt("WinTitleMatchMode", 1) ;1=start, 2=subStr, 3=exact, 4=advanced, -1 to -4=Nocase Opt("WinWaitDelay", 250) ;250 milliseconds

Function Reference

PixelGetColor
Returns a pixel color according to x,y pixel coordinates. PixelGetColor ( x , y [, hwnd] ) Parameters x y hwnd Return Value Success: Failure: Remarks None Related PixelSearch, PixelCoordMode (Option), MouseGetPos, PixelChec ksum Example Returns decimal value of pixel's color. Returns -1 if invalid coordinates. x coordinate of pixel. y coordinate of pixel. [optional] Window handle to be used.

$var = PixelGetColor( 10 , 100 ) MsgBox(0,"The decimal color is", $var) MsgBox(0,"The hex color is", Hex($var, 6))

Function Reference

PixelSearch
Searches a rectangle of pixels for the pixel color provided. PixelSearch ( left, top, right, bottom, color [, shade-variation [, step [, hwnd]]] ) Parameters left top right bottom color shade-variation step hwnd Return Value Success: Failure: Remarks The search direction varies as follows: Left-to-Right - left < right Right-to-Left - right < left Top-to-Bottom - top < bottom Bottom-to-Top - bottom < top Changing the search direction can be a useful optimization if the color being searched for frequently appears in in a specific quandrat of the search area since less searching is done if the search starts in the most common quadrant. Remember, a typical display at 1024 x 768 has 786432 pixels. Although PixelSearch is optimized, narrowing the search area helps speed up the result. Related PixelChec ksum, PixelGetColor, PixelCoordMode (Option) Example Returns a two-element array of pixel's coordinates. (Array[0] = x, Array[1] = y). Sets @error to 1 if color is not found. left coordinate of rectangle. top coordinate of rectangle. right coordinate of rectangle. bottom coordinate of rectangle. Colour value of pixel to find (in decimal or hex). [optional] A number between 0 and 255 to indicate the allowed number of shades of variation of the red, green, and blue components of the colour. Default is 0 (exact match). [optional] Instead of searching each pixel use a value larger than 1 to skip pixels (for speed). E.g. A value of 2 will only check every other pixel. Default is 1. [optional] Window handle to be used.

; Find a pure red pixel in the range 0,0-20,300 $coord = PixelSearch( 0, 0, 20, 300, 0xFF0000 ) If Not @error Then MsgBox(0, "X and Y are:", $coord[0] & "," & $coord[1]) EndIf

; Find a pure red pixel or a red pixel within 10 shades variations of pure red $coord = PixelSearch( 0, 0, 20, 300, 0xFF0000, 10 ) If Not @error Then

MsgBox(0, "X and Y are:", $coord[0] & "," & $coord[1]) EndIf

Function Reference

SoundPlay
Play a sound file. SoundPlay ( "filename" [, wait] ) Parameters filename wait Name of the file to be played (typically a WAV or MP3) [optional] This flag determines if the script should wait for the sound to finish before continuing: 1 = wait until sound has finished 0 = continue script while sound is playing (default)

Return Value None. (Always returns 1 regardless of success.) Remarks Terminating the script will stop the sound (if it is still playing). Calling SoundPlay("") can be used to stop a currently playing sound. This has the side effect of also closing the open handle. If you need to delete a sound file which you have played in the script, you should call SoundPlay("") first to ensure the handle is closed. Related SoundSetWaveVolume, Beep Example

SoundPlay(@WindowsDir & "\media\tada.wav",1)

Function Reference

SoundSetWaveVolume
Sets the system wave volume by percent. SoundSetWaveVolume ( percent ) Parameters percent Return Value Success: Failure: Remarks This controls the Wave volume, not the master volume control. Also, a value of Zero does not set mute status. On Windows Vista, there is no system-wide wave volume. This function only changes the wave volume for the script. It can not be used to change the wave volume of other programs. Related SoundPlay Example Returns 1. Returns 0 and sets @error to 1 if percent is invalid. percentage number between 0 and 100

SoundSetWaveVolume(50)

GUI functions Reference


Below is a complete list of the functions available in AutoIt. Click on a function name for a detailed description. See Gui Constants include files if you need to use the related controls Constants . Function GUICreate GUIDelete GUICtrlGetHandle GUICtrlGetState GUICtrlRead GUICtrlRec vMsg GUICtrlSendMsg GUICtrlSendT oDummy GUIGetCursorInfo GUIGetMsg GUIGetStyle GUIRegisterMsg GUIStartGroup GUISwitch Description Create a GUI window. Deletes a GUI window and all controls that it contains. Returns the handle for a control and some special (item) handles (Menu, ContextMenu, TreeViewItem). Gets the current state of a control Read state or data of a control. Send a message to a control and retrieve information in lParam. Send a message to a control. Sends a message to a Dummy control. Gets the mouse cursor position relative to GUI window. Polls the GUI to see if any events have occurred. Retrieves the styles of a GUI window. Register a user defined function for a known Windows Message ID (WM_MSG). Defines that any subsequent controls that are created will be "grouped" together. Switches the current window used for GUI functions.

Function Reference

GUICreate
Create a GUI window. GUICreate ( "title" [, width [, height [, left [, top [, style [, exStyle [, parent]]]]]]] ) Parameters title width height left top The title of the dialog box. [optional] The width of the window. [optional] The height of the window. [optional] The left side of the dialog box. By default (-1), the window is centered. If defined, top must also be defined. [optional] The top of the dialog box. Default (-1) is centered [optional] defines the style of the window. See GUI Control Styles Appendix. Use -1 for the default style which includes a combination of $WS_MINIMIZEBOX, $WS_CAPTION, $WS_POPUP, $WS_SYSMENU styles. Some styles are always included: $WS_CLIPSIBLINGS, and $WS_SYSMENU if $WS_MAXIMIZEBOX or $WS_SIZEBOX is specified. [optional] defines the extended style of the window. See the Extended Style Table below. -1 is the default. [optional] The handle of another previously created window - this new window then becomes a child of that window.

style

exStyle parent Return Value Success: Failure: Remarks

Returns a windows handle. Returns 0 if the window cannot be created and sets @error to 1.

By default the dialog box is non sizable and non maximizable. So WS_SIZEBOX or WS_MAXIMIZEBOX can be used in the style parameter. As defining only one style just set this style don't forget to combine it with default ones, i.e. just defining WS_SIZEBOX will not set WS_MINIMIZEBOX, WS_CAPTION, WS_POPUP, WS_SYSMENU. So the best method to define a resizeable window is to use WS_OVERLAPPEDWINDOW. When using $WS_EX_MDICHILD the position is relative to client area of the parent window. With $WS_EX_LAYERED it is possible to have a transparent pic on a background pic defined in the parent window. Adding $WS_CLIPCHILDREN style can avoid some flickering when resizing GUI containing Edit control for example. You can enable window draging for GUI without $WS_CAPTION by using $WS_EX_CONTROLPARENT in the exStyle parameter. To combine styles with the default style use BitOr($GUI_SS_DEFAULT_GUI, newstyle,...). The size specified is the size of the client area of the window. The border and title bar will make the window slightly larger than specified. Using menu controls will also change the windows height. Extended Style table Extended Style result Allow an edit or input control within the created GUI window to receive filenames via drag and drop. The control must have also the $GUI_DROPACCEPTED state set by GUICtrlSetState. for other controls the drag&drop info c an be retrieved with @GUI_DRAGID, @GUI_DRAGFILE, @GUIDROPID. Forces a top-level window onto the taskbar when the window is visible.

$WS_EX_ACCEPTFILES

$WS_EX_APPWINDOW

$WS_EX_CLIENTEDGE $WS_EX_CONTEXTHELP $WS_EX_DLGMODALFRAME $WS_EX_MDICHILD

Specifies that a window has a border with a sunken edge. Includes a question mark in the title bar of the window. Cannot be used with the WS_MAXIMIZEBOX or WS_MINIMIZEBOX. Creates a window that has a double border; the window can, optionally, be created with a title bar by specifying the WS_CAPTION style in the style parameter. Create a child window included in its parent window (simulation not real MDI). Creates a window with a three-dimensional border style intended to be used for items that do not accept user input. Specifies that a window created with this style should be placed above all non-topmost windows and should stay above them, even when the window is deactivated. The window appears transparent because the bits of underlying sibling windows have already been painted. Creates a tool window; that is, a window intended to be used as a floating toolbar. A tool window has a title bar that is shorter than a normal title bar, and the window title is drawn using a smaller font. A tool window does not appear in the taskbar or in the dialog box that appears when the user presses ALT+TAB. If a tool window has a system menu, its icon is not displayed on the title bar. However, you can display the system menu by typing ALT+SPACE. Specifies that a window has a border with a raised edge. Creates a layered window. Note that this cannot be used for child windows.

$WS_EX_OVERLAPPEDWINDOW Combines the WS_EX_CLIENTEDGE and WS_EX_WINDOWEDGE styles. $WS_EX_STATICEDGE $WS_EX_TOPMOST $WS_EX_TRANSPARENT

$WS_EX_TOOLWINDOW

$WS_EX_WINDOWEDGE $WS_EX_LAYERED

To use the values specified above you must #include <WindowsConstants.au3> in your script. Note: The handle returned from this function is a real windows handle, which means it can be used in the same way as the result of WinGetHandle. Related GUISetParameters..., GUICtrlCreate..., GUIGetMsg, GUISwitch, GUIGetStyle, GUIDelete, WinGetHandle, GUICtrlSetDefBkColor, GUICtrlSetDefColor, GUIGetCursorInfo Example

#include <GUIConstantsEx.au3> #include <WindowsConstants.au3> Opt('MustDeclareVars', 1) Example1() Example2() ; example 1 Func Example1() Local $msg GUICreate("My GUI") ; will create a dialog box that when displayed is centered GUISetState(@SW_SHOW) ; will display an empty dialog box ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd GUIDelete() EndFunc ;==>Example1

; example 2 Func Example2() Local $gui, $background, $pic, $basti_stay, $msg Local $sFile = "..\GUI\logo4.gif" $gui = GUICreate("Background", 400, 100) ; background picture $background = GUICtrlCreatePic("..\GUI\msoobe.jpg", 0, 0, 400, 100) GUISetState(@SW_SHOW) ; transparent MDI child window $pic = GUICreate("", 169, 68, 20, 20, $WS_POPUP, BitOR($WS_EX_LAYERED, $WS_EX_MDICHILD), $gui) ; transparent pic $basti_stay = GUICtrlCreatePic($sFile, 0, 0, 169, 68) GUISetState(@SW_SHOW) Do $msg = GUIGetMsg() Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example2

GUI Control creation functions Reference


Below is a complete list of the functions available in AutoIt. Click on a function name for a detailed description. See Gui Constants include files if you need to use the related controls Constants . Function GUICtrlCreateAvi GUICtrlCreateButton GUICtrlCreateChec kbox GUICtrlCreateCombo GUICtrlCreateContextMenu GUICtrlCreateDate GUICtrlCreateDummy GUICtrlCreateEdit GUICtrlCreateGraphic GUICtrlCreateGroup GUICtrlCreateIcon GUICtrlCreateInput GUICtrlCreateLabel GUICtrlCreateList GUICtrlCreateListView GUICtrlCreateListViewItem GUICtrlCreateMenu GUICtrlCreateMenuItem GUICtrlCreateMonthCal GUICtrlCreateObj GUICtrlCreatePic GUICtrlCreateProgress GUICtrlCreateRadio GUICtrlCreateSlider GUICtrlCreateTab GUICtrlCreateTabItem GUICtrlCreateTreeView Description Creates an AVI video control for the GUI. Creates a Button control for the GUI. Creates a Checkbox control for the GUI. Creates a ComboBox control for the GUI. Creates a context menu for a control or entire GUI window. Creates a date control for the GUI. Creates a Dummy control for the GUI. Creates an Edit control for the GUI. Creates a Graphic control for the GUI. Creates a Group control for the GUI. Creates an Icon control for the GUI. Creates an Input control for the GUI. Creates a static Label control for the GUI. Creates a List control for the GUI. Creates a ListView control for the GUI. Creates a ListView item. Creates a Menu control for the GUI. Creates a MenuItem control for the GUI. Creates a month calendar control for the GUI. Creates an ActiveX control in the GUI. Creates a Picture control for the GUI. Creates a Progress control for the GUI. Creates a Radio button control for the GUI. Creates a Slider control for the GUI. Creates a Tab control for the GUI. Creates a TabItem control for the GUI. Creates a TreeView control for the GUI.

GUICtrlCreateTreeViewItem Creates a TreeViewItem control for the GUI. GUICtrlCreateUpdown GUICtrlDelete Creates an UpDown control for the GUI. Deletes a control.

Function Reference

GUICtrlCreateAvi
Creates an AVI video control for the GUI. GUICtrlCreateAvi ( filename, subfileid, left, top [, width [, height [, style [, exStyle]]]] ) Parameters filename subfileid left top width height style exStyle Return Value Success: Failure: Remarks To obtain the value of the control see GUICtrlRead. To set or change information in the control see GUICtrlUpdate.... To start the video as soon as the control is created use the $ACS_AUTOPLAY style. You can can start and stop the animation by setting the state to 1 or 0 with GUICtrlSetState. See example. To combine styles with the default style use BitOr($GUI_SS_DEFAULT_AVI, newstyle,...). To use the values specified above you must #include <AVIConstants.au3> in your script. Default resizing is $GUI_DOCKSIZE. Related GUICoordMode (option), GUICtrlUpdate..., GUIGetMsg Example Returns the identifier (controlID) of the new control. Returns 0. The filename of the video. Only .avi files are supported. id of the subfile to be used. If the file only contains one video then use -1. The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default is the previously used width). [optional] The height of the control (default is the previously used height). [optional] Defines the style of the control. See GUI Control Styles Appendix. default (-1) : $ACS_TRANSPARENT $ACS_TRANSPARENT is always used unless $ACS_NONTRANSPARENT is specified. [optional] Defines the extended style of the control. See Extended Style Table.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example()

Local $ani1, $buttonstart, $buttonstop, $msg GUICreate("My GUI Animation", 300, 200) $ani1 = GUICtrlCreateAvi(@SystemDir & "\shell32.dll", 165, 50, 10) $buttonstart = GUICtrlCreateButton("start", 50, 150, 70, 22) $buttonstop = GUICtrlCreateButton("stop", 150, 150, 70, 22) GUISetState() ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() Select Case $msg = $GUI_EVENT_CLOSE ExitLoop Case $msg = $buttonstart GUICtrlSetState($ani1, 1) Case $msg = $buttonstop GUICtrlSetState($ani1, 0) EndSelect WEnd EndFunc ;==>Example

Function Reference

GUICtrlCreateButton
Creates a Button control for the GUI. GUICtrlCreateButton ( "text", left, top [, width [, height [, style [, exStyle]]]] ) Parameters text left top width height style exStyle Return Value Success: Failure: Remarks To set or change information in the control see GUICtrlUpdate.... A Button control can display an icon or image by using the $BS_ICON or $BS_BITMAP style. Use GUICtrlSetImage to specify the picture to use. To combine styles with the default style use BitOr($GUI_SS_DEFAULT_BUTTON, newstyle,...). To use the values specified above you must #include <ButtonConstants.au3> in your script. Default resizing is $GUI_DOCKSIZE Related GUICoordMode (Option), GUICtrlUpdate..., GUIGetMsg Example Returns the identifier (controlID) of the new control. Returns 0. The text of the button control. The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default text autofit in width). [optional] The height of the control (default text autofit in height). [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : none. forced styles : $WS_TABSTOP [optional] Defines the extended style of the control. See Extended Style Table.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $Button_1, $Button_2, $msg GUICreate("My GUI Button") ; will create a dialog box that when displayed is centered Opt("GUICoordMode", 2)

$Button_1 = GUICtrlCreateButton("Run Notepad", 10, 30, 100) $Button_2 = GUICtrlCreateButton("Button Test", 0, -1) GUISetState() ; will display an dialog box with 2 button ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() Select Case $msg = $GUI_EVENT_CLOSE ExitLoop Case $msg = $Button_1 Run('Notepad.exe') ; Will Run/Open Notepad Case $msg = $Button_2 MsgBox(0, 'Testing', 'Button 2 was pressed') ; Will demonstrate Button 2 being pressed EndSelect WEnd EndFunc ;==>Example

Function Reference

GUICtrlCreateCheckbox
Creates a Checkbox control for the GUI. GUICtrlCreateCheckbox ( "text", left, top [, width [, height [, style [, exStyle]]]] ) Parameters text left top width height style exStyle Return Value Success: Failure: Remarks To obtain the value of the control see GUICtrlRead. To set or change information in the control see GUICtrlUpdate.... A Checkbox control can display an icon or image by using the $BS_ICON or $BS_BITMAP style. Use GUICtrlSetImage to specify the picture to use. To combine styles with the default style use BitOr($GUI_SS_DEFAULT_CHECKBOX, newstyle,...). To use the values specified above you must #include <ButtonConstants.au3> in your script. Default resizing is $GUI_DOCKHEIGHT. Related GUICoordMode (Option), GUICtrlUpdate..., GUIGetMsg Example Returns the identifier (controlID) of the new control. Returns 0. The text of the control checkbox. The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default text autofit in width). [optional] The height of the control (default text autofit in height). [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : $BS_AUTOCHECKBOX. forced styles : $WS_TABSTOP, and $BS_AUTOCHECKBOX if no checkbox style defined. [optional] Defines the extended style of the control. See Extended Style Table.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $checkCN, $msg GUICreate("My GUI Checkbox") ; will create a dialog box that when displayed is centered

$checkCN = GUICtrlCreateCheckbox("CHECKBOX 1", 10, 10, 120, 20) GUISetState() ; will display an dialog box with 1 checkbox ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUICtrlCreateCombo
Creates a ComboBox control for the GUI. GUICtrlCreateCombo ( "text", left, top [, width [, height [, style [, exStyle]]]] ) Parameters text left top width height style exStyle Return Value Success: Failure: Remarks To obtain the value of the control see GUICtrlRead. To set or change information in the control see GUICtrlUpdate.... Under Windows XP/2003 Windows will adjust the size of the opened combo. On other Windows versions you can define this size with the "height" parameter if the default value is not BIG enough to contain at least one line. To combine styles with the default style use BitOr($GUI_SS_DEFAULT_COMBO, newstyle,...). To use the values specified above you must #include <ComboConstants.au3> in your script. Default resizing is $GUI_DOCKHEIGHT. Related GUICoordMode (Option), GUICtrlSetData, GUICtrlUpdate..., GUIGetMsg Example Returns the identifier (controlID) of the new control. Returns 0. The text which will appear in the combo control. The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default is the previously used width). [optional] The height of the control (default is the previously used height). [optional] Defines the style of the control. See GUI Control Styles Appendix. default (-1) : $CBS_DROPDOWN, $CBS_AUTOHSCROLL, $WS_VSCROLL forced style : $WS_TABSTOP [optional] Defines the extended style of the control. See Extended Style Table.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $msg GUICreate("My GUI combo") ; will create a dialog box that when displayed is centered

GUICtrlCreateCombo("item1", 10, 10) ; create first item GUICtrlSetData(-1, "item2|item3", "item3") ; add other item snd set a new default GUISetState() ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUICtrlCreateContextMenu
Creates a context menu for a control or entire GUI window. GUICtrlCreateContextMenu ( [controlID] ) Parameters controlID Return Value Success: Failure: Remarks After creating the context menu main control with this function, each menu item can be created by using GUICtrlCreateMenuItem. Sub-menus can be created using GUICtrlCreateMenu. If you use no parameters or -1 in this function then the context menu that is created is associated with the entire GUI window rather than an individual control. Only one context menu per control is possible. If you wish to create a new context menu one you have to delete the existing menu first. Note: You can't create context menus for controls that already have system context menus, i.e. edit or input controls. Related GUICtrlCreateMenuItem, GUICtrlCreateMenu, GUICtrlGetHandle, GUICtrlSetState, GUICtrlDelete Example Returns the identifier (controlID) of the new control. Returns 0. [optional] Control identifier as returned by GUICtrlCreate...

#include <GUIConstantsEx.au3> #include <ButtonConstants.au3> Opt('MustDeclareVars', 1) Example1() Example2() ; **************** ; * First sample * ; **************** Func Example1() Local $contextmenu, $button, $buttoncontext, $buttonitem, $msg Local $newsubmenu, $textitem, $fileitem, $saveitem, $infoitem ;right click on gui to bring up context Menu. ;right click on the "ok" button to bring up a controll specific context menu. GUICreate("My GUI Context Menu", 300, 200) $contextmenu = GUICtrlCreateContextMenu()

$button = GUICtrlCreateButton("OK", 100, 100, 70, 20) $buttoncontext = GUICtrlCreateContextMenu($button) $buttonitem = GUICtrlCreateMenuItem("About button", $buttoncontext) $newsubmenu = GUICtrlCreateMenu("new", $contextmenu) $textitem = GUICtrlCreateMenuItem("text", $newsubmenu) $fileitem = GUICtrlCreateMenuItem("Open", $contextmenu) $saveitem = GUICtrlCreateMenuItem("Save", $contextmenu) GUICtrlCreateMenuItem("", $contextmenu) ; separator $infoitem = GUICtrlCreateMenuItem("Info", $contextmenu) GUISetState() ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd GUIDelete() EndFunc ;==>Example1

; ***************** ; * Second sample * ; ***************** Func Example2() Local $hGui, $OptionsBtn, $OptionsDummy, $OptionsContext, $OptionsCommon, $OptionsFile, $msg Local $OptionsExit, $HelpBtn, $HelpDummy, $HelpContext, $HelpWWW, $HelpAbout $hGui = GUICreate("My GUI", 170, 40) $OptionsBtn = GUICtrlCreateButton("&Options", 10, 10, 70, 20, $BS_FLAT) ; At first create a dummy control for the options and a contextmenu for it $OptionsDummy = GUICtrlCreateDummy() $OptionsContext = GUICtrlCreateContextMenu($OptionsDummy) $OptionsCommon = GUICtrlCreateMenuItem("Common", $OptionsContext) $OptionsFile = GUICtrlCreateMenuItem("File", $OptionsContext) GUICtrlCreateMenuItem("", $OptionsContext) $OptionsExit = GUICtrlCreateMenuItem("Exit", $OptionsContext)

$HelpBtn = GUICtrlCreateButton("&Help", 90, 10, 70, 20, $BS_FLAT) ; Create a dummy control and a contextmenu for the help too $HelpDummy = GUICtrlCreateDummy() $HelpContext = GUICtrlCreateContextMenu($HelpDummy) $HelpWWW = GUICtrlCreateMenuItem("Website", $HelpContext) GUICtrlCreateMenuItem("", $HelpContext) $HelpAbout = GUICtrlCreateMenuItem("About...", $HelpContext)

GUISetState() While 1 $msg = GUIGetMsg() Switch $msg Case $OptionsExit, $GUI_EVENT_CLOSE ExitLoop Case $OptionsBtn

ShowMenu($hGui, $msg, $OptionsContext) Case $HelpBtn ShowMenu($hGui, $msg, $HelpContext) Case $HelpAbout MsgBox(64, "About...", "GUICtrlGetHandle-Sample") EndSwitch WEnd GUIDelete() EndFunc ;==>Example2

; Show a menu in a given GUI window which belongs to a given GUI ctrl Func ShowMenu($hWnd, $CtrlID, $nContextID) Local $arPos, $x, $y Local $hMenu = GUICtrlGetHandle($nContextID) $arPos = ControlGetPos($hWnd, "", $CtrlID) $x = $arPos[0] $y = $arPos[1] + $arPos[3] ClientToScreen($hWnd, $x, $y) TrackPopupMenu($hWnd, $hMenu, $x, $y) EndFunc ;==>ShowMenu

; Convert the client (GUI) coordinates to screen (desktop) coordinates Func ClientToScreen($hWnd, ByRef $x, ByRef $y) Local $stPoint = DllStructCreate("int;int") DllStructSetData($stPoint, 1, $x) DllStructSetData($stPoint, 2, $y) DllCall("user32.dll", "int", "ClientToScreen", "hwnd", $hWnd, "ptr", DllStructGetPtr ($stPoint)) $x = DllStructGetData($stPoint, 1) $y = DllStructGetData($stPoint, 2) ; release Struct not really needed as it is a local $stPoint = 0 EndFunc ;==>ClientToScreen

; Show at the given coordinates (x, y) the popup menu (hMenu) which belongs to a given GUI window (hWnd) Func TrackPopupMenu($hWnd, $hMenu, $x, $y) DllCall("user32.dll", "int", "TrackPopupMenuEx", "hwnd", $hMenu, "int", 0, "int", $x, "int", $y, "hwnd", $hWnd, "ptr", 0) EndFunc ;==>TrackPopupMenu

Function Reference

GUICtrlCreateDate
Creates a date control for the GUI. GUICtrlCreateDate ( "text", left, top [, width [, height [, style [, exStyle]]]] ) Parameters text left top width height style The preselected date (always as "yyyy/mm/dd"). The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default is the previously used width). [optional] The height of the control (default is the previously used height). [optional] Defines the style of the control. See GUI Control Styles Appendix. default (-1) : $DTS_LONGDATEFORMAT forced style : $WS_TABSTOP [optional] Defines the extended style of the control. See Extended Style Table. default (-1) : WS_EX_CLIENTEDGE

exStyle Return Value Success: Failure: Remarks

Returns the identifier (controlID) of the new control. Returns 0.

To obtain the value of the control see GUICtrlRead. To set or change information in the control see GUICtrlUpdate.... To combine styles with the default style use BitOr($GUI_SS_DEFAULT_DATE, newstyle,...). To Format the date/time see example 3 to understand how to use a GuiCtrlSendMsg with a $DTM_SETFORMAT. To use the values specified above you must #include <DateTimeConstants.au3> in your script. Default resizing is $GUI_DOCKHEIGHT. Related GUICoordMode (Option), GUICtrlSetState, GUIGetMsg, GUICtrlRead Example

#include <GUIConstantsEx.au3> #include <DateTimeConstants.au3> Opt('MustDeclareVars', 1) Example1() Example2() Example3() Example4()

; example1 Func Example1() Local $date, $msg GUICreate("My GUI get date", 200, 200, 800, 200) $date = GUICtrlCreateDate("1953/04/25", 10, 10, 185, 20) GUISetState() ; Run the GUI until the dialog is closed Do $msg = GUIGetMsg() Until $msg = $GUI_EVENT_CLOSE

MsgBox(0, "Date", GUICtrlRead($date)) GUIDelete() EndFunc ;==>Example1 ; example2 Func Example2() Local $n, $msg GUICreate("My GUI get date", 200, 200, 800, 200) $n = GUICtrlCreateDate("", 10, 10, 100, 20, $DTS_SHORTDATEFORMAT) GUISetState() ; Run the GUI until the dialog is closed Do $msg = GUIGetMsg() Until $msg = $GUI_EVENT_CLOSE

MsgBox(0, "Date", GUICtrlRead($n)) GUIDelete() EndFunc ;==>Example2 ; example3 Func Example3() Local $date, $DTM_SETFORMAT_, $style GUICreate("My GUI get date", 200, 200, 800, 200) $date = GUICtrlCreateDate("1953/04/25", 10, 10, 185, 20) ; to select a specific default format $DTM_SETFORMAT_ = 0x1032 ; $DTM_SETFORMATW $style = "yyyy/MM/dd HH:mm:ss" GUICtrlSendMsg($date, $DTM_SETFORMAT_, 0, $style)

GUISetState() While GUIGetMsg() <> $GUI_EVENT_CLOSE WEnd MsgBox(0, "Time", GUICtrlRead($date)) EndFunc ;==>Example3 ; example4 Func Example4() Local $n, $msg GUICreate("My GUI get time", 200, 200, 800, 200) $n = GUICtrlCreateDate("", 20, 20, 100, 20, $DTS_TIMEFORMAT) GUISetState() ; Run the GUI until the dialog is closed Do $msg = GUIGetMsg() Until $msg = $GUI_EVENT_CLOSE

MsgBox(0, "Time", GUICtrlRead($n)) GUIDelete() EndFunc ;==>Example4

Function Reference

GUICtrlCreateDummy
Creates a Dummy control for the GUI. GUICtrlCreateDummy ( ) Parameters None. Return Value Success: Failure: Remarks This control can receive messages through a GUICtrlSendT oDummy call. The control will "notify" as normal and the value sent with GUISendToDummy can be read with GUICtrlRead. Related GUICtrlSendT oDummy, GUICtrlSetOnEvent, GUICtrlRead, GUICtrlSetData Example Returns the identifier (controlID) of the new control. Returns 0.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $user, $button, $cancel, $msg GUICreate("GUICtrlCreateDummy", 250, 200, 100, 200) GUISetBkColor(0x00E0FFFF) ; will change background color $user = GUICtrlCreateDummy() $button = GUICtrlCreateButton("event", 75, 170, 70, 20) $cancel = GUICtrlCreateButton("Cancel", 150, 170, 70, 20) GUISetState()

Do $msg = GUIGetMsg() Select Case $msg = $button GUICtrlSendToDummy($user) Case $msg = $cancel GUICtrlSendToDummy($user) Case $msg = $user ; special action before closing ; ... Exit EndSelect Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example

Function Reference

GUICtrlCreateEdit
Creates an Edit control for the GUI. GUICtrlCreateEdit ( "text", left, top [, width [, height [, style [, exStyle]]]] ) Parameters text left top width height The text of the control. The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default is the previously used width). [optional] The height of the control (default is the previously used height). [optional] Defines the style of the control. See GUI Control Styles Appendix. style default ( -1) : $ES_WANTRETURN, $WS_VSCROLL, $WS_HSCROLL, $ES_AUTOVSCROLL, $ES_AUTOHSCROLL forced styles : $ES_MULTILINE, $WS_TABSTOP only if not $ES_READONLY [optional] Defines the extended style of the control. See Extended Style Table.

exStyle Return Value Success: Failure: Remarks

Returns the identifier (controlID) of the new control. Returns 0.

To obtain the value of the control see GUICtrlRead. To set or change information in the control see GUICtrlUpdate.... To combine styles with the default style use BitOr($GUI_SS_DEFAULT_EDIT, newstyle,...). If you want to drag & drop a filename onto this control just add the WS_EX_ACCEPTFILES extended style on the GUICreate() and set the state to $GUI_DROPACCEPTED. Multiple selected files will be dropped as separate lines. To use the values specified above you must #include <EditConstants.au3> in your script. Default resizing is $GUI_DOCKAUTO size and position will occur. Creating a RichEdit control is too complex so it will not be included as a basic control. You have to use the GuiCtrlCreateObj. See the second example if you need to have a RichEdit control. Related GUICoordMode (Option), GUICtrlSetData, GUICtrlSetState, GUICtrlSetLimit, GUIGetMsg, GUICtrlRead Example

#include #include #include #include

<GUIConstantsEx.au3> <WindowsConstants.au3> <EditConstants.au3> <StaticConstants.au3>

Opt('MustDeclareVars', 1) Global $oMyError Example() RichEditExample() Func Example() Local $myedit, $msg GUICreate("My GUI edit") ; will create a dialog box that when displayed is centered $myedit = GUICtrlCreateEdit("First line" & @CRLF, 176, 32, 121, 97, $ES_AUTOVSCROLL + $WS_VSCROLL) GUISetState() Send("{END}") ; will be append dont' forget 3rd parameter GUICtrlSetData($myedit, "Second line", 1) ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd GUIDelete() EndFunc ;==>Example

; Rich edit control EXAMPLE using GUICtrlCreateObj ; Author: Kre Johansson ; AutoIt Version: 3.1.1.55 ; Description: Very Simple example: Embedding RICHTEXT object ; Needs: MSCOMCT2.OCX in system32 but it's probably already there ; Date: 3 jul 2005 Func RichEditExample() Local $oRP, $TagsPageC, $AboutC, $PrefsC, $StatC, $GUIActiveX, $msg $oMyError = ObjEvent("AutoIt.Error", "MyErrFunc") $oRP = ObjCreate("RICHTEXT.RichtextCtrl.1") GUICreate("Embedded RICHTEXT control Test", 320, 200, -1, -1, BitOR ($WS_OVERLAPPEDWINDOW, $WS_CLIPSIBLINGS, $WS_CLIPCHILDREN)) $TagsPageC = GUICtrlCreateLabel('Visit Tags Page', 5, 180, 100, 15, $SS_CENTER) GUICtrlSetFont($TagsPageC, 9, 400, 4) GUICtrlSetColor($TagsPageC, 0x0000ff) GUICtrlSetCursor($TagsPageC, 0) $AboutC = GUICtrlCreateButton('About', 105, 177, 70, 20) $PrefsC = GUICtrlCreateButton('FontSize', 175, 177, 70, 20) $StatC = GUICtrlCreateButton('Plain Style', 245, 177, 70, 20) $GUIActiveX = GUICtrlCreateObj($oRP, 10, 10, 400, 260) GUICtrlSetPos($GUIActiveX, 10, 10, 300, 160) & With $oRP; Object tag pool .OLEDrag() .Font = 'Arial' .text = "Hello - Au3 supports ActiveX components like the RICHTEXT thanks to SvenP" @CRLF & 'Try write some text and quit to reload' ;.FileName = @ScriptDir & '\RichText.rtf' ;.BackColor = 0xff00

EndWith GUISetState();Show GUI While 1 $msg = GUIGetMsg() Select Case $msg = $GUI_EVENT_CLOSE $oRP.SaveFile(@ScriptDir & "\RichText.rtf", 0) ExitLoop Case $msg = $TagsPageC Run(@ComSpec & ' /c start http://www.myplugins.info/guids/typeinfo/typeinfo.php?clsid={3B7C8860-D78F-101B-B9B504021C009402}', '', @SW_HIDE) Case $msg = $AboutC $oRP.AboutBox() Case $msg = $PrefsC $oRP.SelFontSize = 12 Case $msg = $StatC $oRP.SelBold = False $oRP.SelItalic = False $oRP.SelUnderline = False $oRP.SelFontSize = 8 EndSelect WEnd GUIDelete() EndFunc ;==>RichEditExample Func MyErrFunc() MsgBox(0, "AutoItCOM Test", "We intercepted a COM Error !" & @CRLF & @CRLF & _ "err.description is: " & @TAB & $oMyError.description & @CRLF & _ "err.windescription:" & @TAB & $oMyError.windescription & @CRLF & _ "err.number is: " & @TAB & Hex($oMyError.number, 8) & @CRLF & _ "err.lastdllerror is: " & @TAB & $oMyError.lastdllerror & @CRLF & _ "err.scriptline is: " & @TAB & $oMyError.scriptline & @CRLF & _ "err.source is: " & @TAB & $oMyError.source & @CRLF & _ "err.helpfile is: " & @TAB & $oMyError.helpfile & @CRLF & _ "err.helpcontext is: " & @TAB & $oMyError.helpcontext _ , 5) ; Will automatically continue after 5 seconds Local $err = $oMyError.number If $err = 0 Then $err = -1 SetError($err) ; to check for after this function returns EndFunc ;==>MyErrFunc

Function Reference

GUICtrlCreateGraphic
Creates a Graphic control for the GUI. GUICtrlCreateGraphic ( left, top [, width [, height [, style]]] ) Parameters left top width height style default ( -1) : $SS_NOTIFY. Return Value Success: Failure: Remarks To draw in the control see GUICtrlSetGraphic . The border and background color can be set with GUICtrlSetBkColor and GUICtrlSetColor. Graphic control can be clicked so they should not overlap with other controls. If overlap is needed it is important to disable the graphic control : GuiCtrlSetState(-1,$GUI_DISABLE). This control cannot be resized due to fix graphic relative addressing creation but can be dock with GUICtrlSetResizing(). Related GUICtrlSetGraphic , GUICtrlSetBkColor, GUICtrlSetColor, GUICtrlDelete, GUICoordMode (Option), GUICtrlSetStyle, GUICtrlSetResizing, GUIGetMsg Example Returns the identifier (controlID) of the new control. Returns 0. The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default is the previously used width). [optional] The height of the control (default is the previously used height). [optional] Defines the style of the control. See GUI Control Styles Appendix.

#include <GUIConstantsEx.au3> #include <StaticConstants.au3> Opt('MustDeclareVars', 1) Global $MAXGr = 6, $del Global $a[$MAXGr + 1] ; 0 and $MAXGr entries not used to allow GUICtrlDelete result Example() Func Example() Local $msg, $inc, $i CreateChild()

$i = 1 $inc = 1 Do $msg = GUIGetMsg()

If $msg = $del Then GUICtrlDelete($a[$i]) $i = $i + $inc If $i < 0 Or $i > $MAXGr Then Exit EndIf If $msg > 0 Then MsgBox(0, "clicked", $msg & @LF & $a[5], 2) Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example Func CreateChild() Local $child $child = GUICreate("My Draw") $del = GUICtrlCreateButton("Delete", 50, 165, 50)

$a[1] = GUICtrlCreateGraphic(20, 50, 100, 100) GUICtrlSetBkColor(-1, 0xffffff) GUICtrlSetColor(-1, 0) GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0xff0000, $GUI_GR_PIE, 50, 50, 40, $GUI_GR_COLOR, 0x00ff00, $GUI_GR_PIE, 58, 50, 40, 0xff0000) 30, 270) 0xffffff) -60, 90)

GUICtrlSetGraphic(-1, $GUI_GR_ELLIPSE, 100, 100, 50, 80) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0x00ff00, 0xc0c0ff) GUICtrlSetGraphic(-1, $GUI_GR_RECT, 350, 200, 50, 80) GUICtrlCreateLabel("label", 65, 100, 30) GUICtrlSetColor(-1, 0xff)

$a[2] = GUICtrlCreateGraphic(220, 50, 100, 100) GUICtrlSetStyle(-1, $SS_NOTIFY) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0, 0xff) GUICtrlSetGraphic(-1, $GUI_GR_PIE, 50, 50, 40, 30, 270) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0x00ff00, 0xffffff) GUICtrlSetGraphic(-1, $GUI_GR_PIE, 58, 50, 40, -60, 90) $a[3] = GUICtrlCreateGraphic(220, 150, 100, 100, 0) GUICtrlSetBkColor(-1, 0xf08080) GUICtrlSetColor(-1, 0xff) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0xff00) GUICtrlSetGraphic(-1, $GUI_GR_RECT, 50, 50, 80, 80) $a[4] = GUICtrlCreateGraphic(20, 200, 80, 80) GUICtrlSetState(-1, $GUI_DISABLE) GUICtrlSetBkColor(-1, 0xffffff) GUICtrlSetGraphic(-1, $GUI_GR_MOVE, 10, 10) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0xff) GUICtrlSetGraphic(-1, $GUI_GR_LINE, 30, 40) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0xff00) GUICtrlSetGraphic(-1, $GUI_GR_LINE, 70, 70) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0xff0000) GUICtrlSetGraphic(-1, $GUI_GR_LINE, 10, 50) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0xffff00) GUICtrlSetGraphic(-1, $GUI_GR_LINE, 10, 10)

$a[5] = GUICtrlCreateGraphic(150, 10, 50, 50, 0) GUICtrlSetBkColor(-1, 0xa0ffa0) GUICtrlSetGraphic(-1, $GUI_GR_MOVE, 20, 20) ; start point

; it is better to draw line and after point ; to avoid to switch color at each drawing GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0x0000ff) GUICtrlSetGraphic(-1, $GUI_GR_DOT, 30, 30) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0) GUICtrlSetGraphic(-1, $GUI_GR_LINE, 20, 40) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0xff0000) GUICtrlSetGraphic(-1, $GUI_GR_DOT, 25, 25) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0) GUICtrlSetGraphic(-1, $GUI_GR_LINE, 40, 40) GUICtrlSetGraphic(-1, $GUI_GR_DOT, 40, 40)

GUISetState() EndFunc ;==>CreateChild

Function Reference

GUICtrlCreateGroup
Creates a Group control for the GUI. GUICtrlCreateGroup ( "text", left, top [, width [, height [, style [, exStyle]]]] ) Parameters text left top width height style exStyle Return Value Success: Failure: Remarks A group control is the thin line you see around controls (usually only Radio button) that visually groups them together. Only one Radio button within a Group can be selected at once. If you want to have multiple groups without the visible line then you must use GUIStartGroup() to group your Radio buttons. To use the values specified above you must #include <ButtonConstants.au3> in your script. Default resizing is $GUI_DOCKAUTO size and position will occur. Related GUICoordMode (Option), GUIStartGroup Example Returns the identifier (controlID) of the new control. Returns 0. The text of the control. The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default is the previously used width). [optional] The height of the control (default is the previously used height). [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : none. forc ed styles : $WS_GROUP, $BS_GROUPBOX. [optional] Defines the extended style of the control. See Extended Style Table.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $radio_1, $radio_2, $msg GUICreate("My GUI group") ; will create a dialog box that when displayed is centered GUICtrlCreateGroup("Group 1", 190, 60, 90, 140) $radio_1 = GUICtrlCreateRadio("Radio 1", 210, 90, 50, 20) $radio_2 = GUICtrlCreateRadio("Radio 2", 210, 110, 60, 50)

GUICtrlCreateGroup("", -99, -99, 1, 1) ;close group GUISetState() ; will display an empty dialog box ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUICtrlCreateIcon
Creates an Icon control for the GUI. GUICtrlCreateIcon ( filename, iconName, left, top [, width [, height [, style [, exStyle]]]] ) Parameters filename ic onName left top width height style exStyle Return Value Success: Failure: Remarks To set or change information in the control see GUICtrlUpdate.... To update the icon after the dialog box is displayed use GUICtrlSetImage iconID can reference the icon group number. Use a resource hacker to know the value. To combine styles with the default style use BitOr($GUI_SS_DEFAULT_ICON, newstyle,...). To use the values specified above you must #include <StaticConstants.au3> in your script. Default resizing is $GUI_DOCKSIZE. Passing a positive number will reference the string equivalent icon name. Passing a negative number causes 1-based "index" behaviour. Some Dll can have icon extracted just with negative numbers. Related GUICoordMode (Option), GUICtrlSetImage, GUICtrlUpdate..., GUIGetMsg Example Returns the identifier (controlID) of the new control. Returns 0. filename of the icon to be loaded. Icon name if the file contain multiple icon. Can be an ordinal name if negative number. Otherwise -1. The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default is 32). [optional] The height of the control (default is 32). [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : $SS_NOTIFY forced styles : $WS_TABSTOP, $SS_ICON [optional] Defines the extended style of the control. See Extended Style Table.

#include <GUIConstantsEx.au3>

Opt('MustDeclareVars', 1) Example1() Example2()

;example1 --------------------------Func Example1() Local $icon, $n1, $n2, $msg GUICreate(" My GUI Icons", 250, 250) $icon = GUICtrlCreateIcon("shell32.dll", 10, 20, 20) $n1 = GUICtrlCreateIcon(@WindowsDir & "\cursors\horse.ani", -1, 20, 40, 32, 32) $n2 = GUICtrlCreateIcon("shell32.dll", 7, 20, 75, 32, 32) GUISetState()

; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd GUIDelete() EndFunc ;==>Example1

; example2 --------------------------Func Example2() Local $iOldOpt, $n1, $n2, $a, $b $iOldOpt = Opt("GUICoordMode", 1) GUICreate("My GUI icon Race", 350, 74, -1, -1) GUICtrlCreateLabel("", 331, 0, 1, 74, 5) $n1 = GUICtrlCreateIcon(@WindowsDir & "\cursors\dinosaur.ani", -1, 0, 0, 32, 32) $n2 = GUICtrlCreateIcon(@WindowsDir & "\cursors\horse.ani", -1, 0, 40, 32, 32)

GUISetState(@SW_SHOW) Dim $a = 0, $b = 0 While ($a < 300) And ($b < 300) $a = $a + Int(Random(0, 1) + 0.5) $b = $b + Int(Random(0, 1) + 0.5) GUICtrlSetPos($n1, $a, 0) GUICtrlSetPos($n2, $b, 40) Sleep(20) WEnd Sleep(1000) Opt("GUICoordMode", $iOldOpt) EndFunc ;==>Example2

Function Reference

GUICtrlCreateInput
Creates an Input control for the GUI. GUICtrlCreateInput ( "text", left, top [, width [, height [, style [, exStyle]]]] ) Parameters text left top width height style exStyle Return Value Success: Failure: Remarks To obtain the value of the control see GUICtrlRead. To set or change information in the control see GUICtrlUpdate.... For defining an input control for entering passwords (input is hidden with an asterisk) use the $ES_PASSWORD style. If you want to drag & drop a filename onto this control just add the WS_EX_ACCEPTFILES extended style on the GUICreate() and set the state to $GUI_DROPACCEPTED. After multiple drag and drop files on this control, you can retrieve the files name which are separated by "|" with GuiCtrlRead. To use the values specified above you must #include <EditConstants.au3> in your script. Default resizing is $GUI_DOCKHEIGHT. Related GUICoordMode (Option), GUICtrlUpdate..., GUIGetMsg, GUICtrlRead, GUICtrlCreateUpdown, GUICtrlSetLimit Example Returns the identifier (controlID) of the new control. Returns 0. The text of the control. The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default is the previously used width). [optional] The height of the control (default is the previously used height). [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : $ES_LEFT, $ES_AUTOHSCROLL forced styles : $WS_TABSTOP only if no $ES_READONLY. $ES_MULTILINE is always reset. [optional] Defines the extended style of the control. See Extended Style Table.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example()

Local $file, $btn, $msg GUICreate(" My GUI input acceptfile", 320, 120, @DesktopWidth / 2 - 160, @DesktopHeight / 2 - 45, -1, 0x00000018); WS_EX_ACCEPTFILES $file = GUICtrlCreateInput("", 10, 5, 300, 20) GUICtrlSetState(-1, $GUI_DROPACCEPTED) GUICtrlCreateInput("", 10, 35, 300, 20) ; will not accept drag&drop files $btn = GUICtrlCreateButton("Ok", 40, 75, 60, 20) GUISetState() $msg = 0 While $msg <> $GUI_EVENT_CLOSE $msg = GUIGetMsg() Select Case $msg = $btn ExitLoop EndSelect WEnd

MsgBox(4096, "drag drop file", GUICtrlRead($file)) EndFunc ;==>Example

Function Reference

GUICtrlCreateLabel
Creates a static Label control for the GUI. GUICtrlCreateLabel ( "text", left, top [, width [, height [, style [, exStyle]]]] ) Parameters text left top width height style The text of the control. The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default text autofit in width). [optional] The height of the control (default text autofit in height). [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : none. forced styles : $SS_NOTIFY, $SS_LEFT exStyle Return Value Success: Failure: Remarks To set or change information in the control see GUICtrlUpdate.... To combine styles with the default style use BitOr($GUI_SS_DEFAULT_LABEL, newstyle,...). To use the values specified above you must #include <StaticConstants.au3> in your script. Default resizing is $GUI_DOCKAUTO size and position will occur. The extended style $GUI_WS_EX_PARENTDRAG can be used to allow the dragging of the parent window for windows that don't have a titlebar (no $WS_CAPTION style in GUICreate). To set the background to transparent, use GUICtrlSetBkColor(-1, $GUI_BKCOLOR_TRANSPARENT). Related GUICoordMode (Option), GUICtrlUpdate..., GUIGetMsg Example Returns the identifier (controlID) of the new control. Returns 0. [optional] Defines the extended style of the control. See Extended Style Table.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $widthCell, $msg, $iOldOpt

GUICreate("My GUI") ; will create a dialog box that when displayed is centered GUISetHelp("notepad") ; will run notepad if F1 is typed $iOldOpt = Opt("GUICoordMode", 2) $widthCell = 70 GUICtrlCreateLabel("Line GUICtrlCreateLabel("Line GUICtrlCreateLabel("Line GUICtrlCreateLabel("Line GUICtrlCreateLabel("Line

1 2 3 3 4

Cell Cell Cell Cell Cell

1", 1", 2", 3", 1",

10, 30, $widthCell) ; first cell 70 width -1, 0) ; next line 0, 0) ; next line and next cell 0, -1) ; next cell same line -3 * $widthCell, 0) ; next line Cell1

GUISetState() ; will display an empty dialog box ; Run the GUI until the dialog is closed Do $msg = GUIGetMsg() Until $msg = $GUI_EVENT_CLOSE

$iOldOpt = Opt("GUICoordMode", $iOldOpt) EndFunc ;==>Example

Function Reference

GUICtrlCreateList
Creates a List control for the GUI. GUICtrlCreateList ( "text", left, top [, width [, height [, style [, exStyle]]]] ) Parameters text left top width height style exStyle Return Value Success: Failure: Remarks To obtain the value of the control see GUICtrlRead. To set or change information in the control see GUICtrlUpdate.... The different list entries that can be selected can be set with GUICtrlSetData To limit horizontal scrolling use GUICtrlSetLimit To combine styles with the default style use BitOr($GUI_SS_DEFAULT_LIST, newstyle,...). To use the values specified above you must #include <ListBoxConstants.au3> in your script. Default resizing is $GUI_DOCKAUTO size and position will occur. Related GUICoordMode (Option), GUICtrlSetData, GUICtrlSetLimit, GUICtrlUpdate..., GUIGetMsg Example Returns the identifier (controlID) of the new control. Returns 0. The text of the control. The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default is the previously used width). [optional] The height of the control (default is the previously used height). [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : $LBS_SORT, $WS_BORDER, $WS_VSCROLL forced styles : $WS_TABSTOP, $LBS_NOTIFY [optional] Defines the extended style of the control. See Extended Style Table.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $MESSAGE = "The following buttons have been clicked" Local $add, $clear, $mylist, $close, $msg

GUICreate("My GUI list") ; will create a dialog box that when displayed is centered $add = GUICtrlCreateButton("Add", 64, 32, 75, 25) $clear = GUICtrlCreateButton("Clear", 64, 72, 75, 25) $mylist = GUICtrlCreateList("buttons that have been clicked", 176, 32, 121, 97) GUICtrlSetLimit(-1, 200) ; to limit horizontal scrolling GUICtrlSetData(-1, $MESSAGE) $close = GUICtrlCreateButton("my closing button", 64, 160, 175, 25)

GUISetState() $msg = 0 While $msg <> $GUI_EVENT_CLOSE $msg = GUIGetMsg() Select Case $msg = $add GUICtrlSetData($mylist, "You clicked button No1|") Case $msg = $clear GUICtrlSetData($mylist, "") Case $msg = $close MsgBox(0, "", "the closing button has been clicked", 2) Exit EndSelect WEnd EndFunc ;==>Example

Function Reference

GUICtrlCreateListView
Creates a ListView control for the GUI. GUICtrlCreateListView ( "text", left, top [, width [, height [, style [, exStyle]]]] ) Parameters text left top width height style definition of columns heading. Each of them are separated with Opt("GUIDataSeparatorChar"). The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default is the previously used width). [optional] The height of the control (default is the previously used height). [optional] Defines the style of the control. See GUI Control Styles Appendix. default (-1) : $LVS_SHOWSELALWAYS, $LVS_SINGLESEL forced style : $LVS_REPORT [optional] Defines the extended style of the control. See Extended Style Table or ListView Extended Style Table.

exStyle Return Value Success: Failure: Remarks

Returns the identifier (controlID) of the new control. Returns 0.

To add items to a ListView control use GUICtrlCreateListViewItem The ListView will appear by default as in the Explorer view "Details" (LVS_REPORT style is forced). You can control initial column size by padding blanks to the column heading definition. The column can be extend during the GUICtrlCreateListViewItem according to item size. Size of a column will be up to around 25 characters. No resizing will be done during an update by GUICtrlSetData. To create a ListView with Icon-, SmallIc on- or List-style just use after creation: GUICtrlSetStyle with the styles $LVS_ICON, $LVS_LIST or $LVS_SMALLICON. Sorting the list by clicking the column name (as in Explorer) is not currently implemented. To have the entire line visually selected use the extended style LVS_EX_FULLROWSELECT. To combine styles with the default style use BitOr($GUI_SS_DEFAULT_LISTVIEW, newstyle,...). To use the values specified above you must #include <ListViewConstants.au3> in your script. The special flag $GUI_BKCOLOR_LV_ALTERNATE can be used with Listview control to give alternate background of the ListviewItems lines. The odd lines will get the color set by GUICtrlSetBkColor of the Listview control. The even lines will get the color set by GUICtrlSetBkColor of the ListviewItem control. Related GUICtrlCreateListViewItem, GUICtrlRegisterListViewSort, GUICoordMode (Option), GUICtrlSetData, GUIGetMsg, GUIDataSeparatorChar (Option)

Example

#include <GUIConstantsEx.au3> #include <WindowsConstants.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $listview, $button, $item1, $item2, $item3, $input1, $msg GUICreate("listview items", 220, 250, 100, 200, -1, $WS_EX_ACCEPTFILES) GUISetBkColor(0x00E0FFFF) ; will change background color $listview = GUICtrlCreateListView("col1 |col2|col3 ", 10, 10, 200, 150);,$LVS_SORTDESCENDING) $button = GUICtrlCreateButton("Value?", 75, 170, 70, 20) $item1 = GUICtrlCreateListViewItem("item2|col22|col23", $listview) $item2 = GUICtrlCreateListViewItem("item1|col12|col13", $listview) $item3 = GUICtrlCreateListViewItem("item3|col32|col33", $listview) $input1 = GUICtrlCreateInput("", 20, 200, 150) GUICtrlSetState(-1, $GUI_DROPACCEPTED) ; to allow drag and dropping GUISetState() GUICtrlSetData($item2, "ITEM1") GUICtrlSetData($item3, "||COL33") GUICtrlDelete($item1) Do $msg = GUIGetMsg() Select Case $msg = $button MsgBox(0, "listview item", GUICtrlRead(GUICtrlRead($listview)), 2) Case $msg = $listview MsgBox(0, "listview", "clicked=" & GUICtrlGetState($listview), 2) EndSelect Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example

Function Reference

GUICtrlCreateListViewItem
Creates a ListView item. GUICtrlCreateListViewItem ( "text", listviewID ) Parameters text listviewID Return Value Success: Failure: Remarks This function creates the individual ListView items that can be selected. The items function as normal controls and can be set with GUICtrlSetData. Items can be deleted as with any other control by using GUICtrlDelete. ListView items can be dragged and drop into an Edit or Input control with a $GUI_DROPACCEPTED state. See GUICtrlCreateListView about resizing of the column. The special flag $GUI_BKCOLOR_LV_ALTERNATE can be used with Listview control to give alternate background of the ListviewItems lines. The odd lines will get the color set by GUICtrlSetBkColor of the Listview control. The even lines will get the color set by GUICtrlSetBkColor of the ListviewItem control. Related GUICtrlCreateListView, GUICtrlSetData, GUICtrlSetState, GUICtrlDelete, GUIGetMsg, GUICtrlRead, GUIDataSeparatorChar (Option) Example Returns the identifier (controlID) of the new control. Returns 0. subitemtext separated with Opt("GUIDataSeparatorChar"). controlID of the ListView control holding the item.

#include <GUIConstantsEx.au3> #include <WindowsConstants.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $listview, $button, $item1, $item2, $item3, $input1, $msg GUICreate("listview items", 220, 250, 100, 200, -1, $WS_EX_ACCEPTFILES) GUISetBkColor(0x00E0FFFF) ; will change background color $listview = GUICtrlCreateListView("col1 |col2|col3 ", 10, 10, 200, 150);,$LVS_SORTDESCENDING) $button = GUICtrlCreateButton("Value?", 75, 170, 70, 20) $item1 = GUICtrlCreateListViewItem("item2|col22|col23", $listview) $item2 = GUICtrlCreateListViewItem("............item1|col12|col13", $listview) $item3 = GUICtrlCreateListViewItem("item3|col32|col33", $listview) $input1 = GUICtrlCreateInput("", 20, 200, 150) GUICtrlSetState(-1, $GUI_DROPACCEPTED) ; to allow drag and dropping

GUISetState() GUICtrlSetData($item2, "|ITEM1") GUICtrlSetData($item3, "||COL33") GUICtrlDelete($item1)

Do $msg = GUIGetMsg() Select Case $msg = $button MsgBox(0, "listview item", GUICtrlRead(GUICtrlRead($listview)), 2) Case $msg = $listview MsgBox(0, "listview", "clicked=" & GUICtrlGetState($listview), 2) EndSelect Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example

Function Reference

GUICtrlCreateMenu
Creates a Menu control for the GUI. GUICtrlCreateMenu ( "submenutext" [, menuID [, menuentry]] ) Parameters submenutext menuID menuentry Return Value Success: Failure: Remarks To set or change information in the control see GUICtrlUpdate.... Related GUICtrlSetState, GUIGetMsg, GUICtrlCreateMenuItem, GUICtrlGetHandle, GUICtrlCreateContextMenu Example Returns the identifier (controlID) of the new control. Returns 0. The submenu text. [optional] If defined, allows you to create a submenu in the referenced menu. If equal -1 it refers to first level menu. [optional] Allows you to define the entry number to be created. The entries are numbered starting at 0.

#include <GUIConstantsEx.au3> #include <StaticConstants.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $defaultstatus = "Ready", $status, $filemenu, $fileitem Local $helpmenu, $saveitem, $infoitem, $exititem, $recentfilesmenu Local $separator1, $viewmenu, $viewstatusitem, $okbutton, $cancelbutton Local $statuslabel, $msg, $file GUICreate("My GUI menu", 300, 200)

$filemenu = GUICtrlCreateMenu("&File") $fileitem = GUICtrlCreateMenuItem("Open", $filemenu) GUICtrlSetState(-1, $GUI_DEFBUTTON) $helpmenu = GUICtrlCreateMenu("?") $saveitem = GUICtrlCreateMenuItem("Save", $filemenu) GUICtrlSetState(-1, $GUI_DISABLE) $infoitem = GUICtrlCreateMenuItem("Info", $helpmenu) $exititem = GUICtrlCreateMenuItem("Exit", $filemenu) $recentfilesmenu = GUICtrlCreateMenu("Recent Files", $filemenu, 1)

$separator1 = GUICtrlCreateMenuItem("", $filemenu, 2) ; create a separator line

$viewmenu = GUICtrlCreateMenu("View", -1, 1) ; is created before "?" menu $viewstatusitem = GUICtrlCreateMenuItem("Statusbar", $viewmenu) GUICtrlSetState(-1, $GUI_CHECKED) $okbutton = GUICtrlCreateButton("OK", 50, 130, 70, 20) GUICtrlSetState(-1, $GUI_FOCUS) $cancelbutton = GUICtrlCreateButton("Cancel", 180, 130, 70, 20)

$statuslabel = GUICtrlCreateLabel($defaultstatus, 0, 165, 300, 16, BitOR($SS_SIMPLE, $SS_SUNKEN)) GUISetState() While 1 $msg = GUIGetMsg() If $msg = $fileitem Then $file = FileOpenDialog("Choose file...", @TempDir, "All (*.*)") If @error <> 1 Then GUICtrlCreateMenuItem($file, $recentfilesmenu) EndIf If $msg = $viewstatusitem Then If BitAND(GUICtrlRead($viewstatusitem), $GUI_CHECKED) = $GUI_CHECKED Then GUICtrlSetState($viewstatusitem, $GUI_UNCHECKED) GUICtrlSetState($statuslabel, $GUI_HIDE) Else GUICtrlSetState($viewstatusitem, $GUI_CHECKED) GUICtrlSetState($statuslabel, $GUI_SHOW) EndIf EndIf If $msg = $GUI_EVENT_CLOSE Or $msg = $cancelbutton Or $msg = $exititem Then ExitLoop If $msg = $infoitem Then MsgBox(0, "Info", "Only a test...") WEnd GUIDelete() EndFunc ;==>Example

Function Reference

GUICtrlCreateMenuItem
Creates a MenuItem control for the GUI. GUICtrlCreateMenuItem ( "text", menuID [, menuentry [, menuradioitem]] ) Parameters text menuID menuentry menuradioitem Return Value Success: Failure: Remarks To set or change information in the control see GUICtrlUpdate.... If the Text parameter is a "" then a separator line is created. GUICtrlSetState can be used as for other controls. See example. Related GUICtrlUpdate..., GUIGetMsg, GUICtrlCreateMenu, GUICtrlCreateContextMenu Example Returns the identifier (controlID) of the new control. Returns 0. The text of the control. Allows you to create a submenu in the referenced menu. If equal -1 it refers to the first level menu. [optional] Allows you to define the entry number to be created. The entries are numbered starting at 0. [optional] 0 (default) = create a normal menuitem, 1 = create a menuradioitem

#include <GUIConstantsEx.au3> #include <StaticConstants.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $defaultstatus, $status, $filemenu, $fileitem, $helpmenu, $saveitem Local $infoitem, $exititem, $recentfilesmenu, $separator1, $viewmenu Local $viewstatusitem, $okbutton, $cancelbutton, $statuslabel, $msg, $file GUICreate("My GUI menu", 300, 200) Global $defaultstatus = "Ready" Global $status $filemenu = GUICtrlCreateMenu("&File") $fileitem = GUICtrlCreateMenuItem("Open", $filemenu) GUICtrlSetState(-1, $GUI_DEFBUTTON) $helpmenu = GUICtrlCreateMenu("?") $saveitem = GUICtrlCreateMenuItem("Save", $filemenu) GUICtrlSetState(-1, $GUI_DISABLE)

$infoitem = GUICtrlCreateMenuItem("Info", $helpmenu) $exititem = GUICtrlCreateMenuItem("Exit", $filemenu) $recentfilesmenu = GUICtrlCreateMenu("Recent Files", $filemenu, 1) $separator1 = GUICtrlCreateMenuItem("", $filemenu, 2) ; create a separator line $viewmenu = GUICtrlCreateMenu("View", -1, 1) ; is created before "?" menu $viewstatusitem = GUICtrlCreateMenuItem("Statusbar", $viewmenu) GUICtrlSetState(-1, $GUI_CHECKED) $okbutton = GUICtrlCreateButton("OK", 50, 130, 70, 20) GUICtrlSetState(-1, $GUI_FOCUS) $cancelbutton = GUICtrlCreateButton("Cancel", 180, 130, 70, 20)

$statuslabel = GUICtrlCreateLabel($defaultstatus, 0, 165, 300, 16, BitOR($SS_SIMPLE, $SS_SUNKEN)) GUISetState() While 1 $msg = GUIGetMsg() If $msg = $fileitem Then $file = FileOpenDialog("Choose file...", @TempDir, "All (*.*)") If @error <> 1 Then GUICtrlCreateMenuItem($file, $recentfilesmenu) EndIf If $msg = $viewstatusitem Then If BitAND(GUICtrlRead($viewstatusitem), $GUI_CHECKED) = $GUI_CHECKED Then GUICtrlSetState($viewstatusitem, $GUI_UNCHECKED) GUICtrlSetState($statuslabel, $GUI_HIDE) Else GUICtrlSetState($viewstatusitem, $GUI_CHECKED) GUICtrlSetState($statuslabel, $GUI_SHOW) EndIf EndIf If $msg = $GUI_EVENT_CLOSE Or $msg = $cancelbutton Or $msg = $exititem Then ExitLoop If $msg = $infoitem Then MsgBox(0, "Info", "Only a test...") WEnd GUIDelete() EndFunc ;==>Example

Function Reference

GUICtrlCreateMonthCal
Creates a month calendar control for the GUI. GUICtrlCreateMonthCal ( "text", left, top [, width [, height [, style [, exStyle]]]] ) Parameters text left top width height style The preselected date (always as "yyyy/mm/dd"). The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default is the previously used width). [optional] The height of the control (default is the previously used height). [optional] Defines the style of the control. See GUI Control Styles Appendix. default (-1) : none. forced style : $WS_TABSTOP [optional] Defines the extended style of the control. See Extended Style Table. default (-1) : WS_EX_CLIENTEDGE

exStyle Return Value Success: Failure: Remarks

Returns the identifier (controlID) of the new control. Returns 0.

To obtain the value of the control see GUICtrlRead. Default resizing is $GUI_DOCKSIZE. Related GUICoordMode (Option), GUIGetMsg, GUICtrlRead Example

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $Date, $msg GUICreate("Get date", 210, 190) $Date = GUICtrlCreateMonthCal("1953/03/25", 10, 10) GUISetState() ; Run the GUI until the dialog is closed or timeout Do

$msg = GUIGetMsg() If $msg = $Date Then MsgBox(0, "debug", "calendar clicked") Until $msg = $GUI_EVENT_CLOSE MsgBox(0, $msg, GUICtrlRead($Date), 2) EndFunc ;==>Example

Function Reference

GUICtrlCreateObj
Creates an ActiveX control in the GUI. GUICtrlCreateObj ( ObjectVar, left, top [, width [, height ]] ) Parameters ObjectVar left top width height Return Value Success: Failure: Remarks This function attempts to embed an 'ActiveX Control' or a 'Document Object' inside the GUI. Not every control can be embedded. They must at least support an 'IDispatch' interface. 'Document Objects' will only be visible if the Windows style $WS_CLIPCHILDREN has been used in GUICreate(). The GUI functions GUICtrlRead and GUICtrlSet have no effect on this control. The object can only be controlled using 'methods' or 'properties' on the $ObjectVar. Related ObjCreate, ObjGet, ObjEvent, IsObj Example Returns the identifier (controlID) of the new control. Returns 0. A variable pointing to a previously opened object The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default is the previously used width). [optional] The height of the control (default is the previously used height).

#include <GUIConstantsEx.au3> #include <WindowsConstants.au3> Opt('MustDeclareVars', 1) Example() ; Simple example: Embedding an Internet Explorer Object inside an AutoIt GUI ; ; See also: http://msdn.microsoft.com/workshop/browser/webbrowser/reference/objects/internetexplorer.asp Func Example() Local $oIE, $GUIActiveX, $GUI_Button_Back, $GUI_Button_Forward Local $GUI_Button_Home, $GUI_Button_Stop, $msg $oIE = ObjCreate("Shell.Explorer.2") ; Create a simple GUI for our output GUICreate("Embedded Web control Test", 640, 580, (@DesktopWidth - 640) / 2,

(@DesktopHeight - 580) / 2, BitOR($WS_OVERLAPPEDWINDOW, $WS_CLIPSIBLINGS, $WS_CLIPCHILDREN)) $GUIActiveX = GUICtrlCreateObj ($oIE, 10, 40, 600, 360) $GUI_Button_Back = GUICtrlCreateButton("Back", 10, 420, 100, 30) $GUI_Button_Forward = GUICtrlCreateButton("Forward", 120, 420, 100, 30) $GUI_Button_Home = GUICtrlCreateButton("Home", 230, 420, 100, 30) $GUI_Button_Stop = GUICtrlCreateButton("Stop", 330, 420, 100, 30) GUISetState() ;Show GUI $oIE.navigate("http://www.autoitscript.com") ; Waiting for user to close the window While 1 $msg = GUIGetMsg() Select Case $msg = $GUI_EVENT_CLOSE ExitLoop Case $msg = $GUI_Button_Home $oIE.navigate("http://www.autoitscript.com") Case $msg = $GUI_Button_Back $oIE.GoBack Case $msg = $GUI_Button_Forward $oIE.GoForward Case $msg = $GUI_Button_Stop $oIE.Stop EndSelect WEnd

GUIDelete() EndFunc ;==>Example

Function Reference

GUICtrlCreatePic
Creates a Picture control for the GUI. GUICtrlCreatePic ( filename, left, top [, width [, height [, style [, exStyle]]]] ) Parameters filename left top width height style exStyle Return Value Success: Failure: Remarks To set or change information in the control see GUICtrlUpdate.... To update the picture after the dialog box is displayed just use GUICtrlSetImage If you want to have a picture having the same size as the file content just use width=height=0. To have a transparent picture it is needed to create the GUI window with WS_EX_LAYERED extended style. The left-top pixel will be used as the transparency color. If several pictures are created the last picture is defining the transparent color. See example 2. To combine styles with the default style use BitOr($GUI_SS_DEFAULT_PIC, newstyle,...). To use the values specified above you must #include <StaticConstants.au3> in your script. Default resizing is $GUI_DOCKSIZE. If a picture is set as a background picture, as the other controls will overlap, it's important to disable the pic control and create it after the others controls: GuiCtrlSetState(-1,$GUI_DISABLE). This is not enough for Tab or Listview control which behave differently. In this case you need to create the picture with the $WS_CLIPSIBLINGS style, GuiCtrlSetState(-1,$GUI_ONTOP) is necessary for the Tab, TreeView or Listview control. The extended style $GUI_WS_EX_PARENTDRAG can be used to allow the dragging of the parent window for windows that don't have a titlebar (no $WS_CAPTION style in GUICreate). The background is always set to transparent. GUICtrlSetBkColor() has not effect on pic control. PNG can be used with GDI+. See example 3. Returns the identifier (controlID) of the new control. Returns 0 if picture cannot be created. filename of the picture to be loaded : supported types BMP, JPG, GIF(but not animated). The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default is the previously used width). [optional] The height of the control (default is the previously used height). [optional] Defines the style of the control. See GUI Control Styles Appendix. default (-1) : $SS_NOTIFY forced style : $SS_BITMAP [optional] Defines the extended style of the control. See Extended Style Table.

Related GUICoordMode (Option), GUICtrlSetImage, GUICtrlUpdate..., GUIGetMsg Example

#include <GUIConstantsEx.au3> #include <WindowsConstants.au3> Opt('MustDeclareVars', 1) Global $gui, $guiPos, $pic, $picPos Example1() Example2() ;----- example 1 ---Func Example1() Local $n, $msg GUICreate("My GUI picture", 350, 300, -1, -1, $WS_SIZEBOX + $WS_SYSMENU) ; will create a dialog box that when displayed is centered GUISetBkColor(0xE0FFFF) $n = GUICtrlCreatePic("..\GUI\mslogo.jpg", 50, 50, 200, 50) GUISetState() ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd

; resize the control $n = GUICtrlSetPos($n, 50, 50, 200, 100) ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd GUIDelete() EndFunc ;==>Example1 ;----- example 2 Func Example2() Local $msg $gui = GUICreate("test transparentpic", 200, 100) $pic = GUICreate("", 68, 71, 10, 20, $WS_POPUP, BitOR($WS_EX_LAYERED, $WS_EX_MDICHILD), $gui) GUICtrlCreatePic("..\GUI\merlin.gif", 0, 0, 0, 0) GUISetState(@SW_SHOW, $pic) GUISetState(@SW_SHOW, $gui) HotKeySet("{ESC}", "main") HotKeySet("{LEFT}", "left") HotKeySet("{RIGHT}", "right") HotKeySet("{DOWN}", "down") HotKeySet("{UP}", "up")

$picPos = WinGetPos($pic) $guiPos = WinGetPos($gui) Do $msg = GUIGetMsg() Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example2 Func main() $guiPos = WinGetPos($gui) WinMove($gui, "", $guiPos[0] + 10, $guiPos[1] + 10) EndFunc ;==>main Func left() $picPos = WinGetPos($pic) WinMove($pic, "", $picPos[0] - 10, $picPos[1]) EndFunc ;==>left Func right() $picPos = WinGetPos($pic) WinMove($pic, "", $picPos[0] + 10, $picPos[1]) EndFunc ;==>right Func down() $picPos = WinGetPos($pic) WinMove($pic, "", $picPos[0], $picPos[1] + 10) EndFunc ;==>down Func up() $picPos = WinGetPos($pic) WinMove($pic, "", $picPos[0], $picPos[1] - 10) EndFunc ;==>up ;----- example 3 PNG work araund by Zedna #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <GDIPlus.au3> #Include <WinAPI.au3> Global $hGUI, $hImage, $hGraphic, $hImage1 ; Create GUI $hGUI = GUICreate("Show PNG", 250, 250) ; Load PNG image _GDIPlus_StartUp() $hImage = _GDIPlus_ImageLoadFromFile("..\GUI\Torus.png") $hGraphic = _GDIPlus_GraphicsCreateFromHWND($hGUI) GUIRegisterMsg($WM_PAINT, "MY_WM_PAINT") GUISetState() ; Loop until user exits do until GUIGetMsg() = $GUI_EVENT_CLOSE ; Clean up resources _GDIPlus_GraphicsDispose($hGraphic) _GDIPlus_ImageDispose($hImage) _GDIPlus_ShutDown() ; Draw PNG image Func MY_WM_PAINT($hWnd, $Msg, $wParam, $lParam) _WinAPI_RedrawWindow($hGUI, 0, 0, $RDW_UPDATENOW) _GDIPlus_GraphicsDrawImage($hGraphic, $hImage, 0, 0) _WinAPI_RedrawWindow($hGUI, 0, 0, $RDW_VALIDATE)

Return $GUI_RUNDEFMSG EndFunc

Function Reference

GUICtrlCreateProgress
Creates a Progress control for the GUI. GUICtrlCreateProgress ( left, top [, width [, height [, style [, exStyle]]]] ) Parameters left top width height style exStyle Return Value Success: Failure: Remarks To obtain the value of the control see GUICtrlRead. To set or change information in the control see GUICtrlUpdate.... To update the bar position just use GUICtrlSetData. To combine styles with the default style use BitOr($GUI_SS_DEFAULT_PROGRESS, newstyle,...). To use the values specified above you must #include <ProgressConstants.au3> in your script. Default resizing is $GUI_DOCKAUTO size and position will occur. Related GUICoordMode (Option), GUICtrlSetData, GUICtrlUpdate..., GUIGetMsg Example Returns the identifier (controlID) of the new control. Returns 0. The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default is the previously used width). [optional] The height of the control (default is the previously used height). [optional] Defines the style of the control. See GUI Control Styles Appendix. [optional] Defines the extended style of the control. See Extended Style Table.

#include <GUIConstantsEx.au3> #include <ProgressConstants.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $progressbar1, $progressbar2, $button, $wait, $s, $msg, $m GUICreate("My GUI Progressbar", 220, 100, 100, 200) $progressbar1 = GUICtrlCreateProgress(10, 10, 200, 20) GUICtrlSetColor(-1, 32250); not working with Windows XP Style $progressbar2 = GUICtrlCreateProgress(10, 40, 200, 20, $PBS_SMOOTH) $button = GUICtrlCreateButton("Start", 75, 70, 70, 20)

GUISetState() $wait = 20; wait 20ms for next progressstep $s = 0; progressbar-saveposition Do $msg = GUIGetMsg() If $msg = $button Then GUICtrlSetData($button, "Stop") For $i = $s To 100 If GUICtrlRead($progressbar1) = 50 Then MsgBox(0, "Info", "The half is done...", 1) $m = GUIGetMsg() If $m = -3 Then ExitLoop If $m = $button Then GUICtrlSetData($button, "Next") $s = $i;save the current bar-position to $s ExitLoop Else $s = 0 GUICtrlSetData($progressbar1, $i) GUICtrlSetData($progressbar2, (100 - $i)) Sleep($wait) EndIf Next If $i > 100 Then ; $s=0 GUICtrlSetData($button, "Start") EndIf EndIf Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example

Function Reference

GUICtrlCreateRadio
Creates a Radio button control for the GUI. GUICtrlCreateRadio ( "text", left, top [, width [, height [, style [, exStyle]]]] ) Parameters text left top width height style exStyle Return Value Success: Failure: Remarks To obtain the value of the control see GUICtrlRead. To set or change information in the control see GUICtrlUpdate.... To combine styles with the default style use BitOr($GUI_SS_DEFAULT_RADIO, newstyle,...). To use the values specified above you must #include <ButtonConstants.au3> in your script. Default resizing is $GUI_DOCKHEIGHT. Related GUICoordMode (Option), GUICtrlUpdate..., GUIGetMsg Example Returns the identifier (controlID) of the new control. Returns 0. The text of the control. The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default text autofit in width). [optional] The height of the control (default text autofit in height). [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : none. forced styles : $BS_AUTORADIOBUTTON and $WS_TABSTOP if first radio in the group. [optional] Defines the extended style of the control. See Extended Style Table.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $radio1, $radio2, $msg GUICreate("My GUI radio") ; will create a dialog box that when displayed is centered $radio1 = GUICtrlCreateRadio("Radio 1", 10, 10, 120, 20) $radio2 = GUICtrlCreateRadio("Radio 2", 10, 40, 120, 20) GUICtrlSetState($radio2, $GUI_CHECKED)

GUISetState() ; will display an dialog box with 1 checkbox ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() Select Case $msg = $GUI_EVENT_CLOSE ExitLoop Case $msg = $radio1 And BitAND(GUICtrlRead($radio1), $GUI_CHECKED) = $GUI_CHECKED MsgBox(64, 'Info:', 'You clicked the Radio 1 and it is Checked.') Case $msg = $radio2 And BitAND(GUICtrlRead($radio2), $GUI_CHECKED) = $GUI_CHECKED MsgBox(64, 'Info:', 'You clicked on Radio 2 and it is Checked.') EndSelect WEnd EndFunc ;==>Example

Function Reference

GUICtrlCreateSlider
Creates a Slider control for the GUI. GUICtrlCreateSlider ( left, top [, width [, height [, style [, exStyle]]]] ) Parameters left top width height style default (-1) : $TBS_AUTOTICKS exStyle Return Value Success: Failure: Remarks To obtain the value of the control see GUICtrlRead. To set or change information in the control see GUICtrlUpdate.... To update the bar position just use GUICtrlSetData. To set the min and max value use GUICtrlSetLimit. To combine styles with the default style use BitOr($GUI_SS_DEFAULT_SLIDER, newstyle,...). To use the values specified above you must #include <SliderConstants.au3> in your script. Default resizing is $GUI_DOCKAUTO size and position will occur. Related GUICoordMode (Option), GUICtrlSetData, GUICtrlSetLimit, GUICtrlUpdate..., GUIGetMsg Example Returns the identifier (controlID) of the new control. Returns 0. [optional] Defines the extended style of the control. See Extended Style Table. The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default is the previously used width). [optional] The height of the control (default is the previously used height). [optional] Defines the style of the control. See GUI Control Styles Appendix.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $slider1, $button, $msg GUICreate("slider", 220, 100, 100, 200) GUISetBkColor(0x00E0FFFF) ; will change background color

$slider1 = GUICtrlCreateSlider(10, 10, 200, 20) GUICtrlSetLimit(-1, 200, 0) ; change min/max value $button = GUICtrlCreateButton("Value?", 75, 70, 70, 20) GUISetState() GUICtrlSetData($slider1, 45) ; set cursor

Do $msg = GUIGetMsg() If $msg = $button Then MsgBox(0, "slider1", GUICtrlRead($slider1), 2) EndIf Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example

Function Reference

GUICtrlCreateTab
Creates a Tab control for the GUI. GUICtrlCreateTab ( left, top [, width [, height [, style [, exStyle]]]] ) Parameters left top width height style exStyle Return Value Success: Failure: Remarks This control is just a control in which the tabitem controls will be created and after the specific control related to a specific tabitem will be created with GUICtrlCreate... controls. To set or change information in the control see GUICtrlUpdate.... To combine styles with the default style use BitOr($GUI_SS_DEFAULT_TAB, newstyle,...). To use the value specified above you must #include <TabConstants.au3> in your script. Default resizing is $GUI_DOCKSIZE. ONLY one Tab control can be created by window. But a script can creates several windows having a tab in. Related GUICtrlCreateTabItem, GUICoordMode (Option), GUICtrlCreate..., GUICtrlUpdate..., GUIGetMsg Example Returns the identifier (controlID) of the new control. Returns 0. The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default is the previously used width). [optional] The height of the control (default is the previously used height). [optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : none. forced styles : $WS_TABSTOP, $WS_CLIPSIBLINGS [optional] Defines the extended style of the control. See Extended Style Table.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $tab, $tab0, $tab0OK, $tab0input Local $tab1, $tab1combo, $tab1OK Local $tab2, $tab2OK, $msg

GUICreate("My GUI Tab") ; will create a dialog box that when displayed is centered GUISetBkColor(0x00E0FFFF) GUISetFont(9, 300) $tab = GUICtrlCreateTab(10, 10, 200, 100) $tab0 = GUICtrlCreateTabItem("tab0") GUICtrlCreateLabel("label0", 30, 80, 50, 20) $tab0OK = GUICtrlCreateButton("OK0", 20, 50, 50, 20) $tab0input = GUICtrlCreateInput("default", 80, 50, 70, 20) $tab1 = GUICtrlCreateTabItem("tab----1") GUICtrlCreateLabel("label1", 30, 80, 50, 20) $tab1combo = GUICtrlCreateCombo("", 20, 50, 60, 120) GUICtrlSetData(-1, "Trids|CyberSlug|Larry|Jon|Tylo", "Jon") ; default Jon $tab1OK = GUICtrlCreateButton("OK1", 80, 50, 50, 20) $tab2 = GUICtrlCreateTabItem("tab2") GUICtrlSetState(-1, $GUI_SHOW) ; will be display first GUICtrlCreateLabel("label2", 30, 80, 50, 20) $tab2OK = GUICtrlCreateButton("OK2", 140, 50, 50)

GUICtrlCreateTabItem("") ; end tabitem definition GUICtrlCreateLabel("label3", 20, 130, 50, 20) GUISetState() ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUICtrlCreateTabItem
Creates a TabItem control for the GUI. GUICtrlCreateTabItem ( "text" ) Parameters text Return Value Success: Failure: Remarks For setting more information see GUICtrlUpdate.... To select a specific tabitem to be shown when the dialog box open just issue a GUICtrlSetState(-1,$GUI_SHOW) see example. To terminate the tab control just create a last "tabitem" control with a null text "". The "tabitem" control cannot be painted (too much code ...). When advanced mode is used, GUICtrlRead($tab,1) will return the controlID instead of index of the clicked tab item. To create a new control on an existing tabitem use GUISwitch($hWin,$tabitem) to select it and just create your new control. Don't forget to close your tabitem creation with GUICtrlCreateTabItem(""). Related GUICtrlSetState, GUISwitch, GUIGetMsg, GUICtrlRead, GUIEventOptions (Option), GUICtrlCreateTab Example Returns the identifier (controlID) of the new control. Returns 0. The text of the control.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $tab, $tab0, $tab0OK, $tab0input Local $tab1, $tab1combo, $tab1OK Local $tab2, $tab2OK, $msg GUICreate("My GUI Tab", 250, 150); will create a dialog box that when displayed is centered GUISetBkColor(0x00E0FFFF) GUISetFont(9, 300) $tab = GUICtrlCreateTab(10, 10, 200, 100) $tab0 = GUICtrlCreateTabItem("tab0")

GUICtrlCreateLabel("label0", 30, 80, 50, 20) $tab0OK = GUICtrlCreateButton("OK0", 20, 50, 50, 20) $tab0input = GUICtrlCreateInput("default", 80, 50, 70, 20) $tab1 = GUICtrlCreateTabItem("tab----1") GUICtrlCreateLabel("label1", 30, 80, 50, 20) $tab1combo = GUICtrlCreateCombo("", 20, 50, 60, 120) GUICtrlSetData(-1, "Trids|CyberSlug|Larry|Jon|Tylo", "Jon"); default Jon $tab1OK = GUICtrlCreateButton("OK1", 80, 50, 50, 20) $tab2 = GUICtrlCreateTabItem("tab2") GUICtrlSetState(-1, $GUI_SHOW); will be display first GUICtrlCreateLabel("label2", 30, 80, 50, 20) $tab2OK = GUICtrlCreateButton("OK2", 140, 50, 50)

GUICtrlCreateTabItem(""); end tabitem definition GUICtrlCreateLabel("Click on tab and see the title", 20, 130, 250, 20) GUISetState() ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop If $msg = $tab Then ; display the clicked tab WinSetTitle("My GUI Tab", "", "My GUI Tab" & GUICtrlRead($tab)) EndIf WEnd EndFunc ;==>Example

Function Reference

GUICtrlCreateTreeView
Creates a TreeView control for the GUI. GUICtrlCreateTreeView ( left, top [, width [, height [, style [, exStyle]]]] ) Parameters left top width height The left side of the control. If -1 is used then left will be computed according to GUICoordMode. The top of the control. If -1 is used then top will be computed according to GUICoordMode. [optional] The width of the control (default is the previously used width). [optional] The height of the control (default is the previously used height). [optional] Defines the style of the control. See GUI Control Styles Appendix. style default (-1) : $TVS_HASBUTTONS, $TVS_HASLINES, $TVS_LINESATROOT, $TVS_DISABLEDRAGDROP, $TVS_SHOWSELALWAYS forced style : $WS_TABSTOP [optional] Defines the extended style of the control. See Extended Style Table.

exStyle Return Value Success: Failure: Remarks

Returns the identifier (controlID) of the new control. Returns 0.

To set or change information in the control see GUICtrlUpdate.... To combine styles with the default style use BitOr($GUI_SS_DEFAULT_TREEVIEW, newstyle,...). To use the values specified above you must #include <TreeViewConstants.au3> in your script. Related GUICtrlCreateTreeViewItem, GUICoordMode (Option), GUICtrlUpdate..., GUIGetMsg, GUICtrlRead Example

#include #include #include #include

<GUIConstantsEx.au3> <WindowsConstants.au3> <TreeViewConstants.au3> <StaticConstants.au3>

Opt('MustDeclareVars', 1) Example() Func Example() Local $treeview, $generalitem, $displayitem, $aboutitem, $compitem Local $useritem, $resitem, $otheritem, $startlabel, $aboutlabel, $compinfo Local $togglebutton, $infobutton, $statebutton, $cancelbutton Local $msg, $item, $hItem, $text GUICreate("My GUI with treeview", 350, 215)

$treeview = GUICtrlCreateTreeView(6, 6, 100, 150, BitOR($TVS_HASBUTTONS, $TVS_HASLINES, $TVS_LINESATROOT, $TVS_DISABLEDRAGDROP, $TVS_SHOWSELALWAYS), $WS_EX_CLIENTEDGE) $generalitem = GUICtrlCreateTreeViewItem("General", $treeview) GUICtrlSetColor(-1, 0x0000C0) $displayitem = GUICtrlCreateTreeViewItem("Display", $treeview) GUICtrlSetColor(-1, 0x0000C0) $aboutitem = GUICtrlCreateTreeViewItem("About", $generalitem) $compitem = GUICtrlCreateTreeViewItem("Computer", $generalitem) $useritem = GUICtrlCreateTreeViewItem("User", $generalitem) $resitem = GUICtrlCreateTreeViewItem("Resolution", $displayitem) $otheritem = GUICtrlCreateTreeViewItem("Other", $displayitem) $startlabel = GUICtrlCreateLabel("TreeView Demo", 190, 90, 100, 20) $aboutlabel = GUICtrlCreateLabel("This little scripts demonstates the using of a treeview-control.", 190, 70, 100, 60) GUICtrlSetState(-1, $GUI_HIDE) ; Hides the "aboutlabel"-text during initialization $compinfo = GUICtrlCreateLabel("Name:" & @TAB & @ComputerName & @LF & "OS:" & @TAB & @OSVersion & @LF & "SP:" & @TAB & @OSServicePack, 120, 30, 200, 80) GUICtrlSetState(-1, $GUI_HIDE) ; Hides the "compinfo"-text during initialization GUICtrlCreateLabel("", 0, 170, 350, 2, $SS_SUNKEN) $togglebutton = GUICtrlCreateButton("&Toggle", 35, 185, 70, 20) $infobutton = GUICtrlCreateButton("&Info", 105, 185, 70, 20) $statebutton = GUICtrlCreateButton("Col./Exp.", 175, 185, 70, 20) $cancelbutton = GUICtrlCreateButton("&Cancel", 245, 185, 70, 20)

GUICtrlSetState($generalitem, BitOR($GUI_EXPAND, $GUI_DEFBUTTON)) ; Expand the "General"-item and paint in bold GUICtrlSetState($displayitem, BitOR($GUI_EXPAND, $GUI_DEFBUTTON)) ; Expand the "Display"-item and paint in bold GUISetState() While 1 $msg = GUIGetMsg() Select Case $msg = $cancelbutton Or $msg = $GUI_EVENT_CLOSE ExitLoop Case $msg = $togglebutton ; Toggle the bold painting If BitAND(GUICtrlRead($generalitem), $GUI_DEFBUTTON) Then GUICtrlSetState($generalitem, 0) GUICtrlSetState($displayitem, 0) Else GUICtrlSetState($generalitem, $GUI_DEFBUTTON) GUICtrlSetState($displayitem, $GUI_DEFBUTTON) EndIf

Case $msg = $infobutton $item = GUICtrlRead($treeview) ; Get the controlID of the current selected treeview item If $item = 0 Then MsgBox(64, "TreeView Demo", "No item currently selected") Else $text = GUICtrlRead($item, 1) ; Get the text of the treeview item If $text == "" Then MsgBox(16, "Error", "Error while retrieving infos about item") Else MsgBox(64, "TreeView Demo", "Current item selected is: " & $text) ; $advmsg[0] contains the text and $advmsg[1] the state value of the treeview item EndIf EndIf Case $msg = $statebutton $item = GUICtrlRead($treeview) If $item > 0 Then

$hItem = GUICtrlGetHandle($item) GUICtrlSendMsg($treeview, $TVM_EXPAND, $TVE_TOGGLE, $hItem) EndIf and ; The following items will hide the other labels (1st and 2nd parameter) then show the 'own' labels (3rd and 4th parameter) Case $msg = $generalitem GUIChangeItems($aboutlabel, $compinfo, $startlabel, $startlabel)

Case $msg = $aboutitem GUICtrlSetState($compinfo, $GUI_HIDE) GUIChangeItems($startlabel, $startlabel, $aboutlabel, $aboutlabel) Case $msg = $compitem GUIChangeItems($startlabel, $aboutlabel, $compinfo, $compinfo) EndSelect WEnd

GUIDelete() EndFunc ;==>Example Func GUIChangeItems($hidestart, $hideend, $showstart, $showend) Local $idx For $idx = $hidestart To $hideend GUICtrlSetState($idx, $GUI_HIDE) Next For $idx = $showstart To $showend GUICtrlSetState($idx, $GUI_SHOW) Next EndFunc ;==>GUIChangeItems

Function Reference

GUICtrlCreateTreeViewItem
Creates a TreeViewItem control for the GUI. GUICtrlCreateTreeViewItem ( "text", treeviewID ) Parameters text treeviewID Return Value Success: Failure: Remarks For setting more information see GUICtrlUpdate.... To paint a treeview item in bold (to show as default) use GuiCtrlSetState($treeviewItem, $GUI_DEFBUTTON), to turn off this behaviour use GUICtrlSetState() with another value but $GUI_DEFBUTTON, for instance GuiCtrlSetState($treeviewItem, 0). To expand a treeview item use GuiCtrlSetState($treeviewItem, $GUI_EXPAND). To select a specific treeview item use GuiCtrlSetState($treeviewItem, $GUI_FOCUS). Related GUICtrlCreateTreeView, GUICtrlUpdate..., GUIGetMsg, GUICtrlRead, GUICtrlGetHandle Example Returns the identifier (controlID) of the new control. Returns 0. The text of the control. treeview identifier as return by treeview or treeviewitem creation if subtree is created.

#include #include #include #include

<GUIConstantsEx.au3> <WindowsConstants.au3> <TreeViewConstants.au3> <StaticConstants.au3>

Opt('MustDeclareVars', 1) Example() Func Example() Local $treeview, $generalitem, $displayitem, $aboutitem, $compitem Local $useritem, $resitem, $otheritem, $startlabel, $aboutlabel Local $compinfo, $togglebutton, $infobutton, $statebutton, $cancelbutton Local $msg, $item, $text, $hItem GUICreate("My GUI with treeview", 350, 215) $treeview = GUICtrlCreateTreeView(6, 6, 100, 150, BitOR($TVS_HASBUTTONS, $TVS_HASLINES, $TVS_LINESATROOT, $TVS_DISABLEDRAGDROP, $TVS_SHOWSELALWAYS), $WS_EX_CLIENTEDGE) $generalitem = GUICtrlCreateTreeViewItem("General", $treeview) GUICtrlSetColor(-1, 0x0000C0) $displayitem = GUICtrlCreateTreeViewItem("Display", $treeview) GUICtrlSetColor(-1, 0x0000C0)

$aboutitem = GUICtrlCreateTreeViewItem("About", $generalitem) $compitem = GUICtrlCreateTreeViewItem("Computer", $generalitem) $useritem = GUICtrlCreateTreeViewItem("User", $generalitem) $resitem = GUICtrlCreateTreeViewItem("Resolution", $displayitem) $otheritem = GUICtrlCreateTreeViewItem("Other", $displayitem)

$startlabel = GUICtrlCreateLabel("TreeView Demo", 190, 90, 100, 20) $aboutlabel = GUICtrlCreateLabel("This little scripts demonstates the using of a treeview-control.", 190, 70, 100, 60) GUICtrlSetState(-1, $GUI_HIDE) ; Hides the "aboutlabel"-text during initialization $compinfo = GUICtrlCreateLabel("Name:" & @TAB & @ComputerName & @LF & "OS:" & @TAB & @OSVersion & @LF & "SP:" & @TAB & @OSServicePack, 120, 30, 200, 80) GUICtrlSetState(-1, $GUI_HIDE) ; Hides the "compinfo"-text during initialization GUICtrlCreateLabel("", 0, 170, 350, 2, $SS_SUNKEN) $togglebutton = GUICtrlCreateButton("&Toggle", 35, 185, 70, 20) $infobutton = GUICtrlCreateButton("&Info", 105, 185, 70, 20) $statebutton = GUICtrlCreateButton("Col./Exp.", 175, 185, 70, 20) $cancelbutton = GUICtrlCreateButton("&Cancel", 245, 185, 70, 20)

GUICtrlSetState($generalitem, BitOR($GUI_EXPAND, $GUI_DEFBUTTON)) ; Expand the "General"-item and paint in bold GUICtrlSetState($displayitem, BitOR($GUI_EXPAND, $GUI_DEFBUTTON)) ; Expand the "Display"-item and paint in bold GUISetState() While 1 $msg = GUIGetMsg() Select Case $msg = $cancelbutton Or $msg = $GUI_EVENT_CLOSE ExitLoop Case $msg = $togglebutton ; Toggle the bold painting If BitAND(GUICtrlRead($generalitem), $GUI_DEFBUTTON) Then GUICtrlSetState($generalitem, 0) GUICtrlSetState($displayitem, 0) Else GUICtrlSetState($generalitem, $GUI_DEFBUTTON) GUICtrlSetState($displayitem, $GUI_DEFBUTTON) EndIf

Case $msg = $infobutton $item = GUICtrlRead($treeview) ; Get the controlID of the current selected treeview item If $item = 0 Then MsgBox(64, "TreeView Demo", "No item currently selected") Else $text = GUICtrlRead($item, 1) ; Get the text of the treeview item If $text == "" Then MsgBox(16, "Error", "Error while retrieving infos about item") Else MsgBox(64, "TreeView Demo", "Current item selected is: " & $text) EndIf EndIf Case $msg = $statebutton $item = GUICtrlRead($treeview) If $item > 0 Then $hItem = GUICtrlGetHandle($item) DllCall("user32.dll", "int", "SendMessage", "hwnd", GUICtrlGetHandle ($treeview), "int", $TVM_EXPAND, "int", $TVE_TOGGLE, "hwnd", $hItem) EndIf ; The following items will hide the other labels (1st and 2nd parameter) and then show the 'own' labels (3rd and 4th parameter) Case $msg = $generalitem

GUIChangeItems($aboutlabel, $compinfo, $startlabel, $startlabel) Case $msg = $aboutitem GUICtrlSetState($compinfo, $GUI_HIDE) GUIChangeItems($startlabel, $startlabel, $aboutlabel, $aboutlabel) Case $msg = $compitem GUIChangeItems($startlabel, $aboutlabel, $compinfo, $compinfo) EndSelect WEnd

GUIDelete() EndFunc ;==>Example Func GUIChangeItems($hidestart, $hideend, $showstart, $showend) Local $idx For $idx = $hidestart To $hideend GUICtrlSetState($idx, $GUI_HIDE) Next For $idx = $showstart To $showend GUICtrlSetState($idx, $GUI_SHOW) Next EndFunc ;==>GUIChangeItems

Function Reference

GUICtrlCreateUpdown
Creates an UpDown control for the GUI. GUICtrlCreateUpdown ( inputcontrolID [,style] ) Parameters inputcontrolID style The controlID of the input control in which the updown control will be created. [optional] Defines the style of the control. See GUI Control Styles Appendix. default (-1) : $UDS_ALIGNRIGHT . forc ed style : $UDS_SETBUDDYINT and $UDS_ALIGNRIGHT if no align defined.

Return Value Success: Failure: Remarks To use the values specified above you must #include <UpDownConstants.au3> in your script. Max and min value can be set with GUICtrlSetLimit. By default Windows increases the value when clicking the upper arrow button. Default height resizing is done according to the one of the related input control. Related GUICtrlCreateInput, GUICtrlSetData, GUICtrlSetLimit Example Returns the identifier (controlID) of the new control. Returns 0.

#include <GUIConstantsEx.au3> #include <WindowsConstants.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $title, $input, $updown, $msg $title = "My GUI UpDown" GUICreate($title, -1, -1, -1, -1, $WS_SIZEBOX) $input = GUICtrlCreateInput("2", 10, 10, 50, 20) $updown = GUICtrlCreateUpdown($input) ; Attempt to resize input control GUICtrlSetPos($input, 10, 10, 100, 40) GUISetState() ; Run the GUI until the dialog is closed

While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd

MsgBox(0, "Updown", GUICtrlRead($input)) EndFunc ;==>Example

Function Reference

GUICtrlDelete
Deletes a control. GUICtrlDelete ( controlID ) Parameters controlID Return Value Success: Failure: Remarks For context menu controls see GUICtrlCreateContextMenu remarks. Related GUICreate, GUICtrlCreate..., GUICtrlCreateContextMenu Example Returns 1. Returns 0. The control identifier (controlID) as returned by a GUICtrlCreate... function.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $date, $del, $msg GUICreate("My GUI delete control", 200, 200, 800, 200) $date = GUICtrlCreateDate("1953/04/25", 10, 10, 185, 20) $del = GUICtrlCreateButton("Delete control", 50, 50, 70, 20) GUISetState() ; Run the GUI until the dialog is closed Do $msg = GUIGetMsg() If $msg = $del Then GUICtrlDelete($date) GUICtrlDelete($del) EndIf Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example

GUI Control update functions Reference


Below is a complete list of the functions available in AutoIt. Click on a function name for a detailed description. See Gui Constants include files if you need to use the related controls Constants . Function Description

GUICtrlRegisterListViewSort Register a user defined function for an internal listview sorting callback function. GUICtrlSetBkColor GUICtrlSetColor GUICtrlSetCursor GUICtrlSetData GUICtrlSetDefBkColor GUICtrlSetDefColor GUICtrlSetFont GUICtrlSetGraphic GUICtrlSetImage GUICtrlSetLimit GUICtrlSetOnEvent GUICtrlSetPos GUICtrlSetResizing GUICtrlSetState GUICtrlSetStyle GUICtrlSetTip Sets the background color of a control. Sets the text color of a control. Sets the mouse cursor icon for a particular control. Modifies the data for a control. Sets the default background color of all the controls of the GUI window. Sets the default text color of all the controls of the GUI window. Sets the font for a control. Modifies the data for a control. Sets the bitmap or icon image to use for a control. Limits the number of characters/pixels for a control. Defines a user-defined function to be called when a control is clicked. Changes the position of a control within the GUI window. Defines the resizing method used by a control. Changes the state of a control. Changes the style of a control. Sets the tip text associated with a control.

Function Reference

GUICtrlRegisterListViewSort
Register a user defined function for an internal listview sorting callback function. GUICtrlRegisterListViewSort ( controlID, "function" ) Parameters controlID function Return Value Success: Failure: Remarks !!! To make the user function workable you have to define it with maximum 4 function parameters otherwise the function won't be called !!! i.e: Func MySortFunction($nListViewID, $LParam1, $LParam2, $nColumn) ... EndFunc Or Func MySortFunction($nListViewID, $LParam1, $LParam2) ... EndFunc When the user function is called then these 4 parameters have the following values: Position 1 2 3 4 Parameter controlID lParam1 lParam2 c olumn Meaning The controlID of the listview control for which the callback function is used. The lParam value of the first item (by default the item controlID). The lParam value of the second item (by default the item controlID). The column that was clicked for sorting (the first column number is 0). 1 0 The listview controlID for which the user function should proceed. The name of the user function to call when the sorting callback runs.

The following values have to be Returned to change the behaviour of the sorting callback: Return value -1 0 1 Meaning 1st item should precede the 2nd. No Change. 1st item should follow the 2nd.

See also examples for sorting with selfcreated GUI listview items. Related GUICtrlCreateListView Example

#include <GUIConstantsEx.au3>

#include <ListViewConstants.au3> Opt('MustDeclareVars', 1) Global Global Global Global $nCurCol = -1 $nSortDir = 1 $bSet = 0 $nCol = -1

Example1() Example2() ; ******************************************************* ; Example 1 - sorting 3 column's different ; ******************************************************* Func Example1() Local $hGUI, $lv, $lvi1, $lvi2, $lvi3, $msg $hGUI = GUICreate("Test", 300, 200) $lv = GUICtrlCreateListView("Column1|Col2|Col3", 10, 10, 280, 180) GUICtrlRegisterListViewSort(-1, "LVSort") ; Register the function "SortLV" for the sorting callback $lvi1 = GUICtrlCreateListViewItem("ABC|666|10.05.2004", $lv) GUICtrlSetImage(-1, "shell32.dll", 7) $lvi2 = GUICtrlCreateListViewItem("DEF|444|11.05.2005", $lv) GUICtrlSetImage(-1, "shell32.dll", 12) $lvi3 = GUICtrlCreateListViewItem("CDE|444|12.05.2004", $lv) GUICtrlSetImage(-1, "shell32.dll", 3)

GUISetState() While 1 $msg = GUIGetMsg() Switch $msg Case $GUI_EVENT_CLOSE ExitLoop Case $lv $bSet = 0 $nCurCol = $nCol GUICtrlSendMsg($lv, $LVM_SETSELECTEDCOLUMN, GUICtrlGetState($lv), 0) DllCall("user32.dll", "int", "InvalidateRect", "hwnd", GUICtrlGetHandle ($lv), "int", 0, "int", 1) EndSwitch WEnd GUIDelete() EndFunc ;==>Example1 ; Our sorting callback funtion Func LVSort($hWnd, $nItem1, $nItem2, $nColumn) Local $nSort, $val1, $val2, $nResult ; Switch the sorting direction If $nColumn = $nCurCol Then If Not $bSet Then $nSortDir = $nSortDir * - 1 $bSet = 1 EndIf Else $nSortDir = 1 EndIf $nCol = $nColumn $val1 = GetSubItemText($hWnd, $nItem1, $nColumn)

$val2 = GetSubItemText($hWnd, $nItem2, $nColumn) ; If it is the 3rd colum (column starts with 0) then compare the dates If $nColumn = 2 Then $val1 = StringRight($val1, 4) & StringMid($val1, 4, 2) & StringLeft($val1, 2) $val2 = StringRight($val2, 4) & StringMid($val2, 4, 2) & StringLeft($val2, 2) EndIf $nResult = 0 ; No change of item1 and item2 positions If $val1 < $val2 Then $nResult = -1 ; Put item2 before item1 ElseIf $val1 > $val2 Then $nResult = 1 ; Put item2 behind item1 EndIf

$nResult = $nResult * $nSortDir Return $nResult EndFunc ;==>LVSort

; Retrieve the text of a listview item in a specified column Func GetSubItemText($nCtrlID, $nItemID, $nColumn) Local $stLvfi = DllStructCreate("uint;ptr;int;int[2];int") Local $nIndex, $stBuffer, $stLvi, $sItemText DllStructSetData($stLvfi, 1, $LVFI_PARAM) DllStructSetData($stLvfi, 3, $nItemID) $stBuffer = DllStructCreate("char[260]") $nIndex = GUICtrlSendMsg($nCtrlID, $LVM_FINDITEM, -1, DllStructGetPtr($stLvfi)); $stLvi = DllStructCreate("uint;int;int;uint;uint;ptr;int;int;int;int") DllStructSetData($stLvi, DllStructSetData($stLvi, DllStructSetData($stLvi, DllStructSetData($stLvi, DllStructSetData($stLvi, 1, 2, 3, 6, 7, $LVIF_TEXT) $nIndex) $nColumn) DllStructGetPtr($stBuffer)) 260)

GUICtrlSendMsg($nCtrlID, $LVM_GETITEMA, 0, DllStructGetPtr($stLvi)); $sItemText = DllStructGetData($stBuffer, 1) $stLvi = 0 $stLvfi = 0 $stBuffer = 0 Return $sItemText EndFunc ;==>GetSubItemText

; ******************************************************* ; Example 2 - sorting with selfcreated items by DllCall ; ******************************************************* Func Example2() Local $hGUI, $lv, $msg $nCurCol = -1 $nSortDir = 1 $bSet = 0 $nCol = -1

$hGUI = GUICreate("Test", 300, 200)

$lv = GUICtrlCreateListView("Column1|Col2|Col3", 10, 10, 280, 180) GUICtrlRegisterListViewSort(-1, "LVSort2") ; Register the function "SortLV" for the sorting callback MyGUICtrlCreateListViewItem("ABC|666|10.05.2004", $lv, -1) MyGUICtrlCreateListViewItem("DEF|444|11.05.2005", $lv, -1) MyGUICtrlCreateListViewItem("CDE|444|12.05.2004", $lv, -1) GUISetState() While 1 $msg = GUIGetMsg() Switch $msg Case $GUI_EVENT_CLOSE ExitLoop Case $lv $bSet = 0 $nCurCol = $nCol GUICtrlSendMsg($lv, $LVM_SETSELECTEDCOLUMN, GUICtrlGetState($lv), 0) DllCall("user32.dll", "int", "InvalidateRect", "hwnd", ControlGetHandle ($hGUI, "", $lv), "int", 0, "int", 1) EndSwitch WEnd EndFunc ;==>Example2 ; Our sorting callback funtion Func LVSort2($hWnd, $nItem1, $nItem2, $nColumn) Local $nSort, $val1, $val2, $nResult ; Switch the sorting direction If $nColumn = $nCurCol Then If Not $bSet Then $nSortDir = $nSortDir * - 1 $bSet = 1 EndIf Else $nSortDir = 1 EndIf $nCol = $nColumn $val1 = GetSubItemText($hWnd, $nItem1, $nColumn) $val2 = GetSubItemText($hWnd, $nItem2, $nColumn) ; If it is the 3rd colum (column starts with 0) then compare the dates If $nColumn = 2 Then $val1 = StringRight($val1, 4) & StringMid($val1, 4, 2) & StringLeft($val1, 2) $val2 = StringRight($val2, 4) & StringMid($val2, 4, 2) & StringLeft($val2, 2) EndIf $nResult = 0 ; No change of item1 and item2 positions If $val1 < $val2 Then $nResult = -1 ; Put item2 before item1 ElseIf $val1 > $val2 Then $nResult = 1 ; Put item2 behind item1 EndIf

$nResult = $nResult * $nSortDir Return $nResult EndFunc ;==>LVSort2

; Retrieve the text of a listview item in a specified column Func GetSubItemText2($nCtrlID, $nItemID, $nColumn) Local $stLvfi = DllStructCreate("uint;ptr;int;int[2];int")

Local $stBuffer, $nIndex, $stLvi, $sItemText DllStructSetData($stLvfi, 1, $LVFI_PARAM) ; Find the item by our saved index DllStructSetData($stLvfi, 3, $nItemID) $stBuffer = DllStructCreate("char[260]") $nIndex = GUICtrlSendMsg($nCtrlID, $LVM_FINDITEM, -1, DllStructGetPtr($stLvfi)); $stLvi = DllStructCreate("uint;int;int;uint;uint;ptr;int;int;int;int") DllStructSetData($stLvi, DllStructSetData($stLvi, DllStructSetData($stLvi, DllStructSetData($stLvi, DllStructSetData($stLvi, 1, 2, 3, 6, 7, $LVIF_TEXT) $nIndex) $nColumn) DllStructGetPtr($stBuffer)) 260)

GUICtrlSendMsg($nCtrlID, $LVM_GETITEMA, 0, DllStructGetPtr($stLvi)); $sItemText = DllStructGetData($stBuffer, 1) $stLvi = 0 $stLvfi = 0 $stBuffer = 0 Return $sItemText EndFunc ;==>GetSubItemText2

; Create and insert items directly into the listview Func MyGUICtrlCreateListViewItem($sText, $nCtrlID, $nIndex) Local $stLvItem = DllStructCreate("uint;int;int;uint;uint;ptr;int;int;int;int;") Local $stText = DllStructCreate("char[260]") Local $arText = StringSplit($sText, "|") If $nIndex = -1 Then $nIndex = GUICtrlSendMsg($nCtrlID, $LVM_GETITEMCOUNT, 0, 0) DllStructSetData($stText, 1, $arText[1]) ; Save the item text in the struct DllStructSetData($stLvItem, 1, BitOR($LVIF_TEXT, $LVIF_PARAM)) DllStructSetData($stLvItem, 2, $nIndex) DllStructSetData($stLvItem, 6, DllStructGetPtr($stText)) ; Set the lParam of the struct to the line index - unique within the listview DllStructSetData($stLvItem, 9, $nIndex) $nIndex = GUICtrlSendMsg($nCtrlID, $LVM_INSERTITEMA, 0, DllStructGetPtr($stLvItem)) If $nIndex > -1 Then ; Insert now the rest of the column text For $i = 2 To $arText[0] DllStructSetData($stText, 1, $arText[$i]) DllStructSetData($stLvItem, 3, $i - 1) ; Store the subitem index GUICtrlSendMsg($nCtrlID, $LVM_SETITEMTEXTA, $nIndex, DllStructGetPtr ($stLvItem)) Next EndIf $stText = 0 $stLvItem = 0 ; Change the column width to fit the item text For $i = 0 To 2 GUICtrlSendMsg($nCtrlID, $LVM_SETCOLUMNWIDTH, $i, -1) GUICtrlSendMsg($nCtrlID, $LVM_SETCOLUMNWIDTH, $i, -2) Next

EndFunc ;==>MyGUICtrlCreateListViewItem

Function Reference

GUICtrlSetBkColor
Sets the background color of a control. GUICtrlSetBkColor ( controlID, backgroundcolor ) Parameters controlID The control identifier (controlID) as returned by a GUICtrlCreate... function.

backgroundcolor The RGB color to use. Return Value Success: Failure: Remarks Only Button, Label, Checkbox, Group, Radio, Edit, Input, List, Listview, ListviewItem, Treeview, TreeviewItem, Graphic, Progress, Slider and Combo controls can currently be colored. Progress controls cannot be painted if the "Windows XP style" is used. Button controls are always painted in "Windows Classic style". They cannot have the $BS_ICON style. The special flag $GUI_BKCOLOR_TRANSPARENT can be used with Label, Group, Radio, Checkbox controls to give them a transparent background. The special flag $GUI_BKCOLOR_LV_ALTERNATE can be used with Listview control to give alternate background of the ListviewItems lines. The odd lines will get the color set by GUICtrlSetBkColor of the Listview control. The even lines will get the color set by GUICtrlSetBkColor of the ListviewItem control. Related GUICtrlCreate..., GUICtrlSetColor, GUICtrlSetDefBkColor Example Returns 1. Returns 0.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $msg GUICreate("My GUI background color") ; will create a dialog box that when displayed is centered GUICtrlCreateLabel("my label", 10, 20) GUICtrlSetBkColor(-1, 0x00ff00) ; Green GUISetState()

; Run the GUI until the dialog is closed

While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUICtrlSetColor
Sets the text color of a control. GUICtrlSetColor ( controlID, textcolor) Parameters controlID textcolor Return Value Success: Failure: Remarks Only Button, Label, Checkbox, Group, Radio, Edit, Input, List, Listview, ListviewItem, Treeview, TreeviewItem, Graphic, Progress and Combo controls can currently be colored. Checkbox, Radio, Group or Progress controls cannot be painted if the "Windows XP/Vista style" is used. Button controls are always painted in "Windows Classic style". Related GUICtrlCreate..., GUICtrlSetBkColor, GUICtrlSetDefColor Example Returns 1. Returns 0. The control identifier (controlID) as returned by a GUICtrlCreate... function. The RGB color to use.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $msg GUICreate("My GUI color text") ; will create a dialog box that when displayed is centered GUICtrlCreateLabel("my Red label", 10, 20) GUICtrlSetColor(-1, 0xff0000) ; Red GUISetState()

; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUICtrlSetCursor
Sets the mouse cursor icon for a particular control. GUICtrlSetCursor ( controlID, cursorID ) Parameters controlID c ursorID Return Value Success: Failure: Remarks Unlike GUISetCursor which changes the mouse cursor for an entire window, this function sets the mouse cursor that is used when the mouse is hovering over the specified control. If the cursorID is invalid the standard arrow will be displayed. For a list of valid cursor IDs see MouseGetCursor. CursorId = 16 will hide the mouse c ursor. Related GUISetCursor Example Returns 1. Returns 0. The control identifier (controlID) as returned by a GUICtrlCreate... function. cursor ID as used by Windows SetCursor API (use -1 for the default mouse cursor for the control)

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() GUICreate("put cursor over label", 300, 100) GUICtrlCreateLabel("label", 125, 40) GUICtrlSetCursor(-1, 4) GUISetState()

While GUIGetMsg() <> $GUI_EVENT_CLOSE WEnd EndFunc ;==>Example

Function Reference

GUICtrlSetData
Modifies the data for a control. GUICtrlSetData ( controlID, data [, default] ) Parameters controlID The control identifier (controlID) as returned by a GUICtrlCreate... function. Combo, List, ListView, ListViewItem: An Opt("GUIDataSeparatorChar",...) separated list of items. Progress: The percentage. Slider: The value. Group, Label, Button, Checkbox, Radio, Combo, List, Input, Edit, TabItem, TreeViewItem: Replaces the text. Date : The date or time depending the style of the control. Dummy: The value. [optional] Combo, List: The default value. Edit, Input: If non-empty (""), the string is inserted at the current insertion point (caret).

data

default Return Value Success: Failure: Remarks

Returns 1. Returns 0. Returns -1 in case of invalid data

For Combo or List control : If the "data" corresponds to an already existing entry it is set as the default. If the "data" starts with GUIDataSeparatorChar or is an empty string "" the previous list is destroyed. For ListView, ListViewItem controls : To update a specific column just forget about the others ie "||update" to update 3rd column. If "update" is empty the column/subitem will be erased. For example "|" will erase the second column/subitem, "" will erase the first. For Date, Monthcal controls : The "data" date format is "yyyy/mm/dd". Related GUICtrlCreate..., GUICtrlUpdate..., GUICtrlRead, GUIDataSeparatorChar (Option) Example

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $msg GUICreate("My GUI") ; will create a dialog box that when displayed is centered

GUICtrlCreateCombo("", 10, 10) GUICtrlSetData(-1, "item1|item2|item3", "item3") GUISetState() ; will display an empty dialog box with a combo control with focus on ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUICtrlSetDefBkColor
Sets the default background color of all the controls of the GUI window. GUICtrlSetDefBkColor ( defbkcolor [, winhandle] ) Parameters defbkcolor winhandle Return Value Success: Failure: Remarks None Related GUICreate, GUICtrlSetDefColor, GUICtrlSetBkColor Example Returns 1. Returns 0. Default background color for all controls. [optional] Windows handle as returned by GUICreate (default is the previously used window).

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $msg GUICreate("test GUISetTextColor", 100,100) ; will create a dialog box that when displayed is centered GUICtrlSetDefBkColor(0xFF0000) ; will change text color for all defined controls GUICtrlCreateLabel("label", 10,5) GUICtrlCreateRadio("radio", 10,25,50) GUICtrlSetBkColor(-1, 0x0000FF) ; will change text color for specified control GUICtrlCreateButton("button", 10,55) GUISetState() ; will display an empty dialog box

; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUICtrlSetDefColor
Sets the default text color of all the controls of the GUI window. GUICtrlSetDefColor ( deftextcolor [, winhandle] ) Parameters deftextcolor winhandle Return Value Success: Failure: Remarks None Related GUICreate, GUICtrlSetDefBkColor, GUICtrlSetColor Example Returns 1. Returns 0. Default text color for all controls. [optional] Windows handle as returned by GUICreate (default is the previously used window).

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $msg GUICreate("test GUISetTextColor", 100,100) ; will create a dialog box that when displayed is centered GUICtrlSetDefColor(0xFF0000) ; will change text color for all defined controls GUICtrlCreateLabel("label", 10,5) GUICtrlCreateRadio("radio", 10,25,50) GUICtrlSetColor(-1, 0x0000FF) ; will change text color for specified control GUICtrlCreateButton("button", 10,55) GUISetState() ; will display an empty dialog box

; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUICtrlSetFont
Sets the font for a control. GUICtrlSetFont (controlID, size [, weight [, attribute [, fontname[, quality]]]] ) Parameters controlID size weight attribute fontname quality Return Value Success: Failure: Remarks By default, controls use the font set by GUISetFont. Size can contain a decimal as in 8.5. For some controls such as labels, the default size can be 8.5 instead of 9 according to Windows Theme Values. See the Appendix for a complete list of Windows fonts and the Windows versions under which they are supported. For Quality parameter check MSDN, some windows XP installation need CLEARTYPE_QUALITY=5 Related GUICtrlCreate..., GUISetFont Example Returns 1. Returns 0. The control identifier (controlID) as returned by a GUICtrlCreate... function. Fontsize (default is 8.5). [optional] Font weight (default 400 = normal). [optional] To define italic:2 underlined:4 strike:8 char format (add together the values of all the styles required, 2+4 = italic and underlined). [optional] The name of the font to use. [optional] Font quality to select (default is PROOF_QUALITY=2).

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $font, $msg GUICreate("My GUI") ; will create a dialog box that when displayed is centered $font = "Comic Sans MS" GUICtrlCreateLabel("underlined label", 10, 20) GUICtrlSetFont(-1, 9, 400, 4, $font) ; will display underlined characters

GUICtrlCreateLabel("italic label", 10, 40) GUICtrlSetFont(-1, 9, 400, 2, $font) ; will display italic characters GUISetFont(9, 400, 8, $font) ; will display strike characters GUICtrlCreateLabel("strike label", 10, 60) GUISetState() ; will display an empty dialog box ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUICtrlSetGraphic
Modifies the data for a control. GUICtrlSetGraphic ( controlID, type [, par1 [, ... par6]] ) Parameters controlID type par1...par6 Return Value Success: Failure: Remarks The point position (x,y) is relative to the GUICtrlCreateGraphic coordinates. It can be outside the graphic control but inside of the GUI window. Graphic Type table Type $GUI_GR_COLOR $GUI_GR_MOVE $GUI_GR_DOT $GUI_GR_PIXEL $GUI_GR_LINE $GUI_GR_BEZIER $GUI_GR_RECT $GUI_GR_ELLIPSE $GUI_GR_PIE $GUI_GR_CLOSE $GUI_GR_REFRESH $GUI_GR_HINT $GUI_GR_PENSIZE Parameters Color [,BkColor] x,y x,y x,y x,y x,y,w,h x,y,w,h x,y,r,sa,wa n result Define the color of the next drawings. When BkColor is equal to $GUI_GR_NOBKCOLOR the drawing will not be filled. It is the default. For Color the default line color is black. Move the current position without drawing. Draw a point(smallest square around the point), the next drawing will start from previous position. Draw a pixel, the next drawing will start from previous position. Draw a line. Draw a rectangle. If w=h it will be a square. Draw an ellipse. If w=h it will be a circle. Draw a pie radius=r startangle=sa sweepangle=wa. Angles are in degrees. to close the current drawing. It has to be added to $GUI_GR_LINE or $GUI_GR_BEZIER to close current drawing. Use alone will be ignored. to force refresh after dynamic update of graphics. to display control point and end point of bezier/line curve. set pensize for the next drawings. It has to be defined before $GUI_GR_COLOR to be taken in account. is a dummy BkColor to force closed drawing not to be filled. Just line drawings. Returns 1. Returns 0. Returns -1 in case of invalid data The control identifier (controlID) as returned by a GUICtrlCreateGraphic function. type of drawing : dot, line, bezier, rect, ellipse, pie. See the Graphic Type table below.

x,y,x1,y1,x2,y2 Draw a bezier curve with 2 control points.

$GUI_GR_NOBKCOLOR

Due to design constraints RECT, ELLIPSE and PIE graphics are drawn first. For example, a LINE will always be drawn over a RECT. If the drawing order is important to the look of the graphic, then it is recommended that multiple graphic controls be used instead of using a single control to do all the drawing.

Related GUICtrlCreateGraphic Example

#include <GUIConstantsEx.au3> #include <StaticConstants.au3> Opt('MustDeclareVars', 1) Global $MAXGr = 6, $del, $child Global $a[$MAXGr + 1] ; 0 and $MAXGr entries not used to allow GUICtrlDelete result Example() Func Example() Local $msg, $inc, $i, $del1 GUICreate("My Main", -1, -1, 100, 100) $del1 = GUICtrlCreateButton("Delete", 50, 200, 50) GUISetState() CreateChild() $i = 1 $inc = 1 ;$i=5 ; uncomment to delete starting from last define Graphic control ;$inc=-1

Do $msg = GUIGetMsg() If $msg = $del1 Then $i = Del($inc) If $msg = $del Then GUICtrlDelete($a[$i]) $i = $i + $inc If $i < 0 Or $i > $MAXGr Then Exit EndIf Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example Func Del($iInc) GUIDelete($child) CreateChild() If $iInc = -1 Then Return 5 Return 1 EndFunc ;==>Del Func CreateChild() $child = GUICreate("My Draw") $del = GUICtrlCreateButton("Delete", 50, 165, 50) $a[1] = GUICtrlCreateGraphic(20, 50, 100, 100) GUICtrlSetBkColor(-1, 0xffffff) GUICtrlSetColor(-1, 0) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0xff0000, GUICtrlSetGraphic(-1, $GUI_GR_PIE, 50, 50, 40, GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0x00ff00, GUICtrlSetGraphic(-1, $GUI_GR_PIE, 58, 50, 40,

0xff0000) 30, 270) 0xffffff) -60, 90)

GUICtrlSetGraphic(-1, $GUI_GR_ELLIPSE, 100, 100, 50, 80) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0x00ff00, 0xc0c0ff) GUICtrlSetGraphic(-1, $GUI_GR_RECT, 350, 200, 50, 80) GUICtrlCreateLabel("label", 65, 100, 30) GUICtrlSetColor(-1, 0xff)

$a[2] = GUICtrlCreateGraphic(220, 10, 100, 100) GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0, 0xff) $GUI_GR_PIE, 50, 50, 40, 30, 270) $GUI_GR_COLOR, 0x00ff00, 0xffffff) $GUI_GR_PIE, 58, 50, 40, -60, 90)

$a[3] = GUICtrlCreateGraphic(220, 110, 100, 100) GUICtrlSetBkColor(-1, 0xf08080) GUICtrlSetColor(-1, 0xff) GUICtrlSetGraphic(-1, $GUI_GR_HINT, 1)

GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0xff00) GUICtrlSetGraphic(-1, $GUI_GR_RECT, 50, 50, 80, 80) $a[4] = GUICtrlCreateGraphic(20, 200, 80, 80) GUICtrlSetBkColor(-1, 0xffffff) GUICtrlSetGraphic(-1, $GUI_GR_HINT, 1) GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, $GUI_GR_MOVE, 10, 10) $GUI_GR_COLOR, 0xff) $GUI_GR_LINE, 30, 40) $GUI_GR_COLOR, 0xff00) $GUI_GR_LINE, 70, 70) $GUI_GR_COLOR, 0xff0000) $GUI_GR_LINE, 10, 50) $GUI_GR_COLOR, 0xffff00) $GUI_GR_LINE, 10, 10)

$a[5] = GUICtrlCreateGraphic(150, 10, 50, 50) GUICtrlSetBkColor(-1, 0xa0ffa0) GUICtrlSetGraphic(-1, $GUI_GR_MOVE, 20, 20) ; start point ; it is better to draw line and after point ; to avoid to switch color at each drawing GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0x0000ff) GUICtrlSetGraphic(-1, $GUI_GR_DOT, 30, 30) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0) GUICtrlSetGraphic(-1, $GUI_GR_LINE, 20, 40) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0xff0000) GUICtrlSetGraphic(-1, $GUI_GR_DOT, 25, 25) GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0) GUICtrlSetGraphic(-1, $GUI_GR_LINE, 40, 40) GUICtrlSetGraphic(-1, $GUI_GR_DOT, 30, 40) $a[6] = GUICtrlCreateGraphic(110, 260, 230, 130) GUICtrlSetColor(-1, 0) ; to display a black border line GUICtrlSetBkColor(-1, 0xc0c0ff) GUICtrlSetGraphic(-1, $GUI_GR_HINT, 3) ; to display control lines and end points GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, $GUI_GR_COLOR, 0, 0xff); fill in blue $GUI_GR_MOVE, 120, 20) ; start point $GUI_GR_BEZIER, 120, 100, 200, 20, 200, 100) $GUI_GR_BEZIER + $GUI_GR_CLOSE, 100, 40, 40, 100, 40, 20) $GUI_GR_LINE, 60, 30) ; start point

GUISetState() EndFunc ;==>CreateChild

Function Reference

GUICtrlSetImage
Sets the bitmap or icon image to use for a control. GUICtrlSetImage ( controlID, filename [, iconname [, icontype]] ) Parameters controlID filename ic onname icontype Return Value Success: Failure: Remarks Use a resource hacker to know the value of the valid icon name in a file. If used on a Button control the image will be displayed on the button. Images can also be set for Checkbox controls as long as the $BS_PUSHLIKE style is used. In both case the $BS_ICON or $BS_BITMAP styles are needed to select the type of the picture used. The first icon resolution will be used in a multi icon resolution file. I.E. if a 128x128 is the first resolution and the control is 64x64 the image will be truncated. !!! If use this command on a TreeViewItem the first time, then all other items will use this icon/image automatically by default !!! If you use GUICtrlSetImage on a TreeView or ListView then all items of it will change to this icon/image. Passing a positive number will reference the string equivalent icon name. Passing a negative number causes 1-based "index" behaviour. Some Dll can have icon extracted just with negative numbers. Related GUICtrlCreatePic, GUICtrlCreateIcon, GUICtrlCreateButton, GUICtrlCreateChec kbox Example Returns 1. Returns 0. The control identifier (controlID) as returned by a GUICtrlCreate... function. The filename containing the picture to be display on the control. [optional] Icon name if the file contain multiple icon. Can be an ordinal name if negative number. Otherwise -1. [optional] To select a specific icon size : 0 = small, 1 = normal (default). for a TreeViewItem the icon size : 2 = selected, 4 for non-selected item.

#include <GUIConstantsEx.au3> #include <ButtonConstants.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $msg GUICreate("My GUI") ; will create a dialog box that when displayed is centered GUICtrlCreateButton("my picture button", 10, 20, 40, 40, $BS_ICON)

GUICtrlSetImage(-1, "shell32.dll", 22) GUISetState() ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUICtrlSetLimit
Limits the number of characters/pixels for a control. GUICtrlSetLimit ( controlID, max [, min] ) Parameters controlID max min Return Value Success: Failure: Remarks None. Related GUICtrlCreateList, GUICtrlCreateInput, GUICtrlCreateEdit, GUICtrlCreateSlider, GUICtrlCreateUpdown Example Returns 1. Returns 0. The control identifier (controlID) as returned by a GUICtrlCreate... function. For List controls it is the extent you can scroll horizontally in pixels. For Input/Edit controls it is the max number of characters that can be entered. [optional] For Slider and UpDown controls you can specify a min value. Default = 0

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $msg GUICreate("My GUI limit input 3 chars") ; will create a dialog box that when displayed is centered GUICtrlCreateInput("", 10, 20) GUICtrlSetLimit(-1, 3) ; to limit the entry to 3 chars GUISetState()

; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUICtrlSetOnEvent
Defines a user-defined function to be called when a control is clicked. GUICtrlSetOnEvent ( controlID, "function" ) Parameters controlID function Return Value Success: Failure: Remarks OnEvent functions are only called when the option GUIOnEventMode is set to 1 - when in this mode GUIGetMsg is NOT used at all. Within the called user function the control identifier can be retrieved with @GUI_CTRLID. If needed the windows handle and the control handle can be retrieved with @GUI_WINHANDLE or @GUI_CT RLHANDLE. If the function is an empty string "" the previous user-defined is disabled. Related GUICtrlCreate..., GUIGetMsg, GUIOnEventMode (Option), GUISetOnEvent, GUICtrlCreateDummy, GUICtrlSendT oDummy Example Returns 1. Returns 0, The control identifier (controlID) as returned by a GUICtrlCreate... function. The name of the user function to call.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $parent1, $ok1, $cancel1 Opt("GUICoordMode", 2) Opt("GUIResizeMode", 1) Opt("GUIOnEventMode", 1) $parent1 = GUICreate("Parent1") GUISetOnEvent($GUI_EVENT_CLOSE, "SpecialEvents") GUISetOnEvent($GUI_EVENT_MINIMIZE, "SpecialEvents") GUISetOnEvent($GUI_EVENT_RESTORE, "SpecialEvents")

$ok1 = GUICtrlCreateButton("OK", 10, 30, 50) GUICtrlSetOnEvent(-1, "OKPressed") $cancel1 = GUICtrlCreateButton("Cancel", 0, -1) GUICtrlSetOnEvent(-1, "CancelPressed")

GUISetState(@SW_SHOW) ; Just idle around While 1 Sleep(10) WEnd

EndFunc ;==>Example Func OKPressed() MsgBox(0, "OK Pressed", "ID=" & @GUI_CtrlId & " WinHandle=" & @GUI_WinHandle & " CtrlHandle=" & @GUI_CtrlHandle) EndFunc ;==>OKPressed Func CancelPressed() MsgBox(0, "Cancel Pressed", "ID=" & @GUI_CtrlId & " WinHandle=" & @GUI_WinHandle & " CtrlHandle=" & @GUI_CtrlHandle) EndFunc ;==>CancelPressed Func SpecialEvents() Select Case @GUI_CtrlId = $GUI_EVENT_CLOSE MsgBox(0, "Close Pressed", "ID=" & @GUI_CtrlId & " WinHandle=" & @GUI_WinHandle) Exit Case @GUI_CtrlId = $GUI_EVENT_MINIMIZE MsgBox(0, "Window Minimized", "ID=" & @GUI_CtrlId & " WinHandle=" & @GUI_WinHandle) Case @GUI_CtrlId = $GUI_EVENT_RESTORE MsgBox(0, "Window Restored", "ID=" & @GUI_CtrlId & " WinHandle=" & @GUI_WinHandle) EndSelect EndFunc ;==>SpecialEvents

Function Reference

GUICtrlSetPos
Changes the position of a control within the GUI window. GUICtrlSetPos ( controlID, left, top [, width [, height]] ) Parameters controlID left top width height Return Value Success: Failure: Remarks None. Related GUICtrlCreate... Example Returns 1. Returns 0. The control identifier (controlID) as returned by a GUICtrlCreate... function. The left side of the control. The top of the control. [optional] The width of the control. [optional] The height of the control .

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $right, $label, $button, $msg GUICreate("My GUI position") ; will create a dialog box that when displayed is centered $right = 0 $label = GUICtrlCreateLabel("my moving label", 10, 20) $button = GUICtrlCreateButton("Click to close", 50, 50) GUICtrlSetState(-1, $GUI_FOCUS) ; the focus is on this button

GUISetState() While 1 $msg = GUIGetMsg() If $msg = $button Or $msg = $GUI_EVENT_CLOSE Then Exit If $right = 0 Then $right = 1

GUICtrlSetPos($label, 20, 20) Else $right = 0 GUICtrlSetPos($label, 10, 20) EndIf Sleep(100) WEnd EndFunc ;==>Example

Function Reference

GUICtrlSetResizing
Defines the resizing method used by a control. GUICtrlSetResizing ( controlID, resizing ) Parameters controlID resizing Return Value Success: Failure: Remarks When a GUI window is resized the controls within react - how they react is determined by this function. To be able to resize a GUI window it needs to have been created with the $WS_SIZEBOX and $WS_SYSMENU styles. See GUICreate. Docking Values Table Resizing $GUI_DOCKAUT O $GUI_DOCKLEFT $GUI_DOCKRIGHT $GUI_DOCKHCENT ER $GUI_DOCKT OP $GUI_DOCKBOTTOM $GUI_DOCKVCENT ER $GUI_DOCKWIDT H $GUI_DOCKHEIGHT $GUI_DOCKSIZE $GUI_DOCKMENUBAR Value No displacement of 1 2 4 8 32 64 128 256 512 768 544 resize and reposition according to new window size Left side Right side Position will not move relative to horizontal center Top side Bottom side Position will not move relative to vertical center Width will not change Height will not change Composite resizing (256+512) Size will not change (512+32) so the control will stay at the top of window with no change in Height (512+64) so the control stay at the bottom of the window with no change in Height (2+32+256+512) so the c ontrol will not move during resizing (2+4+32+64) so the control will grow as the window Returns 1. Returns 0. The control identifier (controlID) as returned by a GUICtrlCreate... function. See the Docking Values table below for values that can be used (add together multiple values if required).

$GUI_DOCKSTATEBAR 576 $GUI_DOCKALL $GUI_DOCKBORDERS 802 102

The default resizing for a given control is control dependent see the control doc. A default value for any control can be set with GUIResizeMode (Option). The automatic resizing event can be disabled if GUIEventOptions (Option) is set to 1. Related GUIResizeMode (Option), GUIEventOptions (Option), GUICtrlCreate...

Example

#include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <EditConstants.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $nEdit, $nOk, $nCancel, $msg Opt("GUICoordMode", 2) GUICreate("My InputBox", 190, 114, -1, -1, $WS_SIZEBOX + $WS_SYSMENU) ; start the definition GUISetIcon("Eiffel Tower.ico") GUISetFont(8, -1, "Arial") GUICtrlCreateLabel("Prompt", 8, 7) ; add prompt info GUICtrlSetResizing(-1, $GUI_DOCKLEFT + $GUI_DOCKTOP) $nEdit = GUICtrlCreateInput("Default", -1, 3, 175, 20, $ES_PASSWORD) ; add the input area GUICtrlSetState($nEdit, $GUI_FOCUS) GUICtrlSetResizing($nEdit, $GUI_DOCKBOTTOM + $GUI_DOCKHEIGHT) $nOk = GUICtrlCreateButton("OK", -1, 3, 75, 24) ; add the button that will close the GUI GUICtrlSetResizing($nOk, $GUI_DOCKBOTTOM + $GUI_DOCKSIZE + $GUI_DOCKHCENTER) $nCancel = GUICtrlCreateButton("Annuler", 25, -1) ; add the button that will close the GUI GUICtrlSetResizing($nCancel, $GUI_DOCKBOTTOM + $GUI_DOCKSIZE + $GUI_DOCKHCENTER) GUISetState() ; to display the GUI ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUICtrlSetState
Changes the state of a control. GUICtrlSetState ( controlID, state ) Parameters controlID state Return Value Success: Failure: Remarks State table State No Change $GUI_UNCHECKED $GUI_CHECKED $GUI_INDET ERMINAT E $GUI_AVISTART $GUI_AVISTOP $GUI_AVICLOSE $GUI_DROPACCEPT ED Comments 0 Radio, Checkbox or ListViewItem will be unchecked. Radio, Checkbox or ListViewItem will be checked. Checkbox having the tristate attribute will be greyed. Avi control will start playing. Avi control will stop playing. Avi control will stop playing and release resource. Control will accept drop action : from file or from a drag of another control. See remarks. Control will be visible. On Tabitem control will select the first tab to be displayed. Control will not be visible. Control will be enabled. Control will be greyed out. Control will be given input/selected focus. Listview control will loose focus. Control will be set as the default button on the window. See remark about TreeviewItems. TreeViewItem will expand it's child items. Control will be have the ontop attribute for the window (zOrdering). Returns 1. Returns 0. The control identifier (controlID) as returned by a GUICtrlCreate... function. See the State table below.

$GUI_NODROPACCEPT ED Control will not accept drop action. $GUI_SHOW $GUI_HIDE $GUI_ENABLE $GUI_DISABLE $GUI_FOCUS $GUI_NOFOCUS $GUI_DEFBUTTON $GUI_EXPAND $GUI_ONTOP

State values can be summed up as for example $GUI_DISABLE + $GUI_HIDE sets the control in an disabled and hidden state. If an AVI control has to be hidden with $GUI_HIDE it should be closed with $GUI_AVICLOSE. State of a "contextmenu" control cannot be changed. State of a "listviewitem" control can be changed if the associated "listview" control has been created with an extended style $LVS_EX_CHECKBOXES. $GUI_FOCUS and $GUI_NOFOCUS can be used on specific listviewitem provided listview control style allows to display it : $LVS_SHOWSELALWAYS.

State of a "menu or a ""menuitem" control cannot be hidden. ! Important information for $GUI_EXPAND: this state is only used for TreeViewItems. If you want to use this 'action' then at least 1 Sub-TreeViewItem has to exist/created under this item ! If you want to select another item in a TreeView then you can use $GUI_FOCUS - the parent TreeView gets the window focus and the specified item is marked as selected. If you want to set a treeview item as a default item which means painting it bold you can use $GUI_DEFBUTTON - to turn it off just use another value but $GUI_DEFBUTTON, for instance 0. This state will not be returned by GUICtrlGetState. If $GUI_DROPACCEPTED is set to a visible control a drag&drop can be taken in account. The edit/input control will be set with the filename. For other controls on reception of $GUI_EVENT_DROPPED, @GUI_DRAGID will return the controlID from where the drag start (-1 if from a file, @GUI_DRAGFILE c ontain the filename being dropped) and @GUI_DROPID returns the controlID of the dropped control. Only dragging a ListviewItem will start the drag & drop process. The @GUI_DRAGID will be the ListView controlID. Related GUICtrlCreate..., GUICtrlGetState Example

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $msg GUICreate("My GUI state") ; will create a dialog box that when displayed is centered GUICtrlCreateLabel("my disable label", 10, 20) GUICtrlSetState(-1, $GUI_DISABLE) ; the label is in disable state GUICtrlCreateButton("my button", 50, 50) GUICtrlSetState(-1, $GUI_FOCUS) ; the focus is on this button

GUISetState() ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUICtrlSetStyle
Changes the style of a control. GUICtrlSetStyle ( controlID, style [, exStyle] ) Parameters controlID style exStyle Return Value Success: Failure: Remarks Some styles cannot be changed dynamically, check MSDN documentation. $CBS_UPPERCASE combo style is one example. Related GUICtrlCreate... Example Returns 1. Returns 0. The control identifier (controlID) as returned by a GUICtrlCreate... function. Defines the style of the control. See GUI Control Styles Appendix. [optional] Defines the extended Style of the control. See Extended Style Table.

#include <GUIConstantsEx.au3> #include <StaticConstants.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $msg GUICreate("My GUI style") ; will create a dialog box that when displayed is centered GUICtrlCreateLabel("my label which will split on several lines", 10, 20, 100, 100) GUICtrlSetStyle(-1, $SS_RIGHT) GUISetState()

; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUICtrlSetTip
Sets the tip text associated with a control. GUICtrlSetTip ( controlID, tiptext [, "title" [, icon [, options]]]]] ) Parameters controlID tiptext title icon The control identifier (controlID) as returned by a GUICtrlCreate... function. Tip text that will be displayed when the mouse is hovered over the control. [optional] The title for the tooltip Requires IE5+ [optional] Pre-defined icon to show next to the title: Requires IE5+. Requires a title. 0 = No icon, 1 = Info icon, 2 = Warning icon, 3 = Error Icon [optional] Sets different options for how the tooltip will be displayed (Can be added together): 1 = Display as Balloon Tip Requires IE5+ 2 = Center the tip horizontally along the control.

options

Return Value Success: Failure: Remarks This tip text is displayed in a tooltip rectangular area. To skip an optional parameter, leaving it's default value intact, use the Default keyword.. You may use @CR or @LF to create multi-line tooltips. The title, icon and Balloon Tip option all require Internet Explorer 5.0 or later in order to function. To display an icon, you must specify a non-empty title. The icon appears on the same row as the title and thus requires a title to be present. Related GUICtrlUpdate... Example Returns 1. Returns 0.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $msg GUICreate("My GUI control tip") ; will create a dialog box that when displayed is centered GUICtrlCreateLabel("my label", 10, 20) GUICtrlSetTip(-1, "tip of my label") GUISetState()

; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

GUI set parameters functions Reference


Below is a complete list of the functions available in AutoIt. Click on a function name for a detailed description. See Gui Constants include files if you need to use the related controls Constants . Function GUISetAccelerators GUISetBkColor GUISetCoord GUISetCursor GUISetFont GUISetHelp GUISetIcon GUISetOnEvent GUISetState GUISetStyle Description Sets the accelerator table to be used in a GUI window. Sets the background color of the GUI window. Sets absolute coordinates for the next control. Sets the mouse cursor icon for a GUI window. Sets the default font for a GUI window. Sets an executable file that will be run when F1 is pressed. Sets the icon used in a GUI window. Defines a user function to be called when a system button is clicked. Changes the state of a GUI window. Changes the styles of a GUI window.

Function Reference

GUISetAccelerators
Sets the accelerator table to be used in a GUI window. GUISetAccelerators ( accelerators [, winhandle] ) Parameters accelerators winhandle Return Value Success: Failure: Remarks The array passed to this function contains the hotkey and the control ID of the accelerator. The array must be defined as Dim $array[n][2] - where n is the number of accelerator keys to set: $array[0][0] $array[0][1] $array[1][0] $array[1][1] ... $array[n][0] $array[n][1] = Hotkey (in HotKeySet() format) of 1st accelerator = Control ID of the 1st accelerator, as returned by GUICtrlCreate...() = Hotkey of 2nd accelerator = Control ID of the 2nd accelerator = Hotkey of nth accelerator = Control ID of the nth accelerator Returns 1. Returns 0. A 2 dimensional array holding the accelerator table (See remarks). [optional] Windows handle as returned by GUICreate (default is the previously used window).

Passing this function a non-array will unset all accelerators for the given winhandle. Related GUICreate, HotKeySet Example

; A simple custom messagebox that uses the MessageLoop mode #include <GUIConstantsEx.au3> GUICreate("Custom Msgbox", 210, 80) GUICtrlCreateLabel("Please click a button!", 10, 10) $YesID = GUICtrlCreateButton("Yes", 10, 50, 50, 20) $NoID = GUICtrlCreateButton("No", 80, 50, 50, 20) $ExitID = GUICtrlCreateButton("Exit", 150, 50, 50, 20) ; Set accelerators for Ctrl+y and Ctrl+n Dim $AccelKeys[2][2]=[["^y", $YesID], ["^n", $NoID]] GUISetAccelerators($AccelKeys) GUISetState() ; display the GUI Do $msg = GUIGetMsg()

Select Case $msg = $YesID MsgBox(0, "You clicked on", Case $msg = $NoID MsgBox(0, "You clicked on", Case $msg = $ExitID MsgBox(0, "You clicked on", Case $msg = $GUI_EVENT_CLOSE MsgBox(0, "You clicked on", EndSelect Until $msg = $GUI_EVENT_CLOSE Or $msg =

"Yes") "No") "Exit") "Close") $ExitID

Function Reference

GUISetBkColor
Sets the background color of the GUI window. GUISetBkColor ( background [, winhandle] ) Parameters background winhandle Return Value Success: Failure: Remarks None Related GUICreate Example Returns 1. Returns 0. Background color of the dialog box. [optional] Windows handle as returned by GUICreate (default is the previously used window).

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $msg GUICreate("My GUI") ; will create a dialog box that when displayed is centered GUISetBkColor(0xE0FFFF) ; will change background color GUISetState() ; will display an empty dialog box ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUISetCoord
Sets absolute coordinates for the next control. GUISetCoord ( left, top [, width [, height [, winhandle]]] ) Parameters left top width height winhandle Return Value Success: Failure: Remarks To be used specifically in Opt ("GUICoordMode", 2). It allows you to set the current position to a precise point and from that position to create controls by row (x_offset,-1) or by columns (-1, y_offset). Related GUICtrlCreate... Example Returns 1. Returns 0. The left side of the control. The top of the control. [optional] The width of the control (default is the previously used width). [optional] The height of the control (default is the previously used height). [optional] Windows handle as returned by GUICreate (default is the previously used).

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $msg Opt("GUICoordMode", 2) ; relative to cell mode GUICreate("My GUI Set Coord", 200, 100) GUICtrlCreateCheckbox("Check #1", 20, 10, 75) GUICtrlCreateCheckbox("Notify #2", 10, -1) ; next cell in the line GUISetCoord(20, 60) GUICtrlCreateButton("OK #3", -1, -1) GUICtrlCreateButton("Cancel #4", 10, -1) GUICtrlSetState(-1, $GUI_FOCUS) GUISetState() ; will display an empty dialog box ; Run the GUI until the dialog is closed While 1

$msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUISetCursor
Sets the mouse cursor icon for a GUI window. GUISetCursor ( [cursorID [, override [, winhandle]]] ) Parameters c ursorID override winhandle Return Value None. Remarks If the cursorID is invalid the standard arrow will be displayed. Usually when you move the mouse cursor over an edit control or other control the mouse cursor changes shape. The "override" option allows you to force the requested mouse cursor to be shown at all times. Note: If you have changed a controls mouse cursor with GUICtrlSetCursor then this control mouse cursor will always be shown. For a list of valid cursor IDs see MouseGetCursor. CursorId = 16 will hide the mouse c ursor. Related GUICtrlSetCursor Example [optional] Cursor Id (See Remarks). [optional] Force the requested mouse cursor even when over controls (see below). 0 = (default) Don't override a control's default mouse cursor. 1= override control's default mouse cursor. [optional] Windows handle as returned by GUICreate (default is the previously used Window).

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Global $IDC = -1, $newIDC = 0 Example() Func Example() HotKeySet("{Esc}", "Increment") GUICreate("Press Esc to Increment", 400, 400, 0, 0, 0x04CF0000, 0x00000110) GUISetState() While GUIGetMsg() <> $GUI_EVENT_CLOSE If $newIDC <> $IDC Then $IDC = $newIDC GUISetCursor($IDC) EndIf

ToolTip("GUI Cursor #" & $IDC) WEnd EndFunc ;==>Example Func Increment() $newIDC = $IDC + 1 If $newIDC > 15 Then $newIDC = 0 EndFunc ;==>Increment

Function Reference

GUISetFont
Sets the default font for a GUI window. GUISetFont (size [, weight [, attribute [, fontname [, winhandle[, quality]]]]] ) Parameters size weight attribute fontname winhandle quality Return Value Success: Failure: Remarks See the Appendix for a complete list of Windows fonts and Windows versions under which they are supported. Size can contain a decimal as in 8.5. For some control as label ones the default can be 8.5 instead of 9 according to Windows Theme Values. For Quality parameter check MSDN, some windows XP installation need CLEARTYPE_QUALITY=5 Related GUICtrlSetFont Example Returns 1. Returns 0. Fontsize (default is 8.5). [optional] Font weight (default 400 = normal). [optional] To define italic:2 underlined:4 strike:8 char format (add together the values of all the styles required, 2+4 = italic and underlined). [optional] Font to use. (OS default GUI font is used if the font is "" or is not found). [optional] Windows handle as returned by GUICreate (default is the previously used window). [optional] Font quality to select (default is PROOF_QUALITY=2).

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $font, $msg GUICreate("My GUI default font") ; will create a dialog box that when displayed is centered $font = "Comic Sans MS" GUISetFont(9, 400, 4, $font) ; will display underlined characters GUICtrlCreateLabel("underlined label", 10, 20) GUISetFont(9, 400, 2, $font) ; will display underlined characters GUICtrlCreateLabel("italic label", 10, 40)

GUISetFont(9, 400, 8, $font) ; will display underlined characters GUICtrlCreateLabel("strike label", 10, 60) GUISetState() ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUISetHelp
Sets an executable file that will be run when F1 is pressed. GUISetHelp ( helpfile [, winhandle] ) Parameters helpfile winhandle Return Value Success: Failure: Remarks None. Related GUICreate Example Returns 1. Returns 0. file that will be run if F1 is pressed when the GUI is active. [optional] Windows handle as returned by GUICreate (default is the previously used window).

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $msg GUICreate("My GUI") ; will create a dialog box that when displayed is centered GUISetHelp("notepad") ; will run notepad if F1 is typed

GUISetState() ; will display an empty dialog box ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUISetIcon
Sets the icon used in a GUI window. GUISetIcon ( iconfile [, iconID [, winhandle]] ) Parameters iconfile ic onID winhandle Return Value Success: Failure: Remarks Passing a positive number will reference the string equivalent icon name. Passing a negative number causes 1-based "index" behaviour. Some Dll can have icon extracted just with negative numbers. Related GUICreate Example Returns 1. Returns 0. used to display the icon in the title area. [optional] The ID of the icon in the iconfile. (Default is -1). [optional] Windows handle as returned by GUICreate (default is the previously used window).

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $sFile = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\AutoIt v3\AutoIt", "InstallDir") & "\icons\filetype1.ico" Local $msg GUICreate("My GUI new icon") ; will create a dialog box that when displayed is centered GUISetIcon($sFile) ; will change icon GUISetState(); will display an empty dialog box ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd EndFunc ;==>Example

Function Reference

GUISetOnEvent
Defines a user function to be called when a system button is clicked. GUISetOnEvent ( specialID, "function" [, winhandle] ) Parameters spec ialID function winhandle Return Value Success: Failure: Remarks OnEvent functions are only called when the option GUIOnEventMode is set to 1 - when in this mode GUIGetMsg is NOT used at all. If the option GUIEventOptions is set to 1 the minimize, restore and maximize button will not do any action on the window just a simple notification. If the function is an empty string "" the previous user-defined is disabled. Special ID table Special Id $GUI_EVENT_CLOSE $GUI_EVENT_MINIMIZE $GUI_EVENT_RESTORE $GUI_EVENT_MAXIMIZE $GUI_EVENT_MOUSEMOVE $GUI_EVENT_PRIMARYDOWN $GUI_EVENT_PRIMARYUP $GUI_EVENT_SECONDARYUP $GUI_EVENT _RESIZED $GUI_EVENT _DROPPED Related GUIOnEventMode (Option), GUIEventOptions (Option), GUICtrlSetOnEvent Example Comments dialog box being closed (either by defined button or system menu). dialog box minimized with Windows title bar button. dialog box restored by click on task bar icon. dialog box maximized with Windows title bar button. the mouse cursor has moved. the primary mouse button was pressed. the primary mouse button was released. the secondary mouse button was released. dialog box has been resized. End of a Drag&Drop ac tion @GUI_DRAGID, @GUI_DRAGFILE and @GUI_DROPID will be used to retrieve the ID's/file corresponding to the involve control. Returns 1. Returns 0. See the Special ID table below. The name of the user function to call. [optional] Windows handle as returned by GUICreate (default is the previously used window).

$GUI_EVENT_SECONDARYDOWN the secondary mouse button was pressed.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1)

Example() Func Example() Local $parent1, $ok1, $cancel1 Opt("GUICoordMode", 2) Opt("GUIResizeMode", 1) Opt("GUIOnEventMode", 1) $parent1 = GUICreate("Parent1") GUISetOnEvent($GUI_EVENT_CLOSE, "SpecialEvents") GUISetOnEvent($GUI_EVENT_MINIMIZE, "SpecialEvents") GUISetOnEvent($GUI_EVENT_RESTORE, "SpecialEvents")

$ok1 = GUICtrlCreateButton("OK", 10, 30, 50) GUICtrlSetOnEvent(-1, "OKPressed") $cancel1 = GUICtrlCreateButton("Cancel", 0, -1) GUICtrlSetOnEvent(-1, "CancelPressed") GUISetState(@SW_SHOW)

; Just idle around While 1 Sleep(10) WEnd EndFunc ;==>Example Func OKPressed() MsgBox(0, "OK Pressed", "ID=" & @GUI_CtrlId & " WinHandle=" & @GUI_WinHandle & " CtrlHandle=" & @GUI_CtrlHandle) EndFunc ;==>OKPressed Func CancelPressed() MsgBox(0, "Cancel Pressed", "ID=" & @GUI_CtrlId & " WinHandle=" & @GUI_WinHandle & " CtrlHandle=" & @GUI_CtrlHandle) EndFunc ;==>CancelPressed Func SpecialEvents()

Select Case @GUI_CtrlId = $GUI_EVENT_CLOSE MsgBox(0, "Close Pressed", "ID=" & @GUI_CtrlId & " WinHandle=" & @GUI_WinHandle) Exit Case @GUI_CtrlId = $GUI_EVENT_MINIMIZE MsgBox(0, "Window Minimized", "ID=" & @GUI_CtrlId & " WinHandle=" & @GUI_WinHandle) Case @GUI_CtrlId = $GUI_EVENT_RESTORE MsgBox(0, "Window Restored", "ID=" & @GUI_CtrlId & " WinHandle=" & @GUI_WinHandle) EndSelect EndFunc ;==>SpecialEvents

Function Reference

GUISetState
Changes the state of a GUI window. GUISetState ( [flag [, winhandle]] ) Parameters [optional] @SW_SHOW = Shows a previously hidden window (default) @SW_HIDE = Hide window @SW_MINIMIZE = Minimize window @SW_MAXIMIZE = Maximize window @SW_RESTORE = Undoes a window minimization @SW_DISABLE = Disables the window @SW_ENABLE = Enables the window @SW_LOCK = Lock the window to avoid repainting. @SW_UNLOCK = Unlock windows to allow painting. [optional] Windows handle as returned by GUICreate (default is the previously used window).

flag

winhandle Return Value Success: Failure: Remarks

Returns 1. Returns 0.

When windows are created they are initially hidden so you must use this function to display them (@SW_SHOW). Only one window can be locked with @SW_LOCK. Any other @SW_LOCK will lock the requested window. @SW_UNLOCK just ignored the "winhandle" to unlock any locked window. Related GUICreate Example

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $msg GUICreate("My GUI") ; start the definition GUISetState() ; will display an empty dialog box ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd

EndFunc ;==>Example

Function Reference

GUISetStyle
Changes the styles of a GUI window. GUISetStyle ( Style [,ExStyle [, winhandle]] ) Parameters defines the style of the window. See GUI Control Styles Appendix. style Use -1 to leave it unchanged. exStyle winhandle Return Value Success: Failure: Remarks No checking is done on style value, neither non interaction with already defined control. It is the designer responsability to take care of this compatibility. Related GUIGetStyle Example Returns 1. Returns 0. [optional] defines the extended style of the window. See the Extended Style Table below. -1 is the default. Use -1 to leave it unchanged. [optional] Windows handle as returned by GUICreate (default is the previously used window).

#include <GUIConstantsEx.au3> #include <WindowsConstants.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $NewStyle = False, $hWnd, $Style, $Msg $hWnd = GUICreate("Gui Style", 260, 100) $Style = GUICtrlCreateButton("Set Style", 45, 50, 150, 20) GUISetState() While 1 $Msg = GUIGetMsg() Switch $Msg Case $GUI_EVENT_CLOSE Exit Case $Style If Not $NewStyle Then GUISetStyle(BitOR($WS_POPUPWINDOW, $WS_THICKFRAME), BitOR ($WS_EX_CLIENTEDGE, $WS_EX_TOOLWINDOW)) GUICtrlSetData($Style, 'Undo Style')

$NewStyle = True Else GUISetStyle(BitOR($WS_MINIMIZEBOX, $WS_CAPTION, $WS_POPUP, $WS_SYSMENU), 0) GUICtrlSetData($Style, 'Set Style') $NewStyle = False EndIf Case Else EndSwitch WEnd EndFunc ;==>Example

Function Reference

GUIDelete
Deletes a GUI window and all controls that it contains. GUIDelete ( [winhandle] ) Parameters winhandle Return Value Success: Failure: Remarks None. Related GUICreate, GUISwitch Example Returns 1. Returns 0. [optional] Windows handle as returned by GUICreate (default is the previous used).

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $msg GUICreate("My GUI") ; will create a dialog box that when displayed is centered GUISetState() ; will display an empty dialog box ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd

GUIDelete(); ; will return 1 EndFunc ;==>Example

Function Reference

GUICtrlGetHandle
Returns the handle for a control and some special (item) handles (Menu, ContextMenu, TreeViewItem). GUICtrlGetHandle ( controlID ) Parameters controlID Return Value Success: Failure: Remarks ! These controls are not supported: Dummy, Graphic, Object, ListViewItem and TabItem ! ListViewItems and TabItems are managed through indexes. To get the index of these items use DllCall() and DllStructCreate(). Related IsHWnd Example Returns the handle of the given control ID. Returns 0. Control identifier as returned by GUICtrlCreate...

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $hGui, $FileMenu, $OpenItem, $SaveItem, $OptionsMenu Local $ViewItem, $ToolsItem, $ExitItem, $HelpMenu, $AboutItem Local $EndBtn, $Msg

$hGui = GUICreate("My GUI", 300, 200) $FileMenu = GUICtrlCreateMenu("&File") $OpenItem = GUICtrlCreateMenuItem("&Open", $FileMenu) $SaveItem = GUICtrlCreateMenuItem("&Save", $FileMenu) GUICtrlCreateMenuItem("", $FileMenu) $OptionsMenu = GUICtrlCreateMenu("O&ptions", $FileMenu) $ViewItem = GUICtrlCreateMenuItem("View", $OptionsMenu) GUICtrlCreateMenuItem("", $OptionsMenu) $ToolsItem = GUICtrlCreateMenuItem("Tools", $OptionsMenu)

GUICtrlCreateMenuItem("", $FileMenu) $ExitItem = GUICtrlCreateMenuItem("&Exit", $FileMenu) $HelpMenu = GUICtrlCreateMenu("&?") $AboutItem = GUICtrlCreateMenuItem("&About", $HelpMenu)

$EndBtn = GUICtrlCreateButton("End", 110, 140, 70, 20) SetMenuColor($FileMenu, 0xEEBB99) ; BGR color value SetMenuColor($OptionsMenu, 0x66BB99); BGR color value SetMenuColor($HelpMenu, 0x99BBEE) ; BGR color value GUISetState() While 1 $Msg = GUIGetMsg() Switch $Msg Case $ExitItem, $EndBtn, $GUI_EVENT_CLOSE ExitLoop Case $AboutItem MsgBox(64, "About...", "Colored menu sample") EndSwitch WEnd EndFunc ;==>Example

; Apply the color to the menu Func SetMenuColor($nMenuID, $nColor) Local $hMenu, $hBrush, $stMenuInfo Local Const $MIM_APPLYTOSUBMENUS = 0x80000000 Local Const $MIM_BACKGROUND = 0x00000002 $hMenu = GUICtrlGetHandle($nMenuID) $hBrush = DllCall("gdi32.dll", "hwnd", "CreateSolidBrush", "int", $nColor) $hBrush = $hBrush[0] $stMenuInfo = DllStructCreate("dword;dword;dword;uint;dword;dword;ptr") DllStructSetData($stMenuInfo, 1, DllStructGetSize($stMenuInfo)) DllStructSetData($stMenuInfo, 2, BitOR($MIM_APPLYTOSUBMENUS, $MIM_BACKGROUND)) DllStructSetData($stMenuInfo, 5, $hBrush) DllCall("user32.dll", "int", "SetMenuInfo", "hwnd", $hMenu, "ptr", DllStructGetPtr ($stMenuInfo)) ; release Struct not really needed as it is a local $stMenuInfo = 0 EndFunc ;==>SetMenuColor

Function Reference

GUICtrlGetState
Gets the current state of a control GUICtrlGetState ( [controlID] ) Parameters controlID Return Value Success: Failure: Remarks As opposed to GUICtrlRead this function returns ONLY the state of a control enabled/disabled/hidden/show/dropaccepted Exceptions: For ListView controls it returns the number of the clicked column. Related GUICtrlRead, GUICtrlSetState Example Returns the state. See GUICtrlSetState for values. Returns -1 if control is not defined. [optional] The control identifier (controlID) as returned by a GUICtrlCreate... function.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $n, $msg GUICreate("My GUI (GetControlState)") $n = GUICtrlCreateCheckbox("checkbox", 10, 10) GUICtrlSetState(-1, 1) ; checked GUISetState() ; will display an empty dialog box ; Run the GUI until the dialog is closed While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd

MsgBox(0, "state", StringFormat("GUICtrlRead=%d\nGUICtrlGetState=%d", GUICtrlRead($n), GUICtrlGetState($n))) EndFunc ;==>Example

Function Reference

GUICtrlRead
Read state or data of a control. GUICtrlRead ( controlID [, advanced] ) Parameters controlID advanced Return Value Success: Failure: Type Combo, List Input, Edit Button Date Progress Slider Tab Menu, MenuItem TreeView TreeViewItem ListView Dummy Remarks In 'advanced' mode the return value contains additional data of the control (see below). Note: not for all known controls there is additional data available! Returns depending the control (see below). Returns 0. Value The value selected The text entered The display text The selected date Current percentage Current value The number or the controlID of the tabitem selected depending of the advanced parameter value. State of the menu/item. See State table Control identifier (controlID) of the selected TreeViewItem State of the TreeViewItem Control identifier (controlID) of the selected ListViewItem. 0 means no item is selected The value set by GUICtrlSendT oDummy or GUICtrlSetData The control identifier (controlID) as returned by a GUICtrlCreate... function. [optional] returns extended information of a control. 0 = (Default) Returns a value with state or data of a control. 1 = Returns extended information of a control (see Remarks).

Checkbox, Radio state of the button. See State table

Type Checkbox, Radio Menu, MenuItem TreeView TreeViewItem ListViewItem

Additional Value The text of the control. The text of the control. The text of the current selected TreeViewItem. The text of the TreeViewItem. The state of the ListViewItem if $LVS_EX_CHECKBOXES exStyle used in advanced mode. See State table

Tab

The controlID of the tabitem selected

For Checkbox, Radio control several states can be returned as $GUI_FOCUS and $GUI_CHECKED,. So use i.e. BitAnd(GUICtrlRead($Item),$GUI_CHECKED) to test if the control is checked. For Listview items several states can be returned as $GUI_CHECKED and $GUI_UNCHECKED (only for listview controls with LVS_EX_CHECKBOXES-exstyle and on 'advanced' return) . So use i.e. BitAnd(GUICtrlRead ($Item),$GUI_CHECKED) to test if the item is checked. For Treeview items several states can be returned as $GUI_FOCUS, $GUI_EXPAND and $GUI_CHECKED, $GUI_UNCHECKED (only for treeview c ontrols with TVS_CHECKBOXES-style . So use i.e. BitAnd(GUICtrlRead ($Item),$GUI_CHECKED) to test if the item is checked. Related GUICtrlUpdate..., GUIGetMsg, GUICtrlSetData, GUIEventOptions (Option), GUICtrlCreate..., GUICtrlGetState, GUICtrlSendT oDummy, GUICtrlSendMsg Example

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $menu1, $n1, $n2, $msg, $menustate, $menutext GUICreate("My GUICtrlRead") ; will create a dialog box that when displayed is centered $menu1 = GUICtrlCreateMenu("File") $n1 = GUICtrlCreateList("", 10, 10, -1, 100) GUICtrlSetData(-1, "item1|item2|item3", "item2") $n2 = GUICtrlCreateButton("Read", 10, 110, 50) GUICtrlSetState(-1, $GUI_FOCUS) ; the focus is on this button GUISetState() ; will display an empty dialog box ; Run the GUI until the dialog is closed Do $msg = GUIGetMsg() If $msg = $n2 Then MsgBox(0, "Selected listbox entry", GUICtrlRead($n1)) ; display the selected listbox entry $menustate = GUICtrlRead($menu1) ; return the state of the menu item $menutext = GUICtrlRead($menu1, 1) ; return the text of the menu item MsgBox(0, "State and text of the menuitem", "state:" & $menustate & @LF & "text:" & $menutext) EndIf Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example

Function Reference

GUICtrlRecvMsg
Send a message to a control and retrieve information in lParam. GUICtrlRecvMsg ( controlID , msg [, wParam [, lParamType]] ) Parameters controlID msg wParam lParamType Return Value Success: Failure: Remarks This function allows the sending of special Windows messages directly to the control using the SendMessage API. It is used to enable special control features not available with the simple GUICtrlRead() and GUICtrlUpdate... () range of functions. If the wParam and lParamType parameters are not specified then an array of two elements is returned (LPwParam, LPlParam). The RECT is returned in an array of 4 elements (Left, Top, Right, Bottom). Related GUICtrlSendMsg, GUICtrlUpdate... Example Returns the value returned by the SendMessage Windows API. Returns 0. The control identifier (controlID) as returned by a GUICtrlCreate... function. type of message to be send to the control as defined in the Windows controls documentation. [optional] An integer first param to be send to the control. [optional] Define the type of lParam that will be returned: 0 (default) for wParam and lParam, 1 for lParam String, 2 for lParam RECT struct.

#include <GUIConstantsEx.au3> #include <EditConstants.au3> GUICreate("My GUI") ; will create a dialog box that when displayed is centered $nEdit = GUICtrlCreateEdit ("line 0", 10,10) GUICtrlCreateButton ("Ok", 20,200,50) GUISetState () For $n=1 To 5 GUICtrlSetData ($nEdit, @CRLF & "line "& $n) Next

; Run the GUI until the dialog is closed Do $msg = GUIGetMsg() If $msg >0 Then $a=GUICtrlRecvMsg($nEdit, $EM_GETSEL)

GUICtrlSetState($nEdit,$GUI_FOCUS) ; set focus back on edit control ; will display the wParam and lParam values return by the control MsgBox(0,"Current selection",StringFormat("start=%d end=%d", $a[0], $a[1])) EndIf Until $msg = $GUI_EVENT_CLOSE

Function Reference

GUICtrlSendMsg
Send a message to a control. GUICtrlSendMsg ( controlID, msg , wParam, lParam ) Parameters controlID msg wParam lParam Return Value Success: Failure: Remarks This function allows the sending of special Windows messages directly to the control using the SendMessage API. It is used to enable special control features not available with the simple GUICtrlRead() and GUICtrlUpdate... () range of functions. The parameters (wParam and lParam) can be an integer or a string. GUICtrlSendMsg should be used for messages that have no special return types. For more advanced messages where you must be able to receive extra data you must use GUICtrlRec vMsg(). Related GUICtrlRec vMsg, GUICtrlCreate..., GUICtrlUpdate..., GUIGetMsg, GUICtrlRead Example Returns the value returned by the SendMessage Windows API. Returns 0. The control identifier (controlID) as returned by a GUICtrlCreate... function. type of message to be send to the control as defined in the Windows control documentation. The first param to send to the control. The second param to send to the control.

#include <GUIConstantsEx.au3> #include <EditConstants.au3> GUICreate("My GUI") ; will create a dialog box that when displayed is centered $nEdit = GUICtrlCreateEdit ("line 0", 10,10) GUICtrlCreateButton ("Ok", 20,200,50) GUISetState () For $n=1 To 5 GUICtrlSetData ($nEdit,@CRLF & "line "& $n) Next

; Run the GUI until the dialog is closed Do $msg = GUIGetMsg() If $msg >0 Then $n=GUICtrlSendMsg ($nEdit, $EM_LINEINDEX,-1,0) $nline=GUICtrlSendMsg( $nEdit, $EM_LINEFROMCHAR,$n,0) GUICtrlSetState ($nEdit,$GUI_FOCUS); set focus

MsgBox (0,"Currentline",$nLine) EndIf Until $msg = $GUI_EVENT_CLOSE

Function Reference

GUICtrlSendToDummy
Sends a message to a Dummy control. GUICtrlSendToDummy ( controlID [, state] ) Parameters controlID state Return Value Success: Failure: Remarks When this function is called a notification that can be handled through the message loop or with a OnEvent function is generated (as if the control had been "clicked" on). Related GUICtrlCreateDummy, GUICtrlSetOnEvent, GUICtrlRead Example Returns 1. Returns 0. The control identifier (controlID) as returned by GUICtrlCreateDummy [optional] value that can be retrieved later on by GUICtrlRead

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Global $user Example() Func Example() Local $iOldOpt, $button $iOldOpt = Opt("GUIOnEventMode", 1) GUICreate("GUISendToDummy", 220, 200, 100, 200) GUISetBkColor(0x00E0FFFF) ; will change background color GUICtrlSetOnEvent($GUI_EVENT_CLOSE, "OnClick") ; to handle click on button $user = GUICtrlCreateDummy() GUICtrlSetOnEvent(-1, "Onexit") ; to handle click on button $button = GUICtrlCreateButton("event", 75, 170, 70, 20) GUICtrlSetOnEvent(-1, "OnClick") ; to handle click on button GUISetState()

While 1 Sleep(100) WEnd Opt("GUIOnEventMode", $iOldOpt) EndFunc ;==>Example

Func OnClick() GUICtrlSendToDummy($user) ; fired dummy control EndFunc ;==>OnClick Func OnExit() ; special action before exiting Exit EndFunc ;==>OnExit

Function Reference

GUIGetCursorInfo
Gets the mouse cursor position relative to GUI window. GUIGetCursorInfo ( [winhandle] ) Parameters winhandle Return Value Success: returns a five-element array that containing the mouse cursor information: $array[0] = X coord (horizontal) $array[1] = Y coord (vertical) $array[2] = Primary down (1 if pressed, 0 if not pressed) $array[3] = Secondary down (1 if pressed, 0 if not pressed) $array[4] = ID of the control that the mouse cursor is hovering over (or 0 if none) Failure: Remarks The coordinates given are relative to the GUI window (known as client coords). If the "winhandle" parameter is used then the specified window becomes the new "current" window. The mouse cursor position is successful only on an window created by a GUICreate. When no winhandle it will be successful if the GUI Windows is active. ListViewItem or TreeViewItem controlID will never be returned, only the parent Listview or TreeView control ID is. Related GUICreate, GUIGetMsg Example 0 and set @error to 1 [optional] The handle of the window to use. If omitted the "current" window will be used.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Global $x, $y Example() Func Example() Local $msg HotKeySet("{Esc}", "GetPos") GUICreate("Press Esc to Get Pos", 400, 400) $x = GUICtrlCreateLabel("0", 10, 10, 50) $y = GUICtrlCreateLabel("0", 10, 30, 50) GUISetState()

; Run the GUI until the dialog is closed Do $msg = GUIGetMsg() Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example Func GetPos() Local $a $a = GUIGetCursorInfo() GUICtrlSetData($x, $a[0]) GUICtrlSetData($y, $a[1]) EndFunc ;==>GetPos

Function Reference

GUIGetMsg
Polls the GUI to see if any events have occurred. GUIGetMsg ( [advanced] ) Parameters advanced Return Value Returns an event, or an array depending on the "advanced" parameter. The "event" returned is the control ID of the control sending the message, or it is a special event (like the window is closing, minimizing). Or if there is no message, the event is 0. [optional] return extended information in an array. 0 = (default) Returns a single event. 1 = returns an array containing the event and extended information.

Event ID 0 $GUI_EVENT_CLOSE $GUI_EVENT_MINIMIZE $GUI_EVENT_RESTORE $GUI_EVENT_MAXIMIZE $GUI_EVENT_MOUSEMOVE $GUI_EVENT_PRIMARYDOWN $GUI_EVENT_PRIMARYUP $GUI_EVENT_SECONDARYUP $GUI_EVENT _RESIZED $GUI_EVENT _DROPPED

the ID of the control sending the message No event dialog box being closed (either by defined button or system menu). dialog box minimized with Windows title bar button. dialog box restored by click on task bar icon. dialog box maximized with Windows title bar button. the mouse cursor has moved. the primary mouse button was pressed. the primary mouse button was released. the secondary mouse button was released. dialog box has been resized. End of a Drag&Drop ac tion @GUI_DRAGID, @GUI_DRAGFILE and @GUI_DROPID will be used to retrieve the ID's/file corresponding to the involve control.

$GUI_EVENT_SECONDARYDOWN the secondary mouse button was pressed.

When using the "advanced" parameter the information is returned in an array with extended information: $array[0] = 0 or Event ID or Control ID $array[1] = The window handle the event is from $array[2] = The control handle the event is from (if applicable) $array[3] = The current X position of the mouse cursor (relative to the GUI window) $array[4] = The current Y position of the mouse cursor (relative to the GUI window) If the GUIOnEventMode option is set to 1 then the return from GUIGetMsg is always 0 and the @error is set to 1. If the option GUIEventOptions is set to 1 the minimize, restore and maximize button will not do any action on the window just a simple notification. Remarks This function automatically idles the CPU when required so that it can be safely used in tight loops without hogging all the CPU. Information about the mouse position and the hovering control can be retrieved with GUIGetCursorInfo. No event is fired when the mouse is over a control so GUIGetCursorInfo must be called to retrieve the ControlID.

Related GUICreate, GUICtrlCreate..., GUICtrlRead, GUIOnEventMode (Option), GUIEventOptions (Option), GUIGetCursorInfo, GUICtrlSendMsg, GUICtrlSetOnEvent Example

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() ;------------------------------------------------------------------------------------; Example - Press the button to see the value of the radio boxes ; The script also detects state changes (closed/minimized/timeouts, etc). Func Example() Local $button_1, $group_1, $radio_1, $radio_2, $radio_3 Local $radioval1, $radioval2, $msg Opt("GUICoordMode", 1) GUICreate("Radio Box Demo", 400, 280) ; Create the controls $button_1 = GUICtrlCreateButton("B&utton 1", 30, 20, 120, 40) $group_1 = GUICtrlCreateGroup("Group 1", 30, 90, 165, 160) GUIStartGroup() $radio_1 = GUICtrlCreateRadio("Radio &0", 50, 120, 70, 20) $radio_2 = GUICtrlCreateRadio("Radio &1", 50, 150, 60, 20) $radio_3 = GUICtrlCreateRadio("Radio &2", 50, 180, 60, 20)

; Init our vars that we will use to keep track of GUI events $radioval1 = 0 ; We will assume 0 = first radio button selected, 2 = last button $radioval2 = 2 ; Show the GUI GUISetState() ; In this message loop we use variables to keep track of changes to the radios, another ; way would be to use GUICtrlRead() at the end to read in the state of each control While 1 $msg = GUIGetMsg() Select Case $msg = $GUI_EVENT_CLOSE MsgBox(0, "", "Dialog was closed") Exit Case $msg = $GUI_EVENT_MINIMIZE MsgBox(0, "", "Dialog minimized", 2) Case $msg = $GUI_EVENT_MAXIMIZE MsgBox(0, "", "Dialog restored", 2)

Case $msg = $button_1 MsgBox(0, "Default button clicked", "Radio " & $radioval1) Case $msg >= $radio_1 And $msg <= $radio_3 $radioval1 = $msg - $radio_1 EndSelect WEnd EndFunc ;==>Example

Function Reference

GUIGetStyle
Retrieves the styles of a GUI window. GUIGetStyle ( [ winhandle] ) Parameters winhandle Return Value Success: returns a two-element array that containing the styles information: $array[0] = Style $array[1] = ExStyle Failure: Remarks Be carefull Style changes after GUISetState(). Related GUICreate, GUISetStyle Example Returns 0. [optional] Windows handle as returned by GUICreate (default is the previously used window).

#include <GUIConstantsEx.au3> #include <WindowsConstants.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $NewStyle = False, $hWnd, $Style, $GuiStyles, $Msg $hWnd = GUICreate("Gui Style", 260, 100) $Style = GUICtrlCreateButton("Set Style", 45, 50, 150, 20) $GuiStyles = GUIGetStyle($hWnd) ; be careful the style change after opening GUISetState() While 1 $Msg = GUIGetMsg() Switch $Msg Case $GUI_EVENT_CLOSE Exit Case $Style If Not $NewStyle Then GUISetStyle(BitOR($WS_POPUPWINDOW, $WS_THICKFRAME), BitOR ($WS_EX_CLIENTEDGE, $WS_EX_TOOLWINDOW)) GUICtrlSetData($Style, 'Undo Style') $NewStyle = True Else

GUISetStyle($GuiStyles[0], $GuiStyles[1]) GUICtrlSetData($Style, 'Set Style') $NewStyle = False EndIf Case Else EndSwitch WEnd EndFunc ;==>Example

Function Reference

GUIRegisterMsg
Register a user defined function for a known Windows Message ID (WM_MSG). GUIRegisterMsg ( msgID, "function" ) Parameters msgID function Return Value Success: Failure: Remarks !!! To make the user function workable you have to define it with maximum 4 function parameters otherwise the function won't be called !!! i.e: Func MyUserFunction($hWndGUI, $MsgID, $WParam, $LParam) ... EndFunc Or Func MyUserFunction($hWndGUI, $MsgID) ... EndFunc When the user function is called then these 4 parameters have the following values: Position 1 2 3 4 Parameter hWnd Msg wParam lParam Meaning The Window handle of the GUI in which the message appears. The Windows message ID. The first message parameter as hex value. The second message parameter as hex value. 1 0 A Windows Message ID (see Appendix: Windows Message Codes). The name of the user function to call when the message appears or an empty string "" to unregister a message.

Up to 256 user functions can be registered for message ID's. By default after finishing the user function the AutoIt internal message handler will be proceed. That won't be if your Return a value (See WM_COMMAND in example) or if you use the keyword 'Return' without any value. By using 'Return' without any return value the AutoIt internal message handler (if there is one for this message) will NOT be proceed! !!! If you want AutoIt to run it's internal handler for a message, return the variable $GUI_RUNDEFMSG (in GUIConstantsEx.au3) from the function (see also examples) !!! I.e. if you want to return earlier than the user function ends and also proceed the AutoIt internal message handler. Warning: blocking of running user functions which executes window messages with commands such as "Msgbox ()" can lead to unexpected behavior, the return to the system should be as fast as possible !!! Some controls consume internally specific Windows Message ID, so registrating them will have no effect, e.g; WM_CHAR, WM_KEYDOWN, WM_KEYUP are consumed by an edit control.

Related GUICtrlGetHandle Example

; ******************************************************* ; Example - Create an ownerdrawn/colored button ; ******************************************************* #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <ButtonConstants.au3> Example() Func Example() Local Const $BS_OWNERDRAW = 0x0000000B Local $hGUI, $nButton, $nButton2, $GUIMsg $hGUI = GUICreate("My Ownerdrawn Created Button", 300, 200) $nButton = GUICtrlCreateButton("", 90, 50, 120, 30) GUICtrlSetStyle($nButton, BitOR($WS_TABSTOP, $BS_NOTIFY, $BS_OWNERDRAW)) ; Set the ownerdrawn flag $nButton2 = GUICtrlCreateButton("Normal Button", 90, 110, 120, 30) GUIRegisterMsg($WM_COMMAND, "MY_WM_COMMAND") ; WM_DRAWITEM has to registered before showing GUI otherwise the initial drawing isn't done GUIRegisterMsg($WM_DRAWITEM, "MY_WM_DRAWITEM") GUISetState() While 1 $GUIMsg = GUIGetMsg() Switch $GUIMsg Case $GUI_EVENT_CLOSE ExitLoop Case $nButton ; Normally should MsgBox(0, "Info", Case $nButton2 ; Normally should MsgBox(0, "Info", EndSwitch WEnd EndFunc ;==>Example

not run through cause of our MY_WM_COMMAND function "Button pressed")

not run through cause of our MY_WM_COMMAND function "Button2 pressed")

; React on a button click Func MY_WM_COMMAND($hWnd, $Msg, $wParam, $lParam) $nNotifyCode = BitShift($wParam, 16) $nID = BitAND($wParam, 0x0000FFFF) $hCtrl = $lParam If $nID <> 2 And $nNotifyCode = 0 Then ; Check for IDCANCEL - 2 ; Ownerdrawn buttons don't send something by pressing ENTER ; So IDOK - 1 comes up, now check for the control that has the current focus If $nID = 1 Then $hFocus = DllCall("user32.dll", "hwnd", "GetFocus")

$nCtrlID = DllCall("user32.dll", "int", "GetDlgCtrlID", "hwnd", $hFocus[0]) PostButtonClick($hWnd, $nCtrlID[0]) Else MsgBox(0, "MY_WM_COMMAND", "GUIHWnd" & @TAB & ":" & $hWnd & @LF & _ "MsgID" & @TAB & ":" & $Msg & @LF & _ "wParam" & @TAB & ":" & $wParam & @LF & _ "lParam" & @TAB & ":" & $lParam & @LF & @LF & _ "WM_COMMAND - Infos:" & @LF & _ "-----------------------------" & @LF & _ "Code" & @TAB & ":" & $nNotifyCode & @LF & _ "CtrlID" & @TAB & ":" & $nID & @LF & _ "CtrlHWnd" & @TAB & ":" & $hCtrl) EndIf Return 0 ; Only workout clicking on the button EndIf ; Proceed the default Autoit3 internal message commands. ; You also can complete let the line out. ; !!! But only 'Return' (without any value) will not proceed ; the default Autoit3-message in the future !!! Return $GUI_RUNDEFMSG EndFunc ;==>MY_WM_COMMAND

; RePost a WM_COMMAND message to a ctrl in a gui window Func PostButtonClick($hWnd, $nCtrlID) DllCall("user32.dll", "int", "PostMessage", _ "hwnd", $hWnd, _ "int", $WM_COMMAND, _ "int", BitAND($nCtrlID, 0x0000FFFF), _ "hwnd", GUICtrlGetHandle($nCtrlID)) EndFunc ;==>PostButtonClick

; Draw the button Func MY_WM_DRAWITEM($hWnd, $Msg, $wParam, $lParam) Local $stDrawItem = DllStructCreate("uint;uint;uint;uint;uint;uint;uint;int[4];dword", $lParam) Local Const $ODT_BUTTON = 4 $nCtlType = DllStructGetData($stDrawItem, 1) If $nCtlType = $ODT_BUTTON Then $nCtrlID = DllStructGetData($stDrawItem, 2) $nItemState = DllStructGetData($stDrawItem, 5) $hCtrl = DllStructGetData($stDrawItem, 6) $hDC = DllStructGetData($stDrawItem, 7) $nLeft = DllStructGetData($stDrawItem, 8, 1) $nTop = DllStructGetData($stDrawItem, 8, 2) $nRight = DllStructGetData($stDrawItem, 8, 3) $nBottom = DllStructGetData($stDrawItem, 8, 4) $sText = "Ownerdrawn Button" $nTextColor = 0x5555DD $nBackColor = 0xFFEEDD DrawButton($hWnd, $hCtrl, $hDC, $nLeft, $nTop, $nRight, $nBottom, $nItemState, $sText, $nTextColor, $nBackColor) $stDrawItem = 0 Return 1 EndIf $stDrawItem = 0 Return $GUI_RUNDEFMSG ; Proceed the default Autoit3 internal message commands EndFunc ;==>MY_WM_DRAWITEM

; The main drawing procedure Func DrawButton($hWnd, $hCtrl, $hDC, $nLeft, $nTop, $nRight, $nBottom, $nItemState, $sText, $nTextColor, $nBackColor) ;Local $bDefault = FALSE

Local Local Local Local Local Local Local Local Local Local Local Local Local Local Local Local

Const $GWL_STYLE = -16 Const $ODS_SELECTED = 0x0001 Const $ODS_GRAYED = 0x0002 Const $ODS_DISABLED = 0x0004 Const $ODS_CHECKED = 0x0008 Const $ODS_FOCUS = 0x0010 Const $ODS_HOTLIGHT = 0x0040 Const $ODS_INACTIVE = 0x0080 Const $ODS_NOACCEL = 0x0100 Const $ODS_NOFOCUSRECT = 0x0200 Const $DFC_BUTTON = 4 Const $DFCS_BUTTONPUSH = 0x0010 $bChecked = BitAND($nItemState, $ODS_CHECKED) $bFocused = BitAND($nItemState, $ODS_FOCUS) $bGrayed = BitAND($nItemState, BitOR($ODS_GRAYED, $ODS_DISABLED)) $bSelected = BitAND($nItemState, $ODS_SELECTED)

$stRect = DllStructCreate("int;int;int;int") DllStructSetData($stRect, 1, $nLeft) DllStructSetData($stRect, 2, $nTop) DllStructSetData($stRect, 3, $nRight) DllStructSetData($stRect, 4, $nBottom) If $bGrayed Then $nClrTxt = SetTextColor($hDC, GetSysColor($COLOR_HIGHLIGHTTEXT)) ElseIf $nTextColor = -1 Then $nClrTxt = SetTextColor($hDC, GetSysColor($COLOR_BTNTEXT)) Else $nClrTxt = SetTextColor($hDC, $nTextColor) EndIf If $nBackColor = -1 Then $hBrush = GetSysColorBrush($COLOR_BTNFACE) $nClrSel = GetSysColor($COLOR_BTNFACE) Else $hBrush = CreateSolidBrush($nBackColor) $nClrSel = $nBackColor; EndIf

$nClrBk = SetBkColor($hDC, $nClrSel) $hOldBrush = SelectObject($hDC, $hBrush) $nTmpLeft = $nLeft $nTmpTop = $nTop $nTmpRight = $nRight $nTmpBottom = $nBottom If $bSelected Then InflateRect($nTmpLeft, $nTmpTop, $nTmpRight, $nTmpBottom, -1, -1) $hBrushSel = CreateSolidBrush(GetSysColor($COLOR_BTNSHADOW)) FrameRect($hDC, $nTmpLeft, $nTmpTop, $nTmpRight, $nTmpBottom, $hBrushSel) DeleteObject($hBrushSel) Else If $bFocused And Not $bSelected Then InflateRect($nTmpLeft, $nTmpTop, $nTmpRight, $nTmpBottom, -1, -1) DrawFrameControl($hDC, $nTmpLeft, $nTmpTop, $nTmpRight, $nTmpBottom, $DFC_BUTTON, $DFCS_BUTTONPUSH) EndIf $nTmpLeft = $nLeft $nTmpTop = $nTop $nTmpRight = $nRight $nTmpBottom = $nBottom If $bSelected Then InflateRect($nTmpLeft, $nTmpTop, $nTmpRight, $nTmpBottom, -2, -2) Else If $bFocused And Not $bSelected Then

InflateRect($nTmpLeft, $nTmpTop, $nTmpRight, $nTmpBottom, -3, -3) $nTmpLeft -= 1 $nTmpTop -= 1 Else InflateRect($nTmpLeft, $nTmpTop, $nTmpRight, $nTmpBottom, -2, -2) $nTmpLeft -= 1 $nTmpTop -= 1 EndIf EndIf FillRect($hDC, $nTmpLeft, $nTmpTop, $nTmpRight, $nTmpBottom, $hBrush) If $bSelected Or $bGrayed Then $nTmpLeft = $nTmpLeft + 2 $nTmpTop = $nTmpTop + 2 EndIf $uFlags = BitOR($DT_NOCLIP, $DT_CENTER, $DT_VCENTER)

If Not BitAND(GetWindowLong($hCtrl, $GWL_STYLE), $BS_MULTILINE) Then $uFlags = BitOR ($uFlags, $DT_SINGLELINE) DrawText($hDC, $sText, $nTmpLeft, $nTmpTop, $nTmpRight, $nTmpBottom, $uFlags) If $bGrayed Then $nTmpLeft = $nLeft $nTmpTop = $nTop $nTmpRight = $nRight $nTmpBottom = $nBottom $nTmpLeft -= 1 $nClrTxt = SetTextColor($hDC, GetSysColor($COLOR_GRAYTEXT)) DrawText($hDC, $sText, $nTmpLeft, $nTmpTop, $nTmpRight, $nTmpBottom, BitOR ($DT_NOCLIP, $DT_CENTER, $DT_VCENTER, $DT_SINGLELINE)) EndIf $nTmpLeft = $nLeft $nTmpTop = $nTop $nTmpRight = $nRight $nTmpBottom = $nBottom If $bFocused Then $hBrush = CreateSolidBrush(0) FrameRect($hDC, $nTmpLeft, $nTmpTop, $nTmpRight, $nTmpBottom, $hBrush) $nTmpLeft = $nLeft $nTmpTop = $nTop $nTmpRight = $nRight $nTmpBottom = $nBottom InflateRect($nTmpLeft, $nTmpTop, $nTmpRight, $nTmpBottom, -4, -4) DrawFocusRect($hDC, $nTmpLeft, $nTmpTop, $nTmpRight, $nTmpBottom) EndIf

SelectObject($hDC, $hOldBrush) DeleteObject($hBrush) SetTextColor($hDC, $nClrTxt) SetBkColor($hDC, $nClrBk) Return 1 EndFunc ;==>DrawButton

; Some graphic / windows functions Func CreateSolidBrush($nColor) Local $hBrush = DllCall("gdi32.dll", "hwnd", "CreateSolidBrush", "int", $nColor) Return $hBrush[0]

EndFunc ;==>CreateSolidBrush Func GetSysColor($nIndex) Local $nColor = DllCall("user32.dll", "int", "GetSysColor", "int", $nIndex) Return $nColor[0] EndFunc ;==>GetSysColor Func GetSysColorBrush($nIndex) Local $hBrush = DllCall("user32.dll", "hwnd", "GetSysColorBrush", "int", $nIndex) Return $hBrush[0] EndFunc ;==>GetSysColorBrush Func DrawFrameControl($hDC, $nLeft, $nTop, $nRight, $nBottom, $nType, $nState) Local $stRect = DllStructCreate("int;int;int;int") DllStructSetData($stRect, 1, $nLeft) DllStructSetData($stRect, 2, $nTop) DllStructSetData($stRect, 3, $nRight) DllStructSetData($stRect, 4, $nBottom) DllCall("user32.dll", "int", "DrawFrameControl", "hwnd", $hDC, "ptr", DllStructGetPtr ($stRect), "int", $nType, "int", $nState) $stRect = 0 EndFunc ;==>DrawFrameControl Func DrawFocusRect($hDC, $nLeft, $nTop, $nRight, $nBottom) Local $stRect = DllStructCreate("int;int;int;int") DllStructSetData($stRect, 1, $nLeft) DllStructSetData($stRect, 2, $nTop) DllStructSetData($stRect, 3, $nRight) DllStructSetData($stRect, 4, $nBottom) DllCall("user32.dll", "int", "DrawFocusRect", "hwnd", $hDC, "ptr", DllStructGetPtr ($stRect)) $stRect = 0 EndFunc ;==>DrawFocusRect Func DrawText($hDC, $sText, $nLeft, $nTop, $nRight, $nBottom, $nFormat) Local $nLen = StringLen($sText) Local $stRect = DllStructCreate("int;int;int;int") DllStructSetData($stRect, 1, $nLeft) DllStructSetData($stRect, 2, $nTop) DllStructSetData($stRect, 3, $nRight) DllStructSetData($stRect, 4, $nBottom) Local $stText = DllStructCreate("char[260]") DllStructSetData($stText, 1, $sText) DllCall("user32.dll", "int", "DrawText", "hwnd", $hDC, "ptr", DllStructGetPtr($stText), "int", $nLen, "ptr", DllStructGetPtr($stRect), "int", $nFormat) $stRect = 0 $stText = 0 EndFunc ;==>DrawText Func FillRect($hDC, $nLeft, $nTop, $nRight, $nBottom, $hBrush)

Local $stRect = DllStructCreate("int;int;int;int") DllStructSetData($stRect, 1, $nLeft) DllStructSetData($stRect, 2, $nTop) DllStructSetData($stRect, 3, $nRight) DllStructSetData($stRect, 4, $nBottom) DllCall("user32.dll", "int", "FillRect", "hwnd", $hDC, "ptr", DllStructGetPtr($stRect), "hwnd", $hBrush) $stRect = 0 EndFunc ;==>FillRect Func FrameRect($hDC, $nLeft, $nTop, $nRight, $nBottom, $hBrush) Local $stRect = DllStructCreate("int;int;int;int") DllStructSetData($stRect, 1, $nLeft) DllStructSetData($stRect, 2, $nTop) DllStructSetData($stRect, 3, $nRight) DllStructSetData($stRect, 4, $nBottom) DllCall("user32.dll", "int", "FrameRect", "hwnd", $hDC, "ptr", DllStructGetPtr ($stRect), "hwnd", $hBrush) $stRect = 0 EndFunc ;==>FrameRect Func InflateRect(ByRef $nLeft, ByRef $nTop, ByRef $nRight, ByRef $nBottom, $nX, $nY) Local $stRect = DllStructCreate("int;int;int;int") DllStructSetData($stRect, 1, $nLeft) DllStructSetData($stRect, 2, $nTop) DllStructSetData($stRect, 3, $nRight) DllStructSetData($stRect, 4, $nBottom) DllCall("user32.dll", "int", "InflateRect", "ptr", DllStructGetPtr($stRect), "int", $nX, "int", $nY) $nLeft = DllStructGetData($stRect, 1) $nTop = DllStructGetData($stRect, 2) $nRight = DllStructGetData($stRect, 3) $nBottom = DllStructGetData($stRect, 4) $stRect = 0 EndFunc ;==>InflateRect Func SetBkColor($hDC, $nColor) Local $nOldColor = DllCall("gdi32.dll", "int", "SetBkColor", "hwnd", $hDC, "int", $nColor) Return $nOldColor[0] EndFunc ;==>SetBkColor Func SetTextColor($hDC, $nColor) Local $nOldColor = DllCall("gdi32.dll", "int", "SetTextColor", "hwnd", $hDC, "int", $nColor) Return $nOldColor[0] EndFunc ;==>SetTextColor Func SelectObject($hDC, $hObj) Local $hOldObj = DllCall("gdi32.dll", "hwnd", "SelectObject", "hwnd", $hDC, "hwnd", $hObj) Return $hOldObj[0]

EndFunc ;==>SelectObject Func DeleteObject($hObj) Local $nResult = DllCall("gdi32.dll", "hwnd", "DeleteObject", "hwnd", $hObj) EndFunc ;==>DeleteObject Func GetWindowLong($hWnd, $nIndex) Local $nVal = DllCall("user32.dll", "int", "GetWindowLong", "hwnd", $hWnd, "int", $nIndex) Return $nVal[0] EndFunc ;==>GetWindowLong

Function Reference

GUIStartGroup
Defines that any subsequent controls that are created will be "grouped" together. GUIStartGroup ( [winhandle] ) Parameters winhandle Return Value Success: Failure: Remarks This function is generally used when working with radio button controls. When you click a radio button all other radio buttons in the same grouping are reset. The GUIStartGroup function allows you to easily define these groups. Related GUICtrlCreateGroup Example Returns 1. Returns 0. [optional] Windows handle as returned by GUICreate (default is the previously used window).

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $button_1, $group_1, $radio_1, $radio_2, $radio_3 Local $radio_4, $radio_5, $radio_6, $input_1, $input_2 Local $radioval1, $radioval2, $msg Opt("GUICoordMode", 1) GUICreate("Radio Box Grouping Demo", 400, 280) ; Create the controls $button_1 = GUICtrlCreateButton("B&utton 1", 30, 20, 120, 40) $group_1 = GUICtrlCreateGroup("Group 1", 30, 90, 165, 160) GUIStartGroup() $radio_1 = GUICtrlCreateRadio("Radio &0", 50, 120, 70, 20) $radio_2 = GUICtrlCreateRadio("Radio &1", 50, 150, 60, 20) $radio_3 = GUICtrlCreateRadio("Radio &2", 50, 180, 60, 20) GUIStartGroup() $radio_4 = GUICtrlCreateRadio("Radio &A", 120, 120, 70, 20) $radio_5 = GUICtrlCreateRadio("Radio &B", 120, 150, 60, 20) $radio_6 = GUICtrlCreateRadio("Radio &C", 120, 180, 60, 20) GUIStartGroup() $input_1 = GUICtrlCreateInput("Input 1", 200, 20, 160, 30) $input_2 = GUICtrlCreateInput("Input 2", 200, 70, 160, 30)

; Set the defaults (radio buttons clicked, default button, etc) GUICtrlSetState($radio_1, $GUI_CHECKED) GUICtrlSetState($radio_6, $GUI_CHECKED) GUICtrlSetState($button_1, $GUI_FOCUS + $GUI_DEFBUTTON)

; Init our vars that we will use to keep track of radio events $radioval1 = 0 ; We will assume 0 = first radio button selected, 2 = last button $radioval2 = 2 GUISetState() ; In this message loop we use variables to keep track of changes to the radios, another ; way would be to use GUICtrlRead() at the end to read in the state of each control. Both ; methods are equally valid While 1 $msg = GUIGetMsg() Select Case $msg = $GUI_EVENT_CLOSE Exit Case $msg = $button_1 MsgBox(0, "Button", "Radio " & $radioval1 & @LF & "Radio " & Chr($radioval2 + Asc("A")) & @LF & GUICtrlRead($input_1) & @LF & GUICtrlRead($input_2)) Case $msg = $radio_1 Or $msg = $radio_2 Or $msg = $radio_3 $radioval1 = $msg - $radio_1 Case $msg = $radio_4 Or $msg = $radio_5 Or $msg = $radio_6 $radioval2 = $msg - $radio_4 EndSelect WEnd EndFunc ;==>Example

Function Reference

GUISwitch
Switches the current window used for GUI functions. GUISwitch ( winhandle [, tabitemID] ) Parameters winhandle tabitemID Return Value Success: Failure: Remarks Many of the GUI specific functions work on the "current" window - this is usually the last window created with GUICreate. This function allows you to make another window "current". That's does not mean that the referenced window will become active. You have to use WinActivate. Using the tabitemID allow to create new control in the specified tabitem control. Don't forget to close tabitem definition GuiCtrlCreateTabItem("") Related GUICreate, GUIDelete, GUICtrlCreateTabItem Example Returns the handle of the previously current. Returns a NULL handle. The handle of the window to switch to. [optional] controlID of the tabitem control to be selected.

#include <GUIConstantsEx.au3> Opt('MustDeclareVars', 1) Example() Func Example() Local $parent1, $parent2, $tabitem, $msg $parent1 = GUICreate("Parent1") GUICtrlCreateTab(10, 10) $tabitem = GUICtrlCreateTabItem("tab1") GUICtrlCreateTabItem("tab2") GUICtrlCreateTabItem("") $parent2 = GUICreate("Parent2", -1, -1, 100, 100) GUISwitch($parent2) GUISetState() Do $msg = GUIGetMsg() Until $msg = $GUI_EVENT_CLOSE

GUISwitch($parent1, $tabitem) GUICtrlCreateButton("OK", 50, 50, 50) GUICtrlCreateTabItem("")

GUISetState(@SW_SHOW, $parent1) Do $msg = GUIGetMsg() Until $msg = $GUI_EVENT_CLOSE EndFunc ;==>Example

Keyboard functions Reference


Below is a complete list of the functions available in AutoIt. Click on a function name for a detailed description. Function HotKeySet Send SendKeepActive Description Sets a hotkey that calls a user function. Sends simulated keystrokes to the active window. Attempts to keep a specified window active during Send().

Function Reference

HotKeySet
Sets a hotkey that calls a user function. HotKeySet ( "key" [, "function"] ) Parameters key function Return Value Success: Failure: Remarks If two AutoIt scripts set the same HotKeys, you should avoid running those scripts simultaneously. (The second script cannot capture the hotkey unless the first script terminates or unregisters the key prior to the second script setting the hotkey.) A hotkey-press *typically* interrupts the active AutoIt function/statement and runs its user function until it completes or is interrupted. Exceptions are as follows: 1) If the current function is a "blocking" function, then the key-presses are buffered and execute as soon as the blocking function completes. MsgBox and FileSelectFolder are examples of blocking functions. Try the behavior of Shift-Alt-d in the Example. 2) If you have paused the script by clicking on the AutoIt Tray icon, any hotkeys pressed during this paused state are ignored. The following hotkeys cannot be set: Ctrl+Alt+Delete F12 NumPad's Enter Key It is reserved by Windows It is also reserved by Windows, according to its API. Instead, use {Enter} which captures both Enter keys on the keyboard. Returns 1. Returns 0. The key combination to use as the hotkey. Same format as Send(). [optional] The name of the function to call when the key is pressed. Not specifying this parameter will unset a previous hotkey.

Win+B,D,E,F,L,M,R,U; These are built-in Windows shortcuts. Note: Win+B and Win+L might only be reserved on and Win+Shift+M Windows XP and above. Alt, Ctrl, Shift, Win Other These are the modifier keys themselves! Any global hotkeys a user has defined using third-party software, any combos of two or more "base keys" such as '{F1}{F2}', and any keys of the form '{LALT}' or '{ALTDOWN}'.

When you set a hotkey, AutoIt captures the key-press and does not pass it on to the active application, with one exception: the Lock keys (NumLock, CapsLock, and ScrollLock) still toggle their respective state! To Send() a key combination which will trigger a HotKeySet() event, either use ControlSend() or unregister the HotKeySet() event, otherwise, the Send() event may trigger an infinite loop. ; capture and pass along a keypress HotKeySet("{Esc}", "captureEsc") Func captureEsc() ; ... can do stuff here HotKeySet("{Esc}") Send("{Esc}") HotKeySet("{Esc}", "captureEsc") EndFunc

The called function can not be given parameters. They will be ignored. @HotKeyPressed macro can be used inside the function to handle several keys in the same function. Related Send, GUISetAccelerators Example

; Press Esc to terminate script, Pause/Break to "pause" Global $Paused HotKeySet("{PAUSE}", "TogglePause") HotKeySet("{ESC}", "Terminate") HotKeySet("+!d", "ShowMessage") ;Shift-Alt-d ;;;; Body of program would go here ;;;; While 1 Sleep(100) WEnd ;;;;;;;; Func TogglePause() $Paused = NOT $Paused While $Paused sleep(100) ToolTip('Script is "Paused"',0,0) WEnd ToolTip("") EndFunc Func Terminate() Exit 0 EndFunc Func ShowMessage() MsgBox(4096,"","This is a message.") EndFunc

Function Reference

Send
Sends simulated keystrokes to the active window. Send ( "keys" [, flag] ) Parameters keys flag The sequence of keys to send. [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.

Return Value None. Remarks See the Appendix for some tips on using Send. AutoIt can send all ASCII and Extended ASCII characters (0255), to send UNICODE characters you must use the "ASC" option and the code of the character you wish to send (see {ASC} at the bottom of the table below). The "Send" command syntax is similar to that of ScriptIt and the Visual Basic "SendKeys" command. Characters are sent as written with the exception of the following characters: '!' 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 set SendCapslockMode to make CAPS LOCK disabled at the start of a Send operation and restored upon completion. However, if a user is holding down the Shift key when a Send function begins, text may be sent in uppercase. One workaround is to Send("{SHIFTDOWN}{SHIFTUP}") before the other Send operations. Certain keyboard as the Czech one send different characters when using the Shift Key or being in CAPS LOCK enabled and sending a char. Due to the send AutoIt implementation the CAPS LOCKed char will be sent as Shifted one so it will not work. Certain special keys can be sent and should be enclosed in braces: N.B. Windows does not allow the simulation of the "CTRL-ALT-DEL" c ombination!

Send Command (if zero flag) {!} {#} {+} {^} {{} {}} {SPACE} {ENTER} {ALT} {BACKSPACE} or {BS} {DELETE} or {DEL} {UP} {DOWN} {LEFT} {RIGHT } {HOME} {END} {ESCAPE} or {ESC} {INSERT} or {INS} {PGUP} {PGDN} {F1} - {F12} {TAB} {PRINT SCREEN} {LWIN} {RWIN} {NUMLOCK on} {CAPSLOCK off} {SCROLLLOCK toggle} {BREAK} {PAUSE} {NUMPAD0} - {NUMPAD9} {NUMPADMULT} {NUMPADADD} {NUMPADSUB} {NUMPADDIV} {NUMPADDOT} {NUMPADENTER} {APPSKEY} {LALT} {RALT} {LCTRL} {RCTRL} {LSHIFT} {RSHIFT}

Resulting Keypress ! # + ^ { } SPACE ENTER key on the main keyboard ALT BACKSPACE DELETE Up arrow Down arrow Left arrow Right arrow HOME END ESCAPE INS PageUp PageDown Function keys TAB Print Screen key Left Windows key Right Windows key NUMLOCK (on/off/toggle) CAPSLOCK (on/off/toggle) SCROLLLOCK (on/off/toggle) for Ctrl+Break proc essing PAUSE Numpad digits Numpad Multiply Numpad Add Numpad Subtract Numpad Divide Numpad period Enter key on the numpad Windows App key Left ALT key Right ALT key Left CTRL key Right CTRL key Left Shift key Right Shift key

{SLEEP} {ALTDOWN} {SHIFTDOWN} {CTRLDOWN} {LWINDOWN} {RWINDOWN} {ASC nnnn} {BROWSER_BACK} {BROWSER_FORWARD} {BROWSER_REFRESH} {BROWSER_STOP} {BROWSER_SEARCH} {BROWSER_FAVORITES} {BROWSER_HOME} {VOLUME_MUTE} {VOLUME_DOWN} {VOLUME_UP} {MEDIA_NEXT} {MEDIA_PREV} {MEDIA_STOP} {MEDIA_PLAY_PAUSE} {LAUNCH_MAIL} {LAUNCH_MEDIA} {LAUNCH_APP1} {LAUNCH_APP2}

Computer SLEEP key Holds the ALT key down until {ALTUP} is sent Holds the SHIFT key down until {SHIFTUP} is sent Holds the CTRL key down until {CTRLUP} is sent Holds the left Windows key down until {LWINUP} is sent Holds the right Windows key down until {RWINUP} is sent Send the ALT+nnnn key combination 2000/XP Only: Select the browser "back" button 2000/XP Only: Select the browser "forward" button 2000/XP Only: Select the browser "refresh" button 2000/XP Only: Select the browser "stop" button 2000/XP Only: Select the browser "search" button 2000/XP Only: Select the browser "favorites" button 2000/XP Only: Launch the browser and go to the home page 2000/XP Only: Mute the volume 2000/XP Only: Reduce the volume 2000/XP Only: Increase the volume 2000/XP Only: Select next track in media player 2000/XP Only: Select previous track in media player 2000/XP Only: Stop media player 2000/XP Only: Play/pause media player 2000/XP Only: Launch the email application 2000/XP Only: Launch media player 2000/XP Only: Launch user app1 2000/XP Only: Launch user app2

To send the ASCII value A (same as pressing ALT+065 on the numeric keypad) Send("{ASC 065}") (When using 2 digit ASCII codes you must use a leading 0, otherwise an obsolete 437 code page is used). To send UNICODE characters enter the character code (decimal or hex), for example this sends a Chinese character Send("{ASC 2709}") or Send("{ASC 0xA95}") Single keys can also be repeated, e.g. Send("{DEL 4}") ;Presses the DEL key 4 times Send("{S 30}") ;Sends 30 'S' characters Send("+{TAB 4}") ;Presses SHIFT+TAB 4 times The key will be send at least once even if the count is zero. To hold a key down (generally only useful for games) Send("{a down}") ;Holds the A key down Send("{a up}") ;Releases the A key To set the state of the capslock, numlock and scrolllock keys Send("{NumLock on}") ;Turns the NumLock key on Send("{CapsLock off}") ;Turns the CapsLock key off Send("{ScrollLock toggle}") ;Toggles the state of ScrollLock If you wish to use a variable for the count, try $n = 4 Send("+{TAB " & $n & "}") If you wish to send the ASCII value A four times, then try

$x = Chr(65) Send("{" & $x & " 4}") Most laptop computer keyboards have a special Fn key. This key cannot be simulated. Note, by setting the flag parameter to 1 the above "special" processing will be disabled. This is useful when you want to send some text copied from a variable and you want the text sent exactly as written. For example, open Folder Options (in the control panel) and try the following: Send("{TAB}") Send("+{TAB}") Send("^{TAB}") Send("^+{TAB}") Send("{SPACE}") Send("{+}") Send("{-}") Send("{NumPadMult}") Navigate to next control (button, checkbox, etc) Navigate to previous control. Navigate to next WindowTab (on a Tabbed dialog window) Navigate to previous WindowTab. Can be used to toggle a checkbox or click a button. Usually checks a checkbox (if it's a "real" checkbox.) Usually unchecks a checkbox. Recursively expands folders in a SysTreeView32.

Use Alt-key combos to access menu items. Also, open Notepad and try the following: Send("!f") Send Alt+f, the access key for Notepad's file menu. Try other letters! Send("{DOWN}") Send("{UP}") Send("{LEFT}") Send("{RIGHT }") Move down a menu. Move up a menu. Move leftward to new menu or expand a submenu. Move rightward to new menu or collapse a submenu.

See Windows' Help--press Win+F1--for a complete list of keyboard shortcuts if you don't know the importance of Alt+F4, PrintScreen, Ctrl+C, and so on. When running a script on a remote computer through a program as psexec (www.sysinternals.com) or beyondexec (www.beyondlogic.org) it is necessary, specially when sending strokes to a program launch by the script with a Run function, to use ControlSend or other ControlXXX functions to directly communicate with the control. Send even with Opt("SendAttachMode",1) is not working. Using the -s mode when submitting can help to have better right on the remote computer. Opt("SendKeyDelay",...) alters the the length of the brief pause in between sent keystrokes. Opt("SendKeyDownDelay",...) alters the length of time a key is held down before being released during a keystroke. Set both "SendKeyDelay" and "SendKeyDownDelay" to 0 to remove all delays when sending keystrokes. This may be required under certain circumstances, for example, when locking the system ("#l") it may be necessary to remove the delays in order to prevent the WIN key from being stuck down. Related SendAttachMode (Option), SendKeepActive, SendKeyDelay (Option), SendKeyDownDelay (Option), ControlSend, Bloc kInput, HotKeySet, WinMenuSelectItem Example

Send("#r") WinWaitActive("Run") Send("notepad.exe{Enter}") WinWaitActive("[CLASS:Notepad]") Send("Today's time/date is {F5}")

Function Reference

SendKeepActive
Attempts to keep a specified window active during Send(). SendKeepActive ( "title" [, "text"] ) Parameters title text Return Value Success: Failure: Remarks Attempts to reset the active window in between each simulated keystroke from Send(). Related Send Example Returns 1. Returns 0 if window is not found. The title of the window to activate. See Title special definition. Use a blank title to disable the function. [optional] The text of the window.

Run("notepad.exe") WinWait("[CLASS:Notepad]") SendKeepActive("[CLASS:Notepad]") ; Change the active window during pauses For $i = 1 to 10 Sleep(1000) Send("Hello") Next

Math functions Reference


Below is a complete list of the functions available in AutoIt. Click on a function name for a detailed description. Function Abs ACos ASin ATan BitAND BitNOT BitOR BitRotate BitShift BitXOR Cos Ceiling Exp Floor Log Mod Random Round Sin Sqrt SRandom Tan Description Calculates the absolute value of a number. Calculates the arcCosine of a number. Calculates the arcsine of a number. Calculates the arctangent of a number. Performs a bitwise AND operation. Performs a bitwise NOT operation. Performs a bitwise OR operation. Performs a bit shifting operation, with rotation. Performs a bit shifting operation. Performs a bitwise exclusive OR (XOR) operation. Calculates the cosine of a number. Returns a number rounded up to the next integer. Calculates e to the power of a number. Returns a number rounded down to the closest integer. Calculates the natural logarithm of a number. Performs the modulus operation. Generates a pseudo-random float-type number. Returns a number rounded to a specified number of decimal places. Calculates the sine of a number. Calculates the square-root of a number. Set Seed for random number generation. Calculates the tangent of a number.

Function Reference

Abs
Calculates the absolute value of a number. Abs ( expression ) Parameters expression Return Value Returns absolute value of expression. Remarks A string has a value of zero. Related None. Example Any valid numeric expression.

$var = Abs(-123.45) ;value is 123.45

Function Reference

ACos
Calculates the arcCosine of a number. ACos ( expression ) Parameters expression Return Value Returns the trigonometric arccosine of expression. Result is in radians. Remarks ACos(x) is mathematically defined only for -1 < x < 1, so ACos tends to return -1.#IND for other values of x. Related Sin, Cos, Tan, ASin, ATan Example Any value between -1 and 1 inclusive.

$x = ACos(0.5) $pi = 3.14159265358979 $radToDeg = 180 / $pi $y = ACos(-1) * $radToDeg ;arcCosine of -1 returns 180

Function Reference

ASin
Calculates the arcsine of a number. ASin ( expression ) Parameters expression Return Value Returns the trigonometric arcsine of expression. Result is in radians. Remarks ASin(x) is mathematically defined only for -1 < x < 1, so ASin tends to return -1.#IND for other values of x. Related Sin, Cos, Tan, ACos, ATan Example Any value between -1 and 1 (inclusive).

$x = ASin(0.5) $pi = 3.14159265358979 $radToDeg = 180 / $pi $y = ASin(1) * $radToDeg ;arcsine of 1 returns 90

Function Reference

ATan
Calculates the arctangent of a number. ATan ( expression ) Parameters expression Return Value Returns the trigonometric arctangent of expression. Result is in radians. Remarks The result of 4 * ATan(1) is pi. Related Sin, Cos, Tan, ASin, ACos Example Any valid numeric expression.

$x = ATan(0.5) $pi = 4 * ATan(1) ;equals 3.14159265358979 $radToDeg = 180 / $pi $y = ATan(1) * $radToDeg ;arctangent of 1 returns 45

Function Reference

BitAND
Performs a bitwise AND operation. BitAND ( value1, value2 [, value n] ) Parameters value1 value2 value n Return Value Returns the value of the parameters bitwise-AND'ed together. Bit operations are performed as 32-bit integers. Remarks Remember hex notation can be used for numbers. BitAND returns 1 in each bit position where all input arguments have a 1 in the corresponding position and 0 in all others, Related BitNOT, BitOR, BitShift, BitXOR, Hex, BitRotate Example The first number. The second number. [optional] The nth number - up to 255 values can be specified.

$x = BitAND(13, 7) ;x == 5 because 1101 AND 0111 = 0101 $x = BitAND(2, 3, 6) ;x == 2 because 0010 AND 0011 AND 0110 = 0010

Function Reference

BitNOT
Performs a bitwise NOT operation. BitNOT ( value ) Parameters value Return Value Returns the bitwise NOT of the value. Bit operations are performed as 32-bit integers. Remarks Remember hex notation can be used for numbers. Remember that in 2's-complement notation, BitNOT is functionally equivalent to adding 1 and negating the result. Also remember that NOT changes a 0 bit to 1 and vice-versa. Related BitAND, BitOR, BitShift, BitXOR, Hex, BitRotate Example The number to operate on.

$x = BitNot(5) #cs #ce Comments: Result is -6 because for 32-bit numbers 5 == 00000000000000000000000000000101 binary -6 == 11111111111111111111111111111010 binary and the first bit is signed

Function Reference

BitOR
Performs a bitwise OR operation. BitOR ( value1, value2 [, value n] ) Parameters value1 value2 value n Return Value Returns the two parameters bitwise-OR'ed together. Bit operations are performed as 32-bit integers. Remarks Remember hex notation can be used for numbers. BitOR returns 0 in each bit position where all input arguments have a 0 in the corresponding position and 1 wherever there is at least one 1-bit. Related BitAND, BitNOT, BitShift, BitXOR, Hex, BitRotate Example The first number. The second number. [optional] The nth number - up to 255 values can be specified.

$x = BitOR(3, 6) ;x == is 7 because 0011 OR 0110 = 0111 $x = BitOR(3, 15, 32) ;x == 47 because 0011 OR 1111 OR 00100000 = 00101111

Function Reference

BitRotate
Performs a bit shifting operation, with rotation. BitRotate ( value , shift [, size] ) Parameters value shift size The number to be operate on. Number of bits to rotate to the left (negative numbers shift right). If not given, the default is 1. [optional] A string that determines the rotation size, the default is (16 bits). See below.

Size parameter : "B" "W" "D" Return Value Success: Returns the value rotated by the required number of bits. Failure: Set @error if size is invalid Bit operations are performed as 32-bit integers. Remarks Remember hex notation can be used for numbers. Related BitShift, BitAND, BitNOT, BitOR, BitXOR, Hex Example rotate bits within the low-order byte (8 bits). rotate bits within the low-order word (16 bits). rotate bits within the entire double-word (32 bits).

$x = BitRotate(7, 2) ; x == 3 because 111b left-rotated twice is 1 1100b == 28 $y = BitRotate(14, -2) ; y == 32771 because 1110b right-rotated twice on 16 bits is 1000 0000 0000 0011b == 32771 $z = BitRotate(14, -2, "D") ; z == -2147483645 because 1110b right-rotated twice on 16 bits is 1000 0000 0000 0000 0000 0000 0000 0011b == 2147483645

Function Reference

BitShift
Performs a bit shifting operation. BitShift ( value, shift ) Parameters value shift Return Value Returns the value shifted by the required number of bits. Bit operations are performed as 32-bit integers. Remarks Remember hex notation can be used for numbers. Right shifts are equivalent to halving; left shifts to doubling. Related BitAND, BitNOT, BitOR, BitXOR, Hex, BitRotate Example The number to be shifted. Number of bits to shift to the right (negative numbers shift left).

$x = BitShift(14, 2) ; x == 3 because 1110b right-shifted twice is 11b == 3 $y = BitShift(14, -2) ; y == 56 because 1110b left-shifted twice is 111000b == 56 $z = BitShift( 1, -31) ; z == -2147483648 because in 2's-complement notation, the ; 32nd digit from the right has a negative sign.

Function Reference

BitXOR
Performs a bitwise exclusive OR (XOR) operation. BitXOR ( value1, value2 [, value n] ) Parameters value1 value2 value n Return Value Returns the value of the parameters bitwise-XOR'ed together. Bit operations are performed as 32-bit integers. Remarks Remember hex notation can be used for numbers. BitXOR returns 1 in a bit position if there are an odd number 1's in the corresponding bit position in all the input arguments, and 0 otherwise. Related BitAND, BitNOT, BitOR, BitShift, Hex, BitRotate Example The first number. The second number. [optional] The nth number - up to 255 values can be specified.

$x = BitXOR(10, 6) ;x == 12 because 1010b XOR 0110b == 1100 $x = BitXOR(2, 3, 6) ;x == 7 because 0010 XOR 0011 XOR 0110 = 0111

Das könnte Ihnen auch gefallen