All notes
Autoi

Reference

AutoItScript: Send.

Variables

autoitScript: Dim.


Global | Local [Const] $variable [ = initializer ]
Global | Local [Const] $aArray[subscript 1]...[subscript n] [ = initializer ]

Once created, you cannot change the value of a constant.

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.

Function


 #include <Constants.au3>

Local $iNumber = 10
Local $iDoubled = 0

For $i = 1 To 10
    $iDoubled = MyDouble($iNumber)
    MsgBox($MB_OK, "", $iNumber & " doubled is " & $iDoubled)
    $iNumber = $iDoubled
Next
Exit

Func MyDouble($iValue)
    $iValue = $iValue * 2
    Return $iValue
EndFunc   ;==>MyDouble

Loop statements

For


For <Variable> In <expression>
    statements
    ...
Next 

Keywords

include

autoItScript: include.


#include "[path\]filename"
#include <filename>

If "..." is used, the filename is taken to be relative to the current script.

If <...> is used the filename is taken to be relative to include library directory (usually C:\Program Files\AutoIt3\Include). The include library contains many pre-written user-functions for you to use.

include-once

autoItScript: include once.

when writing a script intended for use as an include file, add #include-once to prevent that file from being included more than once.

Note that the #include-once line must be placed at the top of the script and before any other #include lines.

It is not recommended to add a #include-once line to scripts which are not intended to be used as include files within other scripts.


#include-once
#include <MsgBoxConstants.au3>

GUI


MsgBox(flag title text timeout) 

Function Reference

String related

StringRegExp

StringRegExp.

Check if a string fits a given regular expression pattern.

StringRegExp ( "test", "pattern" [, flag = 0 [, offset = 1]] )

Flag and values:

$STR_REGEXPMATCH (0) 	Returns 1 (match) or 0 (no match). (Default).
$STR_REGEXPARRAYMATCH (1) 	Return array of matches.
$STR_REGEXPARRAYFULLMATCH (2) 	Return array of matches including the full match (Perl / PHP style).
$STR_REGEXPARRAYGLOBALMATCH (3) 	Return array of global matches.
$STR_REGEXPARRAYGLOBALFULLMATCH (4) 	Return an array of arrays containing global matches including the full match (Perl / PHP style).
Constants are defined in StringConstants.au3.

File IO related

FileOpen

Opens a file for reading or writing.


FileOpen ( "filename" [, mode = 0] )

Parameters:
filename 	Filename of the file to open.
mode 	[optional] Mode to open the file in.
Can be a combination of the following:
    $FO_READ (0) = Read mode (default)
    $FO_APPEND (1) = Write mode (append to end of file)
    $FO_OVERWRITE (2) = Write mode (erase previous contents)
    $FO_CREATEPATH (8) = Create directory structure if it doesn't exist (See Remarks).
    $FO_BINARY (16) = Force binary mode (See Remarks).
    $FO_UNICODE or $FO_UTF16_LE (32) = Use Unicode UTF16 Little Endian reading and writing mode.
    $FO_UTF16_BE (64) = Use Unicode UTF16 Big Endian reading and writing mode.
    $FO_UTF8 (128) = Use Unicode UTF8 (with BOM) reading and writing mode.
    $FO_UTF8_NOBOM (256) = Use Unicode UTF8 (without BOM) reading and writing mode.
    $FO_ANSI (512) = Use ANSI reading and writing mode.
    $FO_UTF16_LE_NOBOM (1024) = Use Unicode UTF16 Little Endian (without BOM) reading and writing mode.
    $FO_UTF16_BE_NOBOM (2048) = Use Unicode UTF16 Big Endian (without BOM) reading and writing mode.
    $FO_FULLFILE_DETECT (16384) = When opening for reading and no BOM is present, use the entire file to determine if it is UTF8 or UTF16. If this is not used then only the initial part of the file (up to 64KB) is checked for performance reasons.
The folder path must already exist (except using $FO_CREATEPATH mode - See Remarks).

_FileWriteFromArray

autoItScript.com: _FileWriteFromArray.

Writes an array to a specified file.


#include <File.au3>
_FileWriteFromArray ( $sFilePath, Const ByRef $aArray [, $iBase = Default [, $iUBound = Default [, $sDelimiter = "|"]]] )

Example.


#include <File.au3>

; List all the files in the current script directory.
Local $aScriptDir = _FileListToArray(@ScriptDir)

; Create a file in the users %TEMP% directory.
Local $sFilePath = @TempDir & "\Examples.txt"

; Write array to a file by passing the file name.
_FileWriteFromArray($sFilePath, $aScriptDir, 1)

