Auto It 3
April 19, 2017 | Author: Francisco Valera | Category: N/A
Short Description
Download Auto It 3...
Description
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 Scripts 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
Description
(Top-level files) AutoIt3.exe
The AutoIt main program and only file required to run scripts!
AutoIt3_x64.exe
The x64 version of AutoIt (if installed).
AU3Info.exe
The AutoIt Window Info Tool.
AU3Info_x64.exe
The x64 version of Au3Info (if installed).
AU3Check.exe
The AutoIt syntax checker.
AutoIt.chm
This help file which use AutoIt3.chm and UDFs3.chm
Uninstall.exe
The AutoIt uninstaller.
AutoIt v3 Website.url
A shortcut to http://www.autoitscript.com/autoit3/
Aut2Exe
Icons\
Contains icons used for the .au3 filetype icon in Explorer.
Aut2Exe.exe
The script compiler.
Aut2Exe_x64.exe
The x64 version of Aut2Exe (if installed).
AutoItSC.bin
Executable stub for compiled scripts.
AutoItSC_x64.bin
x64 executable stub for compiled scripts.
UPX.exe
The UPX compressor (shinks the size of exe files).
Examples GUI\
Contains examples of GUIs written in AutoIt.
Helpfile\
Contains scripts used in many of the help file examples.
AutoUpdateIt\
Contains a script for easily retrieving the latest version of AutoIt3.
Editors\
Contains syntax coloring definitions for some popular text editors.
Exe2Aut\
Contains utils for converting compiled scripts back in to source code.
SQLite\
Contains SQLite command line executable and an help file.
Extras
v2_to_v3_Converter\ Contains a tool for converting v2.64 script to AutoIt v3 syntax. Icons Contains icons used for the .au3 filetype icon in Explorer. Include Contains standard include files (pre-written user functions). See the Library Functions) AutoItX Contains a DLL version of AutoIt v3 that provides a subset of the features of AutoIt via an ActiveX/COM and DLL interface. SciTe Contains a light version of SciTe which allows syntax coloring. It should be repeated that to run AutoIt scripts, the only required file is AutoIt3.exe. If you compile a script into an executable then a user does not require AutoIt to be installed to run that compiled executable. (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 )
Registry Keys The AutoIt installer creates registry keys under HKEY_LOCAL_MACHINE\Software\AutoIt v3 and
HKEY_CURRENT_USER\Software\AutoIt v3. The keys are NOT used/created when AutoIt utilities are run on machines that lack a full AutoIt installation--AutoIt is "clean" to run on servers, etc. The table below shows the default (or typical) registry keys. The keys in italic are not created by the installer itself but by the first execution of the corresponding utility: HKEY_LOCAL_MACHINE\SOFTWARE\AutoIt v3\ AutoIt (Default)
REG_SZ
(value not set)
InstallDir
REG_SZ
C:\Program Files\AutoIt3
Version
REG_SZ
Version Number
HKEY_CURRENT_USER\Software\AutoIt v3\ Aut2Exe (Default)
REG_SZ
(value not set)
AllowDec ompile
REG_DWORD
0x1
LastCompression
REG_DWORD
0x2
LastExeDir
REG_SZ
My Documents
LastIcon
REG_SZ
LastIconDir
REG_SZ
C:\Program Files\AutoIt3\Aut2Exe\Icons
LastScriptDir
REG_SZ
My Documents
(Default)
REG_SZ
(value not set)
DoneOption
REG_SZ
Notify
DownloadDir
REG_SZ
C:\Downloads\ForExample\
(Default)
REG_SZ
(value not set)
LastExeDir
REG_SZ
C:\ForExample\
LastScriptDir
REG_SZ
Default
REG_SZ
(value not set)
AlwaysOnTop
REG_DWORD
0x1
ColorMode
REG_DWORD
0x1
CoordMode
REG_DWORD
0x1
HighlightColor
REG_DWORD
0x0
HighlightControls
REG_DWORD
0x1
Magnify
REG_DWORD
0x0
WinH
REG_DWORD
0x01c 2
WinW
REG_DWORD
0x012c
WinX
REG_DWORD
0x0064
WinY
REG_DWORD
0x0064
AutoUpdateIt
Exe2Aut
AU3Info
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.7E–308 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 Scripts
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 [/out ] [/icon ] [/comp 0-4] [/nopack] [x64] [/bin ] Where Switch
Usage
/in
Specifies the path and file name of the script to be compiled.
Default value None. The file must be specified
/out
Specifies the path and name of the compiled file. Specifies the path and file name when creating an *.a3x file.
The input filename with a .exe extension
/icon
Specifies the path and file name of the icon to use for the compiled file.
/comp
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).
The AutoIt icon 2
/nopack
Specifies that the file should not be compressed with UPX after compilation.
pack
/pack
Specifies that the file should be compressed with UPX after compilation.
pack
/x64
Specifies that the script should be compiled for use on systems with x64 (64-bit) architecture.
see notes
/x86
Specifies that the script should be compiled for use on systems with x86 (32-bit) architecture.
see notes
/console
Specifies that the script should be compiled as a Console application.
/gui
Specifies that the script should be compiled as a Windows application.
Windows application (/gui)
/bin
Specifies the path and file name of the bin file to be use to compile the file.
searched in Aut2exe folder
Windows application (/gui)
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.
Technical 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
Notepad
Notepad++
SciTe (AutoIt Default Editor)
ANSI
ANSI
ANSI
8 bit / Code Page Property
UTF16 Little Endian
Unicode
UCS-2 Little Endian
UCS-2 Little Endian
UTF16 Big Endian
Unicode big endian
UCS-2 Big Endian
UCS-2 Big Endian
UTF8 with BOM
UTF-8
UTF-8
UTF-8 with BOM
UTF8 without BOM
Not supported
UTF-8 without BOM
UTF-8
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.
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 - Conventions: , [,] has been replaced with Cmd(parm1 [,parm2]) - Goto does not exist due to the support of loops and user-defined functions. - AutoItv3 supports variables like most programming languages: $myVar = "Example of assignment" - Scripts have the extension .au3 instead of .aut If you wish to re-write version 2.64 scripts as version 3, the following table may help you: Version 2.64 function
Version 3 equivalent
AdlibOn
AdlibRegister
Bloc kInput
Bloc kInput
Break
Break
DetectHiddenText
AutoItSetOption("WinDetectHiddenText",...)
Exit
Exit
EnvAdd
[see + operator]
EnvDiv
[see / operator]
EnvMult
[see * operator]
EnvSub
[see - operator]
FileAppend
[FileOpen(...,2) followed by FileWriteLine]
FileCopy
FileCopy
FileCreateDir
DirCreate
FileDelete
FileDelete or FileRecycle
FileInstall
FileInstall
FileReadLine
FileReadLine
FileRemoveDir
DirRemove
FileSelectFile
FileOpenDialog or FileSaveDialog
Gosub
[see Func...EndFunc]
Return
[see Func...EndFunc]
Goto
[not needed]
HideAutoItDebug
--
HideAutoItWin
AutoItSetOption("TrayIconHide",...)
IfInString
If StringInStr(...) Then
IfNotInString
If Not StringInStr(...) Then
IfWinExist
If WinExists(...) Then
IfWinNotExist
If Not WinExists(...) Then
IfWinActive
If WinActive(...) Then
IfWinNotActive
If Not WinActive(...) Then
IfEqual
[see = and == operators]
IfNotEqual
[see operator]
IfGreater
[see > operator]
IfGreaterOrEqual
[see >= operator]
IfLess
[see < operator]
IfLessOrEqual
[see 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
[optional] If present, the Const keyword creates a constant rather than a variable.
$variable
The name of the variable/constant to declare.
initializer
The value that will be initially assigned to the variable. A Const must include the initializer. The initializer can be a function call.
subscript
The number of elements to create for the array dimension, indexed 0 to n-1.
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
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
[optional] The level of the loop to restart. The default is 1 (meaning the current loop).
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
;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 Parameters expression
The statements in between Do and Until are executed until the expression is true.
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
Keyword Reference
Enum Enumerates constants. [scope] Enum [Step ] Parameters scope
[optional] The scope the Enum should be placed in, either Local, Global, Dim or none. If none, Dim behavior is used.
stepval
[optional] The default step is to add 1. Other possible step methods are: *n, +n, -n where n is a whole number.
constantlist
A list constants to be enumerated.
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)
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
return code
[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.
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
[optional] The number of loop levels to exit from. The default is 1 (meaning the current loop).
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)
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 = To [Step ] statements ... Next Parameters variable
The variable used for the count.
start
The initial numeric value of the variable.
stop
The final numeric value of the variable.
stepval
[optional] The numeric value (possibly fractional) that the count is increased by each loop. Default is 1.
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!")
Keyword Reference
For...In...Next Enumerates elements in an Object collection or an array For In statements ... Next Parameters Variable
A variable to which an element is being assigned
expression
Must be an expression resulting in an Object, or an Array with at least one element
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
;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 Then statement Parameters expression
If the expression is true, the statement is executed.
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
;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 Then statements ... [ElseIf expression-n Then [elseif statements ... ]] ... [Else [else statements] ... EndIf Parameters expression
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.
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
Keyword Reference
ReDim Resize an existing array ReDim $array[subscript 1]...[subscript n] Parameters $array
The name of the array to resize.
subscript
The number of elements to create for the array dimension, indexed 0 to n-1.
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
; 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 statement1 ... [Case statement2 ...] [Case Else statementN ...] EndSelect Parameters Case
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.
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
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
An optional modifier, Local or Global that indicates where the variable is visible.
$variable
The name of the static variable to declare.
initializer
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.
subscript
The number of elements to create for the array dimension, indexed 0 to n-1.
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.
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 Case [To ] [, [To ] ...] statement1 ... [Case [To ] [, [To ] ...] statement2 ...] [Case Else statementN ...] EndSwitch Parameters
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.
To
The case is executed if the expression is between the two values.
The case is executed if the expression matches the 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)
Keyword Reference
With...EndWith Used to reduce long references to object type variables With statements ... EndWith Parameters expression
Must be an object type expression
Remarks With...EndWith statements may NOT be nested. Related For...In...Next Example
$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 statements ... WEnd Parameters expression
If the expression is true the following statements up to the WEnd statement are executed. This loop continues until the expression is false.
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 = 0 the sizes
Failure:
Returns -1 and sets @error to 1 if the path doesn't exist.
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
$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
Path of the source directory (with no trailing backslash). e.g. "C:\Path1"
dest dir
Path of the destination dir (with no trailing backslash). e.g. "C:\Path_Copy"
flag
[optional] this flag determines whether to overwrite files if they already exist: 0 = (default) do not overwrite existing files 1 = overwrite existing files
Return Value Success:
Returns 1.
Failure:
Returns 0 if there is an error moving the directory.
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
DirMove(@MyDocumentsDir, "C:\Backups\MyDocs")
Function Reference
DirRemove Deletes a directory/folder. DirRemove ( "path" [, recurse] ) Parameters path
Path of the directory to remove.
recurse
[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)
Return Value Success:
Returns 1.
Failure:
Returns 0 if there is an error removing the directory (or if directory does not exist).
Remarks Some dir attributes can make the removal impossible. Related DirCreate, FileRecycle, DirCopy, DirMove, FileDelete Example
; 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 of drive to find: "ALL", "CDROM", "REMOVABLE", "FIXED", "NET WORK", "RAMDISK", or "UNKNOWN"
type Return Value Success:
Returns an array of strings (drive letter followed by colon) of drives found. The zeroth array element contains the number of drives.
Failure:
Returns "" and sets @error to 1.
Remarks None. Related DriveGetFileSystem, DriveGetLabel, DriveGetSerial, DriveGetType, DriveSetLabel, DriveSpaceFree, DriveSpaceTotal, DriveStatus Example
$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 of drive to receive information from.
path Return Value Success:
Returns the File System Type of the drive as a string; see table below.
Failure:
Sets @error to 1.
Return Value
Interpretation
1 (numeric)
Drive does NOT contain media (CD, Floppy, Zip) or media is unformatted (RAW).
"FAT"
Typical file system for drives under ~500 MB such as Floppy, RAM disks, USB "pen" drives, etc.
"FAT32"
Typical file system for Windows 9x/Me hard drives.
"NTFS"
Typical file system for Windows NT/2000/XP hard drives.
"NWFS"
Typical file system for Novell Netware file servers.
"CDFS"
Typically indicates a CD (or an ISO image mounted as a virtual CD drive).
"UDF"
Typically indicates a DVD.
Remarks 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
Path of drive to receive information from.
Return Value Success:
Returns the Volume Label of the drive as a string.
Failure:
Sets @error to 1.
Remarks None. Related DriveGetDrive, DriveGetFileSystem, DriveGetSerial, DriveGetType, DriveSetLabel, DriveSpaceFree, DriveSpaceTotal, DriveStatus Example
$var = DriveGetLabel( "c:\" ) MsgBox(4096,"Volume Label: ",$var)
Function Reference
DriveGetSerial Returns Serial Number of a drive. DriveGetSerial ( "path" ) Parameters path
Path of drive to receive information from.
Return Value Success:
Returns the Serial Number of the drive as a string.
Failure:
Sets @error to 1.
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
$var = DriveGetSerial( "c:\" ) MsgBox(4096, "Serial Number: ", $var)
Function Reference
DriveGetType Returns drive type. DriveGetType ( "path" ) Parameters path
Path of drive to receive information from.
Return Value Success:
Returns the type of drive: "Unknown", "Removable", "Fixed", "Network", "CDROM", "RAMDisk"
Failure:
Returns "" and sets @error to 1.
Remarks The list of possible return values might be incomplete. Related DriveGetDrive, DriveGetFileSystem, DriveGetLabel, DriveGetSerial, DriveSetLabel, DriveSpaceFree, DriveSpaceTotal, DriveStatus, CDTray Example
$var = DriveGetType( "c:\" ) MsgBox(4096, "Drive Type:", $var)
Function Reference
DriveMapAdd Maps a network drive. DriveMapAdd ( "device", "remote share" [, flags [, "user" [, "password"]]] ) Parameters device
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.
remote share
The remote share to connect to in the form "\\server\share".
flags
[optional] A combination of the following: 0 = default 1 = Persistent mapping 8 = Show authentication dialog if required
user
[optional] The username to use to connect. In the form "username" or "domain\username".
password
[optional] The password to use to connect.
Return Value Success:
Returns 1. (See Remarks)
Failure:
Returns 0 if a new mapping could not be created and sets @error (see below). (See Remarks)
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
; 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 The device to disconnect, e.g. "O:" or "LPT1:".
drive Return Value Success:
Returns 1.
Failure:
Returns 0 if the disconnection was unsuccessful.
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
; 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 The device (drive or printer) letter to query, e.g. "O:" or "LPT1:"
device Return Value Success:
Returns details of the mapping, e.g. \\server\share
Failure:
Returns a blank string "" and sets @error to 1.
Remarks None. Related DriveMapAdd, DriveMapDel Example
; 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
Path of drive to change.
label
New volume label for the drive. (11 characters is usually max length)
Return Value Success:
Returns 1.
Failure:
Returns 0.
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
DriveSetLabel("C:\", "New_Label")
Function Reference
DriveSpaceFree Returns the free disk space of a path in Megabytes. DriveSpaceFree ( "path" ) Parameters Path of drive to receive information from.
path Return Value Success:
Returns free disk space in Megabytes as a float number.
Failure:
Returns 0 and sets @error to 1.
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
$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
Path of drive to receive information from.
Return Value Success:
Returns diskspace in Megabytes as a float number.
Failure:
Sets @error to 1.
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
$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
Path of drive to receive information from.
Return Value Value
Interpretation
UNKNOWN
Drive may be unformatted (RAW).
READY
Typical of hard drives and drives that contain removable media.
NOTREADY
Typical of floppy and CD drives that do not contain media.
INVALID
May indicate the drive letter does not exist or that a mapped network drive is inaccessible.
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
$var = DriveStatus( "c:\" ) MsgBox(4096,"Status",$var)
Function Reference
FileChangeDir Changes the current working directory. FileChangeDir ( "path" ) Parameters path
The path to make the current working directory.
Return Value Success:
Returns 1.
Failure:
Returns 0 if working directory not changed.
Remarks None. Related @WorkingDir Example
FileChangeDir(@WindowsDir)
Function Reference
FileClose Closes a previously opened text file. FileClose ( filehandle ) Parameters The handle of a file, as returned by a previous call to FileOpen.
filehandle Return Value Success:
Returns 1.
Failure:
Returns 0 if the filehandle is invalid.
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
$handle = FileOpen("test.txt", 0) FileClose($handle)
Function Reference
FileCopy Copies one or more files. FileCopy ( "source", "dest" [, flag] ) Parameters source
The source path of the file(s) to copy. Wildcards are supported.
dest
The destination path of the copied file(s).
flag
[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).
Return Value Success:
Returns 1.
Failure:
Returns 0.
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
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
Path of the source to which the hardlink will be created.
hardlink
Path of the hardlink.
flag
[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:
Returns 1.
Failure:
Returns 0.
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
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
Full path and file name of file to create shortcut to.
lnk
Full path and file name of the shortcut.
workdir
[optional] Working directory.
args
[optional] Additional file arguments.
desc
[optional] File Description.
icon
[optional] Full Path/File name of icon to use.
hotkey
[optional] Hotkey - same as the Send() key format.
ic on number
[optional] The icon instance to use (usually 0)
state
[optional] The state the shortcut is launched in. Use either @SW_SHOWNORMAL, @SW_SHOWMINNOACTIVE or @SW_SHOWMAXIMIZED
Return Value Success:
Returns 1.
Failure:
Returns 0 if lnk cannot be created.
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
; 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
The path of the file(s) to delete. Wildcards are supported.
Return Value Success:
Return 1.
Failure:
Returns 0 if files are not deleted or do not exist.
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
FileDelete("D:\*.tmp")
Function Reference
FileExists Checks if a file or directory exists. FileExists ( "path" ) Parameters Path
The directory or file to check.
Return Value Success:
Returns 1.
Failure:
Returns 0 if path/file does not exist.
Remarks FileExists returns 0 if you specify a floppy drive which does not contain a disk. Related FileGetAttrib, DriveStatus Example
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 File search string. (* and ? wildcards accepted)
filename Return Value Success:
Returns a search "handle" for use with subsequent FileFindNextFile functions.
Failure:
Returns -1 if error occurs. If the Folder is empty the @error is set to 1.
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
; 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 The search handle, as returned by FileFindFirstFile.
search Return Value Success:
Returns a filename according to a previous call to FileFindFirstFile, @extended set to 1 if filename is a directory.
Failure:
Sets @error to 1 if no more files/directories match the search.
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
; 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
A handle to a file previously opened with FileOpen().
Return Value Success:
Returns true if the buffer was flushed (or did not need to be flushed).
Failure:
Returns false.
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)
Function Reference
FileGetAttrib Returns a code string representing a file's attributes. FileGetAttrib ( "filename" ) Parameters filename
Filename (or directory) to check.
Return Value Success:
Returns a code string representing a files attributes.
Failure:
Returns "" (blank string) and sets @error to 1.
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
$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
The handle of a file, as returned by a previous call to FileOpen. Alternatively you may use a string filename as the first parameter.
mode
[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)
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:
Returns -1.
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
Function Reference
FileGetLongName Returns the long path+name of the path+name passed. FileGetLongName ( "file" [, flag] ) Parameters file
full path and file name to convert
flag
[optional] if 1 file can have relative dir, e.g. "..\file.txt"
Return Value Success:
Returns the long path+name of the path+name passed.
Failure:
Returns the parameter and sets @error to 1.
Remarks None. Related FileGetShortName Example
$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 A handle to a file previously opened with FileOpen().
handle Return Value Success:
Returns the position offset from the beginning of the file (First index is 0).
Failure:
Returns 0 and sets @error.
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
#include 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
Full path and file name of the shortcut.
Return Value Success:
Returns an array that contains the shortcut information. See Remarks.
Failure:
Sets @error to 1 if the shortcut could not be accessed.
Remarks The array returned from this function is a single dimension array containing the following elements: $array[0] = Shortcut target path $array[1] = Working directory $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
; 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
full path and file name to convert
flag
[optional] if 1 file can have relative dir, e.g. "..\file.txt"
Return Value Success:
Returns the 8.3 short path+name of the path+name passed.
Failure:
Returns the parameter and sets @error to 1.
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
$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
Filename to check.
Return Value Success:
Returns the size of the file in bytes.
Failure:
Returns 0 and set the @error to 1.
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
$size = FileGetSize("AutoIt.exe")
Function Reference
FileGetTime Returns the time and date information for a file. FileGetTime ( "filename" [, option [, format]] ) Parameters filename
Filename to check.
option
[optional] Flag to indicate which timestamp 0 = Modified (default) 1 = Created 2 = Accessed
format
[optional] to specify type of return 0 = return an array (default) 1 = return a string YYYYMMDDHHMMSS
Return Value Success:
Returns an array or string that contains the file time information. See Remarks.
Failure:
Returns 0 and sets @error to 1.
Remarks 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
Filename to check.
stringname
[optional] name of the field to be retrieved from the header version file info.
Return Value Success:
Returns a string containing the version information, e.g. "3.0.81.0".
Failure:
Returns "0.0.0.0" if no version information (or other error) or "" when retrieving a stringname, and sets @error to 1.
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
$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
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).
dest
The destination path of the file with trailing backslash if only the directory is used. This can be a variable.
flag
[optional] this flag determines whether to overwrite files if they already exist: 0 = (default) do not overwrite existing files 1 = overwrite existing files
Return Value Success:
Returns 1.
Failure:
Returns 0.
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-compilation). 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
; 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
The source path and filename of the file to move. (* wildcards are supported)
dest
The destination path and filename of the moved file. (* wildcards are supported)
flag
[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).
Return Value Success:
Returns 1.
Failure:
Returns 0 if source cannot be moved or if dest already exists and flag=0.
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
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.
mode
[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).
Return Value Success:
Returns a file "handle" for use with subsequent file functions.
Failure:
Returns -1 if error occurs.
Remarks
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
Title text of the Dialog GUI.
init dir
Initial directory selected in the GUI file tree.
filter
File type single filter such as "All (*.*)" or "Text files (*.txt)" or multiple filter groups such as "All (*.*)|Text files (*.txt)" (See Remarks).
options
[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)
default name
[optional] Suggested file name for the user to open. Default is blank ("").
hwnd
[optional] The window handle to use as the parent for this dialog.
Return Value Success:
Returns the full path of the file(s) chosen. Results for multiple selections are "Directory|file1|file2|..."
Failure:
Sets @error
@error:
1 - File selection failed. 2 - Bad file filter
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 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
The handle of a file, as returned by a previous call to FileOpen. Alternatively you may use a string filename as the first parameter.
count
[optional] The number of characters to read. Default read the entire file.
Return Value Success:
Returns the binary/string read. @extended is set to the number of bytes/characters returned.
Special:
Sets @error to -1 if end-of-file is reached.
Failure:
Sets @error to 1 if file not opened in read mode or other error.
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
$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
The handle of a file, as returned by a previous call to FileOpen. Alternatively you may use a string filename as the first parameter.
line
[optional] The line number to read. The first line of a text file is line 1 (not zero), last line is -1.
Return Value Success:
Returns a line of text.
Special:
Sets @error to -1 if end-of-file is reached.
Failure:
Sets @error to 1 if file not opened in read mode or other error.
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
$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
The source path of the file(s) or directory to Recycle. Wildcards are supported.
Return Value Success:
Returns 1.
Failure:
Returns 0 (typically meaning the file is in use or does not exist).
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
FileRecycle("C:\*.tmp")
Function Reference
FileRecycleEmpty Empties the recycle bin. FileRecycleEmpty ( ["source"] ) Parameters [optional] The rootpath to empty - if omitted the recycle bin for all drives is emptied.
source Return Value Success:
Returns 1.
Failure:
Returns 0 (the recycle bin cannot be emptied - see below).
Remarks For this function to work IE4+ must be available. Related FileDelete, FileRecycle Example
FileRecycleEmpty("C:\")
Function Reference
FileSaveDialog Initiates a Save File Dialog. FileSaveDialog ( "title", "init dir", "filter" [, options [, "default name" [, hwnd]]] ) Parameters title
Title text of the Dialog GUI.
init dir
Initial directory selected in the GUI file tree.
filter
File type single filter such as "All (*.*)" or "Text files (*.txt)" or multiple filter groups such as "All (*.*)|Text files (*.txt)" (See Remarks).
options
[optional] 2 = Path Must Exist (if user types a path, ending with a backslash) 16 = Prompt to OverWrite File
default name
[optional] File name to suggest to the user to save the file with. Default is blank ("").
hwnd
[optional] The window handle to use as the parent for this dialog.
Return Value Success:
Returns the full path of the file chosen. Results for multiple selections are "Directory|file1|file2|..."
Failure:
Sets @error
@error:
1 - File selection failed. 2 - Bad file filter
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
; 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
Text greeting in dialog.
root dir
Root directory of GUI file tree. Use "" for Desktop to be root.
flag
[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)
initial dir
[optional] Initial/start directory that will be selected if exist. Default is blank ("").
hwnd
[optional] The window handle to use as the parent for this dialog.
Return Value Success:
Returns full path of the folder chosen.
Failure:
Returns "" (blank string) and sets @error to 1 if user cancels/closes the window.
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
$var = FileSelectFolder("Choose a folder.", "")
Function Reference
FileSetAttrib Sets the attributes of one or more files. FileSetAttrib ( "file pattern", "+-RASHNOT" [, recurse] ) Parameters file pattern
File(s) to change, e.g. C:\*.au3, C:\Dir
+-RASHNOT
Attribute(s) to set/clear. e.g. "+A", "+RA-SH"
recurse
[optional] If this is set to 1, then directories are recursed into. Default is 0 (no recursion).
Return Value Success:
Returns 1.
Failure:
Returns 0 if encountered any errors.
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
;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
A handle to a file previously opened with FileOpen().
offset
The offset to move from the origin. This value may be positive or negative. Negative values move backwards from the origin.
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).
Return Value Success:
True if the operation succeeded.
Failure:
False.
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
#include 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
File(s) to change, e.g. C:\*.au3, C:\Dir
time
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.
type
[optional] The timestamp to change: 0 = Modified (default), 1 = Created, 2 = Accessed
recurse
[optional] If this is set to 1, then directories are recursed into. Default is 0 (no recursion).
Return Value Success:
Returns 1.
Failure:
Returns 0 if error changing timestamp(s).
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
;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
The handle of a file, as returned by a previous call to FileOpen. Alternatively, you may use a string filename as the first parameter.
text/data
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.
Return Value Success:
Returns 1.
Failure:
Returns 0 if file not opened in writemode, file is read only, or file cannot otherwise be written to.
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
$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
The handle of a file, as returned by a previous call to FileOpen. Alternatively, you may use a string filename as the first parameter.
line
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.
Return Value Success:
Returns 1.
Failure:
Returns 0 if file not opened in writemode, file is read only, or file cannot otherwise be written to.
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
$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
The filename of the .ini file.
section
The section name in the .ini file.
key
[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.
Return Value Success:
Returns 1.
Failure:
Returns 0 if the INI file does not exist or if the file is read-only.
Remarks A standard ini file looks like: [SectionName] Key=Value Related IniRead, IniWrite, IniReadSection, IniReadSec tionNames, IniRenameSec tion, IniWriteSection Example
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
The filename of the .ini file.
section
The section name in the .ini file.
key
The key name in the in the .ini file.
default
The default value to return if the requested key is not found.
Return Value Success:
Returns the requested key value.
Failure:
Returns the default string if requested key not found.
Remarks A standard ini file looks like: [SectionName] Key=Value Related IniDelete, IniWrite, FileReadLine, IniReadSection, IniReadSec tionNames, IniRenameSec tion, IniWriteSection Example
$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
The filename of the .ini file.
section
The section name in the .ini file.
Return Value Success:
Returns a 2 dimensional array where element[n][0] is the key and element[n][1] is the value.
Failure:
Sets @error=1 if unable to read the section (The INI file may not exist or the section may not exist)
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
$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
The filename of the .ini file.
Return Value Success:
Returns an array of all section names in the INI file.
Failure:
Sets @error on 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
$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
The filename of the .ini file.
section
The section name in the .ini file.
new section
The new section name.
flag
[optional] 0 (Default) - Fail if "new section" already exists. 1 - Overwrite "new section". This will erase any existing keys in "new section"
Return Value Success:
Non-zero.
Failure:
0 and may set @error if the section couldn't be overwritten (flag = 0 only).
Remarks A standard ini file looks like: [SectionName] Key=Value Related IniRead, IniDelete, IniWrite, IniReadSection, IniReadSec tionNames, IniWriteSection Example
$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
The filename of the .ini file.
section
The section name in the .ini file.
key
The key name in the in the .ini file.
value
The value to write/change.
Return Value Success:
Returns 1.
Failure:
Returns 0 if file is read-only.
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
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
The filename of the .ini file.
section
The section name in the .ini file.
data
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.
index
[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.
Return Value Success:
Returns 1.
Failure:
Returns 0. The function will set @error to 1 if the data format is invalid.
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
; 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
Description
Beep
Plays back a beep to the user.
PixelChec ksum
Generates a checksum for a region of pixels.
PixelGetColor
Returns a pixel color according to x,y pixel coordinates.
PixelSearch
Searches a rectangle of pixels for the pixel color provided.
SoundPlay
Play a sound file.
SoundSetWaveVolume
Sets the system wave volume by percent.
Function Reference
Beep Plays back a beep to the user. Beep ( [ Frequency [, Duration ]] ) Parameters Frequency
[optional] The frequency of the beep in hertz. Can be anywhere from 37 through 32,767 (0x25 through 0x7FFF). Default is 500 Hz.
Duration
[optional] The length of the beep in milliseconds. Default = 1000 ms.
Return Value Always returns 1 regardless of success. Remarks None. Related SoundPlay Example
; 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
left coordinate of rectangle.
top
top coordinate of rectangle.
right
right coordinate of rectangle.
bottom
bottom coordinate of rectangle.
step
[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.
hwnd
[optional] Window handle to be used.
mode
[optional] default 0 ADLER checksum, 1 CRC32 Checksum.
Return Value Success:
Returns the checksum value of the region.
Failure:
Returns 0.
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
; 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
The option to change. See Remarks.
param
[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:
Returns the value of the previous setting for the option.
Failure:
Sets @error to non-zero. Failure will occur if the parameters are invalid (such as an option that doesn't exist).
Remarks You may use Opt() as an alternative to AutoItSetOption(). Options are as follows:
Option
Param
CaretCoordMode
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
ExpandEnvStrings
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")
ExpandVarStrings
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)
GUICloseOnESC
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.
GUICoordMode
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.
GUIDataSeparatorChar
Define the character which delimits subitems in GUICtrlSetData. The default character is '|'.
GUIOnEventMode
Enable/disable OnEvent functions notifications. 0 = (default) disable. 1 = enable.
GUIResizeMode
Change default resizing for a control. 0 = (default) keep default control resizing. 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
The preselected date (always as "yyyy/mm/dd").
left
The left side of the control. If -1 is used then left will be computed according to GUICoordMode.
top
The top of the control. If -1 is used then top will be computed according to GUICoordMode.
width
[optional] The width of the control (default is the previously used width).
height
[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) : $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:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
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_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 in your script. Default resizing is $GUI_DOCKHEIGHT. Related GUICoordMode (Option), GUICtrlSetState, GUIGetMsg, GUICtrlRead Example
#include #include 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:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
Remarks This control can receive messages through a GUICtrlSendToDummy call. The control will "notify" as normal and the value sent with GUISendToDummy can be read with GUICtrlRead. Related GUICtrlSendToDummy, GUICtrlSetOnEvent, GUICtrlRead, GUICtrlSetData Example
#include 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
The text of the control.
left
The left side of the control. If -1 is used then left will be computed according to GUICoordMode.
top
The top of the control. If -1 is used then top will be computed according to GUICoordMode.
width
[optional] The width of the control (default is the previously used width).
height
[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
exStyle
[optional] Defines the extended style of the control. See Extended Style Table.
Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
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_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 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
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: Kåre 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
The left side of the control. If -1 is used then left will be computed according to GUICoordMode.
top
The top of the control. If -1 is used then top will be computed according to GUICoordMode.
width
[optional] The width of the control (default is the previously used width).
height
[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) : $SS_NOTIFY. Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
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
#include #include 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
The text of the control.
left
The left side of the control. If -1 is used then left will be computed according to GUICoordMode.
top
The top of the control. If -1 is used then top will be computed according to GUICoordMode.
width
[optional] The width of the control (default is the previously used width).
height
[optional] The height of the control (default is the previously used height).
style
[optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : none. forc ed styles : $WS_GROUP, $BS_GROUPBOX.
exStyle
[optional] Defines the extended style of the control. See Extended Style Table.
Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
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 in your script. Default resizing is $GUI_DOCKAUTO size and position will occur. Related GUICoordMode (Option), GUIStartGroup Example
#include 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
filename of the icon to be loaded.
ic onName
Icon name if the file contain multiple icon. Can be an ordinal name if negative number. Otherwise -1.
left
The left side of the control. If -1 is used then left will be computed according to GUICoordMode.
top
The top of the control. If -1 is used then top will be computed according to GUICoordMode.
width
[optional] The width of the control (default is 32).
height
[optional] The height of the control (default is 32). [optional] Defines the style of the control. See GUI Control Styles Appendix.
style
default ( -1) : $SS_NOTIFY forced styles : $WS_TABSTOP, $SS_ICON [optional] Defines the extended style of the control. See Extended Style Table.
exStyle Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
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 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
#include
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
The text of the control.
left
The left side of the control. If -1 is used then left will be computed according to GUICoordMode.
top
The top of the control. If -1 is used then top will be computed according to GUICoordMode.
width
[optional] The width of the control (default is the previously used width).
height
[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_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.
exStyle Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
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 in your script. Default resizing is $GUI_DOCKHEIGHT. Related GUICoordMode (Option), GUICtrlUpdate..., GUIGetMsg, GUICtrlRead, GUICtrlCreateUpdown, GUICtrlSetLimit Example
#include 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
The text of the control.
left
The left side of the control. If -1 is used then left will be computed according to GUICoordMode.
top
The top of the control. If -1 is used then top will be computed according to GUICoordMode.
width
[optional] The width of the control (default text autofit in width).
height
[optional] The height of the control (default text autofit in height).
style
[optional] Defines the style of the control. See GUI Control Styles Appendix. default ( -1) : none. forced styles : $SS_NOTIFY, $SS_LEFT [optional] Defines the extended style of the control. See Extended Style Table.
exStyle Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
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 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
#include 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
The text of the control.
left
The left side of the control. If -1 is used then left will be computed according to GUICoordMode.
top
The top of the control. If -1 is used then top will be computed according to GUICoordMode.
width
[optional] The width of the control (default is the previously used width).
height
[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) : $LBS_SORT, $WS_BORDER, $WS_VSCROLL forced styles : $WS_TABSTOP, $LBS_NOTIFY [optional] Defines the extended style of the control. See Extended Style Table.
exStyle Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
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 in your script. Default resizing is $GUI_DOCKAUTO size and position will occur. Related GUICoordMode (Option), GUICtrlSetData, GUICtrlSetLimit, GUICtrlUpdate..., GUIGetMsg Example
#include 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
definition of columns heading. Each of them are separated with Opt("GUIDataSeparatorChar").
left
The left side of the control. If -1 is used then left will be computed according to GUICoordMode.
top
The top of the control. If -1 is used then top will be computed according to GUICoordMode.
width
[optional] The width of the control (default is the previously used width).
height
[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) : $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:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
Remarks 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 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 #include 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
subitemtext separated with Opt("GUIDataSeparatorChar").
listviewID
controlID of the ListView control holding the item.
Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
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
#include #include 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
The submenu text.
menuID
[optional] If defined, allows you to create a submenu in the referenced menu. If equal -1 it refers to first level menu.
menuentry
[optional] Allows you to define the entry number to be created. The entries are numbered starting at 0.
Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
Remarks To set or change information in the control see GUICtrlUpdate.... Related GUICtrlSetState, GUIGetMsg, GUICtrlCreateMenuItem, GUICtrlGetHandle, GUICtrlCreateContextMenu Example
#include #include 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
The text of the control.
menuID
Allows you to create a submenu in the referenced menu. If equal -1 it refers to the first level menu.
menuentry
[optional] Allows you to define the entry number to be created. The entries are numbered starting at 0.
menuradioitem
[optional] 0 (default) = create a normal menuitem, 1 = create a menuradioitem
Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
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
#include #include 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
The preselected date (always as "yyyy/mm/dd").
left
The left side of the control. If -1 is used then left will be computed according to GUICoordMode.
top
The top of the control. If -1 is used then top will be computed according to GUICoordMode.
width
[optional] The width of the control (default is the previously used width).
height
[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) : 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:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
Remarks To obtain the value of the control see GUICtrlRead. Default resizing is $GUI_DOCKSIZE. Related GUICoordMode (Option), GUIGetMsg, GUICtrlRead Example
#include 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
A variable pointing to a previously opened object
left
The left side of the control. If -1 is used then left will be computed according to GUICoordMode.
top
The top of the control. If -1 is used then top will be computed according to GUICoordMode.
width
[optional] The width of the control (default is the previously used width).
height
[optional] The height of the control (default is the previously used height).
Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
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
#include #include 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
filename of the picture to be loaded : supported types BMP, JPG, GIF(but not animated).
left
The left side of the control. If -1 is used then left will be computed according to GUICoordMode.
top
The top of the control. If -1 is used then top will be computed according to GUICoordMode.
width
[optional] The width of the control (default is the previously used width).
height
[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) : $SS_NOTIFY forced style : $SS_BITMAP [optional] Defines the extended style of the control. See Extended Style Table.
exStyle Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0 if picture cannot be created.
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 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.
Related GUICoordMode (Option), GUICtrlSetImage, GUICtrlUpdate..., GUIGetMsg Example
#include #include 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 #include #include #Include 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
The left side of the control. If -1 is used then left will be computed according to GUICoordMode.
top
The top of the control. If -1 is used then top will be computed according to GUICoordMode.
width
[optional] The width of the control (default is the previously used width).
height
[optional] The height of the control (default is the previously used height).
style
[optional] Defines the style of the control. See GUI Control Styles Appendix.
exStyle
[optional] Defines the extended style of the control. See Extended Style Table.
Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
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 in your script. Default resizing is $GUI_DOCKAUTO size and position will occur. Related GUICoordMode (Option), GUICtrlSetData, GUICtrlUpdate..., GUIGetMsg Example
#include #include 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
The text of the control.
left
The left side of the control. If -1 is used then left will be computed according to GUICoordMode.
top
The top of the control. If -1 is used then top will be computed according to GUICoordMode.
width
[optional] The width of the control (default text autofit in width).
height
[optional] The height of the control (default text autofit in height). [optional] Defines the style of the control. See GUI Control Styles Appendix.
style
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.
exStyle Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
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 in your script. Default resizing is $GUI_DOCKHEIGHT. Related GUICoordMode (Option), GUICtrlUpdate..., GUIGetMsg Example
#include 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
The left side of the control. If -1 is used then left will be computed according to GUICoordMode.
top
The top of the control. If -1 is used then top will be computed according to GUICoordMode.
width
[optional] The width of the control (default is the previously used width).
height
[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) : $TBS_AUTOTICKS [optional] Defines the extended style of the control. See Extended Style Table.
exStyle Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
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 in your script. Default resizing is $GUI_DOCKAUTO size and position will occur. Related GUICoordMode (Option), GUICtrlSetData, GUICtrlSetLimit, GUICtrlUpdate..., GUIGetMsg Example
#include 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
The left side of the control. If -1 is used then left will be computed according to GUICoordMode.
top
The top of the control. If -1 is used then top will be computed according to GUICoordMode.
width
[optional] The width of the control (default is the previously used width).
height
[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) : none. forced styles : $WS_TABSTOP, $WS_CLIPSIBLINGS [optional] Defines the extended style of the control. See Extended Style Table.
exStyle Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
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 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
#include 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 The text of the control.
text Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
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
#include 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
The left side of the control. If -1 is used then left will be computed according to GUICoordMode.
top
The top of the control. If -1 is used then top will be computed according to GUICoordMode.
width
[optional] The width of the control (default is the previously used width).
height
[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
exStyle
[optional] Defines the extended style of the control. See Extended Style Table.
Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
Remarks 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 in your script. Related GUICtrlCreateTreeViewItem, GUICoordMode (Option), GUICtrlUpdate..., GUIGetMsg, GUICtrlRead Example
#include #include #include #include
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
The text of the control.
treeviewID
treeview identifier as return by treeview or treeviewitem creation if subtree is created.
Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
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
#include #include #include #include
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
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.
style
default (-1) : $UDS_ALIGNRIGHT. forc ed style : $UDS_SETBUDDYINT and $UDS_ALIGNRIGHT if no align defined.
Return Value Success:
Returns the identifier (controlID) of the new control.
Failure:
Returns 0.
Remarks To use the values specified above you must #include 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
#include #include 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 The control identifier (controlID) as returned by a GUICtrlCreate... function.
controlID Return Value Success:
Returns 1.
Failure:
Returns 0.
Remarks For context menu controls see GUICtrlCreateContextMenu remarks. Related GUICreate, GUICtrlCreate..., GUICtrlCreateContextMenu Example
#include 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
Sets the background color of a control.
GUICtrlSetColor
Sets the text color of a control.
GUICtrlSetCursor
Sets the mouse cursor icon for a particular control.
GUICtrlSetData
Modifies the data for a control.
GUICtrlSetDefBkColor
Sets the default background color of all the controls of the GUI window.
GUICtrlSetDefColor
Sets the default text color of all the controls of the GUI window.
GUICtrlSetFont
Sets the font for a control.
GUICtrlSetGraphic
Modifies the data for a control.
GUICtrlSetImage
Sets the bitmap or icon image to use for a control.
GUICtrlSetLimit
Limits the number of characters/pixels for a control.
GUICtrlSetOnEvent
Defines a user-defined function to be called when a control is clicked.
GUICtrlSetPos
Changes the position of a control within the GUI window.
GUICtrlSetResizing
Defines the resizing method used by a control.
GUICtrlSetState
Changes the state of a control.
GUICtrlSetStyle
Changes the style of a control.
GUICtrlSetTip
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
The listview controlID for which the user function should proceed.
function
The name of the user function to call when the sorting callback runs.
Return Value Success:
1
Failure:
0
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
Parameter
Meaning
1
controlID
The controlID of the listview control for which the callback function is used.
2
lParam1
The lParam value of the first item (by default the item controlID).
3
lParam2
The lParam value of the second item (by default the item controlID).
4
c olumn
The column that was clicked for sorting (the first column number is 0).
The following values have to be Returned to change the behaviour of the sorting callback: Return value
Meaning
-1
1st item should precede the 2nd.
0
No Change.
1
1st item should follow the 2nd.
See also examples for sorting with selfcreated GUI listview items. Related GUICtrlCreateListView Example
#include
#include 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
$stLvi = DllStructCreate("uint;int;int;uint;uint;ptr;int;int;int;int")
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));
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:
Returns 1.
Failure:
Returns 0.
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
#include 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
The control identifier (controlID) as returned by a GUICtrlCreate... function.
textcolor
The RGB color to use.
Return Value Success:
Returns 1.
Failure:
Returns 0.
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
#include 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
The control identifier (controlID) as returned by a GUICtrlCreate... function.
c ursorID
cursor ID as used by Windows SetCursor API (use -1 for the default mouse cursor for the control)
Return Value Success:
Returns 1.
Failure:
Returns 0.
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 cursor. Related GUISetCursor Example
#include 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.
data
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.
default
[optional] Combo, List: The default value. Edit, Input: If non-empty (""), the string is inserted at the current insertion point (caret).
Return Value Success:
Returns 1.
Failure:
Returns 0. Returns -1 in case of invalid data
Remarks 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 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
Default background color for all controls.
winhandle
[optional] Windows handle as returned by GUICreate (default is the previously used window).
Return Value Success:
Returns 1.
Failure:
Returns 0.
Remarks None Related GUICreate, GUICtrlSetDefColor, GUICtrlSetBkColor Example
#include 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
Default text color for all controls.
winhandle
[optional] Windows handle as returned by GUICreate (default is the previously used window).
Return Value Success:
Returns 1.
Failure:
Returns 0.
Remarks None Related GUICreate, GUICtrlSetDefBkColor, GUICtrlSetColor Example
#include 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
The control identifier (controlID) as returned by a GUICtrlCreate... function.
size
Fontsize (default is 8.5).
weight
[optional] Font weight (default 400 = normal).
attribute
[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).
fontname
[optional] The name of the font to use.
quality
[optional] Font quality to select (default is PROOF_QUALITY=2).
Return Value Success:
Returns 1.
Failure:
Returns 0.
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
#include 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
The control identifier (controlID) as returned by a GUICtrlCreateGraphic function.
type
type of drawing : dot, line, bezier, rect, ellipse, pie.
par1...par6
See the Graphic Type table below.
Return Value Success:
Returns 1.
Failure:
Returns 0. Returns -1 in case of invalid data
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
Parameters
result
$GUI_GR_COLOR
Color [,BkColor]
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.
$GUI_GR_MOVE
x,y
Move the current position without drawing.
$GUI_GR_DOT
x,y
Draw a point(smallest square around the point), the next drawing will start from previous position.
$GUI_GR_PIXEL
x,y
Draw a pixel, the next drawing will start from previous position.
$GUI_GR_LINE
x,y
Draw a line.
$GUI_GR_BEZIER
x,y,x1,y1,x2,y2 Draw a bezier curve with 2 control points.
$GUI_GR_RECT
x,y,w,h
Draw a rectangle. If w=h it will be a square.
$GUI_GR_ELLIPSE
x,y,w,h
Draw an ellipse. If w=h it will be a circle.
$GUI_GR_PIE
x,y,r,sa,wa
Draw a pie radius=r startangle=sa sweepangle=wa. Angles are in degrees.
$GUI_GR_CLOSE
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.
$GUI_GR_REFRESH
to force refresh after dynamic update of graphics.
$GUI_GR_HINT
to display control point and end point of bezier/line curve.
$GUI_GR_PENSIZE
n
set pensize for the next drawings. It has to be defined before $GUI_GR_COLOR to be taken in account.
$GUI_GR_NOBKCOLOR
is a dummy BkColor to force closed drawing not to be filled. Just line drawings.
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 #include 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,
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)
0xff0000) 30, 270) 0xffffff) -60, 90)
$a[2] = GUICtrlCreateGraphic(220, 10, 100, 100)
GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1, GUICtrlSetGraphic(-1,
$a[3] = GUICtrlCreateGraphic(220, 110, 100, 100) GUICtrlSetBkColor(-1, 0xf08080) GUICtrlSetColor(-1, 0xff) GUICtrlSetGraphic(-1, $GUI_GR_HINT, 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)
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,
$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,
GUISetState() EndFunc ;==>CreateChild
$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)
$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
Function Reference
GUICtrlSetImage Sets the bitmap or icon image to use for a control. GUICtrlSetImage ( controlID, filename [, iconname [, icontype]] ) Parameters controlID
The control identifier (controlID) as returned by a GUICtrlCreate... function.
filename
The filename containing the picture to be display on the control.
ic onname
[optional] Icon name if the file contain multiple icon. Can be an ordinal name if negative number. Otherwise -1.
icontype
[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.
Return Value Success:
Returns 1.
Failure:
Returns 0.
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
#include #include 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
The control identifier (controlID) as returned by a GUICtrlCreate... function.
max
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.
min
[optional] For Slider and UpDown controls you can specify a min value. Default = 0
Return Value Success:
Returns 1.
Failure:
Returns 0.
Remarks None. Related GUICtrlCreateList, GUICtrlCreateInput, GUICtrlCreateEdit, GUICtrlCreateSlider, GUICtrlCreateUpdown Example
#include 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
The control identifier (controlID) as returned by a GUICtrlCreate... function.
function
The name of the user function to call.
Return Value Success:
Returns 1.
Failure:
Returns 0,
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_CTRLHANDLE. If the function is an empty string "" the previous user-defined is disabled. Related GUICtrlCreate..., GUIGetMsg, GUIOnEventMode (Option), GUISetOnEvent, GUICtrlCreateDummy, GUICtrlSendToDummy Example
#include 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
The control identifier (controlID) as returned by a GUICtrlCreate... function.
left
The left side of the control.
top
The top of the control.
width
[optional] The width of the control.
height
[optional] The height of the control .
Return Value Success:
Returns 1.
Failure:
Returns 0.
Remarks None. Related GUICtrlCreate... Example
#include 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
The control identifier (controlID) as returned by a GUICtrlCreate... function.
resizing
See the Docking Values table below for values that can be used (add together multiple values if required).
Return Value Success:
Returns 1.
Failure:
Returns 0.
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
Value No displacement of
$GUI_DOCKAUT O
1
resize and reposition according to new window size
$GUI_DOCKLEFT
2
Left side
$GUI_DOCKRIGHT
4
Right side
$GUI_DOCKHCENT ER
8
Position will not move relative to horizontal center
$GUI_DOCKTOP
32
Top side
$GUI_DOCKBOTTOM
64
Bottom side
$GUI_DOCKVCENT ER
128
Position will not move relative to vertical center
$GUI_DOCKWIDT H
256
Width will not change
$GUI_DOCKHEIGHT
512
Height will not change Composite resizing
$GUI_DOCKSIZE
768
(256+512) Size will not change
$GUI_DOCKMENUBAR
544
(512+32) so the control will stay at the top of window with no change in Height
$GUI_DOCKSTATEBAR 576
(512+64) so the control stay at the bottom of the window with no change in Height
$GUI_DOCKALL
802
(2+32+256+512) so the c ontrol will not move during resizing
$GUI_DOCKBORDERS
102
(2+4+32+64) so the control will grow as the window
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 #include #include 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
The control identifier (controlID) as returned by a GUICtrlCreate... function.
state
See the State table below.
Return Value Success:
Returns 1.
Failure:
Returns 0.
Remarks State table State
Comments
No Change
0
$GUI_UNCHECKED
Radio, Checkbox or ListViewItem will be unchecked.
$GUI_CHECKED
Radio, Checkbox or ListViewItem will be checked.
$GUI_INDETERMINATE
Checkbox having the tristate attribute will be greyed.
$GUI_AVISTART
Avi control will start playing.
$GUI_AVISTOP
Avi control will stop playing.
$GUI_AVICLOSE
Avi control will stop playing and release resource.
$GUI_DROPACCEPTED
Control will accept drop action : from file or from a drag of another control. See remarks.
$GUI_NODROPACCEPTED Control will not accept drop action. $GUI_SHOW
Control will be visible. On Tabitem control will select the first tab to be displayed.
$GUI_HIDE
Control will not be visible.
$GUI_ENABLE
Control will be enabled.
$GUI_DISABLE
Control will be greyed out.
$GUI_FOCUS
Control will be given input/selected focus.
$GUI_NOFOCUS
Listview control will loose focus.
$GUI_DEFBUTTON
Control will be set as the default button on the window. See remark about TreeviewItems.
$GUI_EXPAND
TreeViewItem will expand it's child items.
$GUI_ONTOP
Control will be have the ontop attribute for the window (zOrdering).
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 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
The control identifier (controlID) as returned by a GUICtrlCreate... function.
style
Defines the style of the control. See GUI Control Styles Appendix.
exStyle
[optional] Defines the extended Style of the control. See Extended Style Table.
Return Value Success:
Returns 1.
Failure:
Returns 0.
Remarks Some styles cannot be changed dynamically, check MSDN documentation. $CBS_UPPERCASE combo style is one example. Related GUICtrlCreate... Example
#include #include 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
The control identifier (controlID) as returned by a GUICtrlCreate... function.
tiptext
Tip text that will be displayed when the mouse is hovered over the control.
title
[optional] The title for the tooltip Requires IE5+
icon
[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
options
[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.
Return Value Success:
Returns 1.
Failure:
Returns 0.
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
#include 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
Description
GUISetAccelerators
Sets the accelerator table to be used in a GUI window.
GUISetBkColor
Sets the background color of the GUI window.
GUISetCoord
Sets absolute coordinates for the next control.
GUISetCursor
Sets the mouse cursor icon for a GUI window.
GUISetFont
Sets the default font for a GUI window.
GUISetHelp
Sets an executable file that will be run when F1 is pressed.
GUISetIcon
Sets the icon used in a GUI window.
GUISetOnEvent
Defines a user function to be called when a system button is clicked.
GUISetState
Changes the state of a GUI window.
GUISetStyle
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
A 2 dimensional array holding the accelerator table (See remarks).
winhandle
[optional] Windows handle as returned by GUICreate (default is the previously used window).
Return Value Success:
Returns 1.
Failure:
Returns 0.
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
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 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
Background color of the dialog box.
winhandle
[optional] Windows handle as returned by GUICreate (default is the previously used window).
Return Value Success:
Returns 1.
Failure:
Returns 0.
Remarks None Related GUICreate Example
#include 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
The left side of the control.
top
The top of the control.
width
[optional] The width of the control (default is the previously used width).
height
[optional] The height of the control (default is the previously used height).
winhandle
[optional] Windows handle as returned by GUICreate (default is the previously used).
Return Value Success:
Returns 1.
Failure:
Returns 0.
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
#include 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
[optional] Cursor Id (See Remarks).
override
[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.
winhandle
[optional] Windows handle as returned by GUICreate (default is the previously used Window).
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 cursor. Related GUICtrlSetCursor Example
#include 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
Fontsize (default is 8.5).
weight
[optional] Font weight (default 400 = normal).
attribute
[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).
fontname
[optional] Font to use. (OS default GUI font is used if the font is "" or is not found).
winhandle
[optional] Windows handle as returned by GUICreate (default is the previously used window).
quality
[optional] Font quality to select (default is PROOF_QUALITY=2).
Return Value Success:
Returns 1.
Failure:
Returns 0.
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
#include 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
file that will be run if F1 is pressed when the GUI is active.
winhandle
[optional] Windows handle as returned by GUICreate (default is the previously used window).
Return Value Success:
Returns 1.
Failure:
Returns 0.
Remarks None. Related GUICreate Example
#include 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
used to display the icon in the title area.
ic onID
[optional] The ID of the icon in the iconfile. (Default is -1).
winhandle
[optional] Windows handle as returned by GUICreate (default is the previously used window).
Return Value Success:
Returns 1.
Failure:
Returns 0.
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
#include 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
See the Special ID table below.
function
The name of the user function to call.
winhandle
[optional] Windows handle as returned by GUICreate (default is the previously used window).
Return Value Success:
Returns 1.
Failure:
Returns 0.
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
Comments
$GUI_EVENT_CLOSE
dialog box being closed (either by defined button or system menu).
$GUI_EVENT_MINIMIZE
dialog box minimized with Windows title bar button.
$GUI_EVENT_RESTORE
dialog box restored by click on task bar icon.
$GUI_EVENT_MAXIMIZE
dialog box maximized with Windows title bar button.
$GUI_EVENT_MOUSEMOVE
the mouse cursor has moved.
$GUI_EVENT_PRIMARYDOWN
the primary mouse button was pressed.
$GUI_EVENT_PRIMARYUP
the primary mouse button was released.
$GUI_EVENT_SECONDARYDOWN the secondary mouse button was pressed. $GUI_EVENT_SECONDARYUP
the secondary mouse button was released.
$GUI_EVENT_RESIZED
dialog box has been resized.
$GUI_EVENT _DROPPED
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.
Related GUIOnEventMode (Option), GUIEventOptions (Option), GUICtrlSetOnEvent Example
#include 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
flag
[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.
winhandle
[optional] Windows handle as returned by GUICreate (default is the previously used window).
Return Value Success:
Returns 1.
Failure:
Returns 0.
Remarks 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 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
[optional] defines the extended style of the window. See the Extended Style Table below. -1 is the default. Use -1 to leave it unchanged.
winhandle
[optional] Windows handle as returned by GUICreate (default is the previously used window).
Return Value Success:
Returns 1.
Failure:
Returns 0.
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
#include #include 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 [optional] Windows handle as returned by GUICreate (default is the previous used).
winhandle Return Value Success:
Returns 1.
Failure:
Returns 0.
Remarks None. Related GUICreate, GUISwitch Example
#include 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 Control identifier as returned by GUICtrlCreate...
controlID Return Value Success:
Returns the handle of the given control ID.
Failure:
Returns 0.
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
#include 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 [optional] The control identifier (controlID) as returned by a GUICtrlCreate... function.
controlID Return Value Success:
Returns the state. See GUICtrlSetState for values.
Failure:
Returns -1 if control is not defined.
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
#include 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
The control identifier (controlID) as returned by a GUICtrlCreate... function.
advanced
[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).
Return Value Success:
Returns depending the control (see below).
Failure:
Returns 0.
Type
Value
Checkbox, Radio state of the button. See State table Combo, List
The value selected
Input, Edit
The text entered
Button
The display text
Date
The selected date
Progress
Current percentage
Slider
Current value
Tab
The number or the controlID of the tabitem selected depending of the advanced parameter value.
Menu, MenuItem
State of the menu/item. See State table
TreeView
Control identifier (controlID) of the selected TreeViewItem
TreeViewItem
State of the TreeViewItem
ListView
Control identifier (controlID) of the selected ListViewItem. 0 means no item is selected
Dummy
The value set by GUICtrlSendToDummy or GUICtrlSetData
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!
Type
Additional Value
Checkbox, Radio
The text of the control.
Menu, MenuItem
The text of the control.
TreeView
The text of the current selected TreeViewItem.
TreeViewItem
The text of the TreeViewItem.
ListViewItem
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 controls 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, GUICtrlSendToDummy, GUICtrlSendMsg Example
#include 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
The control identifier (controlID) as returned by a GUICtrlCreate... function.
msg
type of message to be send to the control as defined in the Windows controls documentation.
wParam
[optional] An integer first param to be send to the control.
lParamType
[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.
Return Value Success:
Returns the value returned by the SendMessage Windows API.
Failure:
Returns 0.
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
#include #include 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
The control identifier (controlID) as returned by a GUICtrlCreate... function.
msg
type of message to be send to the control as defined in the Windows control documentation.
wParam
The first param to send to the control.
lParam
The second param to send to the control.
Return Value Success:
Returns the value returned by the SendMessage Windows API.
Failure:
Returns 0.
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
#include #include 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
The control identifier (controlID) as returned by GUICtrlCreateDummy
state
[optional] value that can be retrieved later on by GUICtrlRead
Return Value Success:
Returns 1.
Failure:
Returns 0.
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
#include 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 [optional] The handle of the window to use. If omitted the "current" window will be used.
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:
0 and set @error to 1
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
#include 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
[optional] return extended information in an array. 0 = (default) Returns a single event. 1 = returns an array containing the event and extended information.
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.
Event ID
the ID of the control sending the message
0
No event
$GUI_EVENT_CLOSE
dialog box being closed (either by defined button or system menu).
$GUI_EVENT_MINIMIZE
dialog box minimized with Windows title bar button.
$GUI_EVENT_RESTORE
dialog box restored by click on task bar icon.
$GUI_EVENT_MAXIMIZE
dialog box maximized with Windows title bar button.
$GUI_EVENT_MOUSEMOVE
the mouse cursor has moved.
$GUI_EVENT_PRIMARYDOWN
the primary mouse button was pressed.
$GUI_EVENT_PRIMARYUP
the primary mouse button was released.
$GUI_EVENT_SECONDARYDOWN the secondary mouse button was pressed. $GUI_EVENT_SECONDARYUP
the secondary mouse button was released.
$GUI_EVENT_RESIZED
dialog box has been resized.
$GUI_EVENT _DROPPED
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.
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 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 Example
Function Reference
GUIGetStyle Retrieves the styles of a GUI window. GUIGetStyle ( [ winhandle] ) Parameters [optional] Windows handle as returned by GUICreate (default is the previously used window).
winhandle Return Value Success:
returns a two-element array that containing the styles information: $array[0] = Style $array[1] = ExStyle
Failure:
Returns 0.
Remarks Be carefull Style changes after GUISetState(). Related GUICreate, GUISetStyle Example
#include #include 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
A Windows Message ID (see Appendix: Windows Message Codes).
function
The name of the user function to call when the message appears or an empty string "" to unregister a message.
Return Value Success:
1
Failure:
0
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
Parameter
Meaning
1
hWnd
The Window handle of the GUI in which the message appears.
2
Msg
The Windows message ID.
3
wParam
The first message parameter as hex value.
4
lParam
The second message parameter as hex value.
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 #include #include 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 [optional] Windows handle as returned by GUICreate (default is the previously used window).
winhandle Return Value Success:
Returns 1.
Failure:
Returns 0.
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
#include 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
The handle of the window to switch to.
tabitemID
[optional] controlID of the tabitem control to be selected.
Return Value Success:
Returns the handle of the previously current.
Failure:
Returns a NULL handle.
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
#include 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
Description
HotKeySet
Sets a hotkey that calls a user function.
Send
Sends simulated keystrokes to the active window.
SendKeepActive
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
The key combination to use as the hotkey. Same format as Send().
function
[optional] The name of the function to call when the key is pressed. Not specifying this parameter will unset a previous hotkey.
Return Value Success:
Returns 1.
Failure:
Returns 0.
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
It is reserved by Windows
F12
It is also reserved by Windows, according to its API.
NumPad's Enter Key
Instead, use {Enter} which captures both Enter keys on the keyboard.
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
These are the modifier keys themselves!
Other
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
The sequence of keys to send.
flag
[optional] Changes how "keys" is processed: flag = 0 (default), Text contains special characters like + and ! to indicate SHIFT and ALT key-presses. flag = 1, keys are sent raw.
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)
Resulting Keypress
{!}
!
{#}
#
{+}
+
{^}
^
{{}
{
{}}
}
{SPACE}
SPACE
{ENTER}
ENTER key on the main keyboard
{ALT}
ALT
{BACKSPACE} or {BS}
BACKSPACE
{DELETE} or {DEL}
DELETE
{UP}
Up arrow
{DOWN}
Down arrow
{LEFT}
Left arrow
{RIGHT }
Right arrow
{HOME}
HOME
{END}
END
{ESCAPE} or {ESC}
ESCAPE
{INSERT} or {INS}
INS
{PGUP}
PageUp
{PGDN}
PageDown
{F1} - {F12}
Function keys
{TAB}
TAB
{PRINTSCREEN}
Print Screen key
{LWIN}
Left Windows key
{RWIN}
Right Windows key
{NUMLOCK on}
NUMLOCK (on/off/toggle)
{CAPSLOCK off}
CAPSLOCK (on/off/toggle)
{SCROLLLOCK toggle}
SCROLLLOCK (on/off/toggle)
{BREAK}
for Ctrl+Break proc essing
{PAUSE}
PAUSE
{NUMPAD0} - {NUMPAD9}
Numpad digits
{NUMPADMULT}
Numpad Multiply
{NUMPADADD}
Numpad Add
{NUMPADSUB}
Numpad Subtract
{NUMPADDIV}
Numpad Divide
{NUMPADDOT}
Numpad period
{NUMPADENTER}
Enter key on the numpad
{APPSKEY}
Windows App key
{LALT}
Left ALT key
{RALT}
Right ALT key
{LCTRL}
Left CTRL key
{RCTRL}
Right CTRL key
{LSHIFT}
Left Shift key
{RSHIFT}
Right Shift key
{SLEEP}
Computer SLEEP key
{ALTDOWN}
Holds the ALT key down until {ALTUP} is sent
{SHIFTDOWN}
Holds the SHIFT key down until {SHIFTUP} is sent
{CTRLDOWN}
Holds the CTRL key down until {CTRLUP} is sent
{LWINDOWN}
Holds the left Windows key down until {LWINUP} is sent
{RWINDOWN}
Holds the right Windows key down until {RWINUP} is sent
{ASC nnnn}
Send the ALT+nnnn key combination
{BROWSER_BACK}
2000/XP Only: Select the browser "back" button
{BROWSER_FORWARD}
2000/XP Only: Select the browser "forward" button
{BROWSER_REFRESH}
2000/XP Only: Select the browser "refresh" button
{BROWSER_STOP}
2000/XP Only: Select the browser "stop" button
{BROWSER_SEARCH}
2000/XP Only: Select the browser "search" button
{BROWSER_FAVORITES}
2000/XP Only: Select the browser "favorites" button
{BROWSER_HOME}
2000/XP Only: Launch the browser and go to the home page
{VOLUME_MUTE}
2000/XP Only: Mute the volume
{VOLUME_DOWN}
2000/XP Only: Reduce the volume
{VOLUME_UP}
2000/XP Only: Increase the volume
{MEDIA_NEXT}
2000/XP Only: Select next track in media player
{MEDIA_PREV}
2000/XP Only: Select previous track in media player
{MEDIA_STOP}
2000/XP Only: Stop media player
{MEDIA_PLAY_PAUSE}
2000/XP Only: Play/pause media player
{LAUNCH_MAIL}
2000/XP Only: Launch the email application
{LAUNCH_MEDIA}
2000/XP Only: Launch media player
{LAUNCH_APP1}
2000/XP Only: Launch user app1
{LAUNCH_APP2}
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}")
Navigate to next control (button, checkbox, etc)
Send("+{TAB}")
Navigate to previous control.
Send("^{TAB}")
Navigate to next WindowTab (on a Tabbed dialog window)
Send("^+{TAB}")
Navigate to previous WindowTab.
Send("{SPACE}")
Can be used to toggle a checkbox or click a button.
Send("{+}")
Usually checks a checkbox (if it's a "real" checkbox.)
Send("{-}")
Usually unchecks a checkbox.
Send("{NumPadMult}")
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}")
Move down a menu.
Send("{UP}")
Move up a menu.
Send("{LEFT}")
Move leftward to new menu or expand a submenu.
Send("{RIGHT }")
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
The title of the window to activate. See Title special definition. Use a blank title to disable the function.
text
[optional] The text of the window.
Return Value Success:
Returns 1.
Failure:
Returns 0 if window is not found.
Remarks Attempts to reset the active window in between each simulated keystroke from Send(). Related Send Example
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
Description
Abs
Calculates the absolute value of a number.
ACos
Calculates the arcCosine of a number.
ASin
Calculates the arcsine of a number.
ATan
Calculates the arctangent of a number.
BitAND
Performs a bitwise AND operation.
BitNOT
Performs a bitwise NOT operation.
BitOR
Performs a bitwise OR operation.
BitRotate
Performs a bit shifting operation, with rotation.
BitShift
Performs a bit shifting operation.
BitXOR
Performs a bitwise exclusive OR (XOR) operation.
Cos
Calculates the cosine of a number.
Ceiling
Returns a number rounded up to the next integer.
Exp
Calculates e to the power of a number.
Floor
Returns a number rounded down to the closest integer.
Log
Calculates the natural logarithm of a number.
Mod
Performs the modulus operation.
Random
Generates a pseudo-random float-type number.
Round
Returns a number rounded to a specified number of decimal places.
Sin
Calculates the sine of a number.
Sqrt
Calculates the square-root of a number.
SRandom
Set Seed for random number generation.
Tan
Calculates the tangent of a number.
Function Reference
Abs Calculates the absolute value of a number. Abs ( expression ) Parameters expression
Any valid numeric expression.
Return Value Returns absolute value of expression. Remarks A string has a value of zero. Related None. Example
$var = Abs(-123.45) ;value is 123.45
Function Reference
ACos Calculates the arcCosine of a number. ACos ( expression ) Parameters expression
Any value between -1 and 1 inclusive.
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
$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
Any value between -1 and 1 (inclusive).
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
$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
Any valid numeric 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
$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
The first number.
value2
The second number.
value n
[optional] The nth number - up to 255 values can be specified.
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
$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
The number to operate on.
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
$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
The first number.
value2
The second number.
value n
[optional] The nth number - up to 255 values can be specified.
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
$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
The number to be operate on.
shift
Number of bits to rotate to the left (negative numbers shift right). If not given, the default is 1.
size
[optional] A string that determines the rotation size, the default is (16 bits). See below.
Size parameter : "B"
rotate bits within the low-order byte (8 bits).
"W"
rotate bits within the low-order word (16 bits).
"D"
rotate bits within the entire double-word (32 bits).
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
$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
The number to be shifted.
shift
Number of bits to shift to the right (negative numbers shift left).
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
$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
The first number.
value2
The second number.
value n
[optional] The nth number - up to 255 values can be specified.
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
$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
View more...
Comments