; Display the file.
ShellExecute($sFilePath)

_FileListToArray

autoitScript.com: _FileListToArray.


#include <File.au3>
_FileListToArray ( $sFilePath [, $sFilter = "*" [, $iFlag = $FLTA_FILESFOLDERS [, $bReturnPath = False]]] )
wcfNote: The first item is the list length.

Success: 	A one-dimensional array.
    $aArray[0] = Number of Files\Folders returned
    $aArray[1] = 1st File\Folder
    $aArray[2] = 2nd File\Folder
    $aArray[3] = 3rd File\Folder
    $aArray[n] = nth File\Folder
$iFlag 	[optional] specifies whether to return files folders or both
    $FLTA_FILESFOLDERS (0) = (Default) Return both files and folders
    $FLTA_FILES (1) = Return files only
    $FLTA_FOLDERS (2) = Return Folders only
    Constants are defined in FileConstants.au3

#include <Array.au3>
#include <File.au3>
#include <MsgBoxConstants.au3>

Example()

Func Example()
    ; List all the files and folders in the desktop directory using the default parameters and return the full path.
    Local $aFileList = _FileListToArray(@DesktopDir, Default, Default, True)
    If @error = 1 Then
        MsgBox($MB_SYSTEMMODAL, "", "Path was invalid.")
        Exit
    EndIf
    If @error = 4 Then
        MsgBox($MB_SYSTEMMODAL, "", "No file(s) were found.")
        Exit
    EndIf
    ; Display the results returned by _FileListToArray.
    _ArrayDisplay($aFileList, "$aFileList")
EndFunc   ;==>Example

dllcall

Dynamically calls a function in a DLL.



DllCall ( "dll", "return type", "function" [, type1, param1 [, type n, param n]] )
; dll 	The filename of the DLL to use. e.g. "user32.dll". A handle obtained from DllOpen can also be used.

; If the function call fails then @error is set to non-zero.
; Otherwise an array is returned that contains the function return value and a copy of all the parameters (including parameters that the function may have modified when passed by reference).
; $return[0] = function return value
; $return[1] = param1
; $return[2] = param2
; ...
; $return[n] = paramn

; By default, AutoIt uses the 'stdcall' calling method. To use the 'cdecl' method place ':cdecl' after the return type.
DllCall("SQLite.dll", "int:cdecl", "sqlite3_open", "str", $sDatabase_Filename , "long*", 0).

;;; Example 1

; Calling the MessageBox API directly.
DllCall("user32.dll", "int", "MessageBox", _
        "hwnd", 0, _ ; Handle to the parent window
        "str", "Some text", _ ; The text of the message box
        "str", "Some title", _ ; The title of the message box
        "int", 0) ; Flags for the message box.

;;; Example 2

#include <MsgBoxConstants.au3>

; Calling a function that modifies parameters,
Local $iPID = Run("notepad")
Local $hWnd = WinWait("[CLASS:Notepad]", "", 2000)

If $hWnd = 0 Then
    ; Timeout occured.
    Exit MsgBox($MB_SYSTEMMODAL, Default, "Unable to start notepad!")
EndIf

Local $aResult = DllCall("user32.dll", "int", "GetWindowText", "hwnd", $hWnd, "str", "", "int", 32768)
MsgBox($MB_SYSTEMMODAL, Default, "Number of characters returned: " & $aResult[0])
MsgBox($MB_SYSTEMMODAL, Default, "Text (returned in parameter 2): '" & $aResult[2] & "'")

WinClose($hWnd)

Library

Array


#include <Array.au3>

Local $aArray[4][4]
For $i = 0 To 3
    For $j = 0 To 3
        $aArray[$i][$j] = $i & $j
    Next
Next
_ArrayDisplay($aArray, "Original")
Local $aExtract = _ArrayExtract($aArray, 1, 2, 2, 3)
_ArrayDisplay($aExtract, "Row 1-2 cols 2-3")

File IO

FileExists

FileRead

autoItScript: FileRead.


#include <FileConstants.au3>
#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>

Example()

Func Example()
    ; Create a constant variable in Local scope of the filepath that will be read/written to.
    Local Const $sFilePath = _WinAPI_GetTempFileName(@TempDir)

    ; Create a temporary file to read data from.
    If Not FileWrite($sFilePath, "This is an example of using FileRead.") Then
        MsgBox($MB_SYSTEMMODAL, "", "An error occurred whilst writing the temporary file.")
        Return False
    EndIf

    ; Open the file for reading and store the handle to a variable.
    Local $hFileOpen = FileOpen($sFilePath, $FO_READ)
    If $hFileOpen = -1 Then
        MsgBox($MB_SYSTEMMODAL, "", "An error occurred when reading the file.")
        Return False
    EndIf

    ; Read the contents of the file using the handle returned by FileOpen.
    Local $sFileRead = FileRead($hFileOpen)

    ; Close the handle returned by FileOpen.
    FileClose($hFileOpen)

    ; Display the contents of the file.
    MsgBox($MB_SYSTEMMODAL, "", "Contents of the file:" & @CRLF & $sFileRead)

    ; Delete the temporary file.
    FileDelete($sFilePath)
EndFunc   ;==>Example

Excel

autoItScript.com: excel rangeRead.


#include <Excel.au3>
_Excel_RangeRead ( $oWorkbook [, $vWorksheet = Default [, $vRange = Default [, $iReturn = 1 [, $bForceFunc = False]]]] )

#include <Array.au3>
#include <Excel.au3>
#include <MsgBoxConstants.au3>

; Create application object and open an example workbook
Local $oExcel = _Excel_Open()
If @error Then Exit MsgBox($MB_SYSTEMMODAL, "Excel UDF: _Excel_RangeRead Example", "Error creating the Excel application object." & @CRLF & "@error = " & @error & ", @extended = " & @extended)
Local $oWorkbook = _Excel_BookOpen($oExcel, @ScriptDir & "\Extras\_Excel1.xls")
If @error Then
    MsgBox($MB_SYSTEMMODAL, "Excel UDF: _Excel_RangeRead Example", "Error opening workbook '" & @ScriptDir & "\Extras\_Excel1.xls'." & @CRLF & "@error = " & @error & ", @extended = " & @extended)
    _Excel_Close($oExcel)
    Exit
EndIf

; *****************************************************************************
; Read the formulas of a cell range (all used cells in column A)
; *****************************************************************************
Local $aResult = _Excel_RangeRead($oWorkbook, Default, $oWorkbook.ActiveSheet.Usedrange.Columns("A:A"), 2)
If @error Then Exit MsgBox($MB_SYSTEMMODAL, "Excel UDF: _Excel_RangeRead Example 3", "Error reading from workbook." & @CRLF & "@error = " & @error & ", @extended = " & @extended)
MsgBox($MB_SYSTEMMODAL, "Excel UDF: _Excel_RangeRead Example 3", "Data successfully read." & @CRLF & "Please click 'OK' to display all formulas in column A.")
_ArrayDisplay($aResult, "Excel UDF: _Excel_RangeRead Example 3 - Formulas in column A")

FAQ

Cant run snipping tool

SO: snipping tool to run with autoit.

Windows 7 (as well as Vista I believe) implements what is called WoW64 Filesystem Redirection.


; This will not work
; Run("C:\Windows\System32\SnippingTool.exe")

; Call the executable withing the boundaries of the WoW64 Filesystem Redirection
Run("C:\Windows\explorer.exe C:\Windows\system32\SnippingTool.exe")

Set input method

在编写钩子的时候,尽量多使用ControlSend。但某些情况下需要使用 send,可以先切换输入法为英文再使用send。

"08040804"为:英语美式键盘,如需切换其它输入法,修改此处即可!

其它编码(如需其它编码,可查询注册表):

Set input method to english:



$hWnd = WinGetHandle("[ACTIVE]"); $hWnd 为目标窗口句柄,这里设置的是当前活动窗口
$ret = DllCall("user32.dll", "long", "LoadKeyboardLayout", "str", "08040804", "int", 1 + 0) ; Obtain the keyboard layout.

DllCall("user32.dll", "ptr", "SendMessage", "hwnd", $hWnd, "int", 0x50, "int", 1, "int", $ret[0])        
Send('nh')

; 0x50 indicates a request to change input lang.
; #DeFine WM_INPUTLANGCHANGEREQUEST 0x50

HKL WINAPI LoadKeyboardLayout(
  _In_ LPCTSTR pwszKLID,
  _In_ UINT    Flags
);

LRESULT WINAPI SendMessage(
  _In_ HWND   hWnd,
  _In_ UINT   Msg,
  _In_ WPARAM wParam,
  _In_ LPARAM lParam
);

Shortcuts to stop macro

A simple solution is to create a HotKey then have the command inside the function to be Exit. See autoitScript.com: stop, abort, quit and end macro hotkey.


#include <Misc.au3>

HotKeySet("{F1}", "ExitIt") ; HotKey set to F1

Func ExitIt()
    Exit ; Code for action here, in this case to exit the script (i.e. close the program)
EndFunc