Saturday 1 March 2008

một vài ứng dụng nho nhỏ

Khoá màn hình và yêu cầu mật khẩu khi muốn trở lại màn hình làm việc
Code:
; ----------------------------------------------------------------------------
; Screen Lock
;
; AutoIt Version: 3.2.0.1
; Author: Hallman \ CWorks
;
; HotKeys
; F9 = Close program
; F10 = Change password
; F11 = Enable ScreenLock
;
; ----------------------------------------------------------------------------

#include
#include
Opt("TrayMenuMode",1)
Dim $Atempts = 0
Dim $Lock = 0
Dim $PassInput = ""
Dim $Label
Dim $ScreenyWindow = ""
Dim $PassWindow = ""
$Show_Controls_Timer = TimerInit()
$Controls_Shown = 0


$PassWord = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Andy\ScreenLock", "Password")

If $PassWord <> "" Then
$PassWord = _StringEncrypt(0, $PassWord, "4471")
Else
Pass()
EndIf

Lock()

While 1
$msg = GUIGetMsg()
Select
Case $msg = $GUI_EVENT_CLOSE And $Lock = 0
Exit

Case $msg = $PassInput
If GUICtrlRead($PassInput) == $PassWord Then
Lock()
MsgBox(0, "Atempts", "An incorrect password was entered " & $Atempts & " time(s).")
$Atempts = 0
Else
$Atempts += 1
SplashMsg("Error", "Invalid Password", 220, 100)
EndIf

Case $msg = $GUI_EVENT_PRIMARYUP And $Lock = 1
GUISetState(@SW_SHOW, $PassWindow)
$Controls_Shown = 1
$Show_Controls_Timer = TimerInit()
EndSelect

If TimerDiff($Show_Controls_Timer) > 10000 And $Controls_Shown = 1 Then
GUISetState(@SW_HIDE, $PassWindow)
$Controls_Shown = 0
EndIf

If WinExists("Windows Task Manager") And $Lock = 1 Then
WinClose("Windows Task Manager")
WinKill("Windows Task Manager")
EndIf

If WinActive($ScreenyWindow) = 0 And WinActive($PassWindow) = 0 And $Lock = 1 Then
WinActivate($ScreenyWindow)
EndIf

If Not BitAND(WinGetState($ScreenyWindow, ""), 2) = 1 And $Lock = 1 Then
GUISetState(@SW_SHOW)
EndIf

If $Lock = 1 And WinExists($ScreenyWindow) = 0 Then
$ScreenyWindow = GUICreate("", @DesktopWidth, @DesktopHeight, -2, -2, $WS_POPUPWINDOW, $WS_EX_TOOLWINDOW)
GUISwitch($ScreenyWindow)
WinSetTrans($ScreenyWindow, "", 1)
GUISetState(@SW_SHOW, $ScreenyWindow)
WinSetOnTop($ScreenyWindow, "", 1)
WinSetOnTop($PassWindow, "", 1)
EndIf
WEnd

Func Lock()
If $Lock = 0 Then
RegWrite("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System", "DisableTaskMgr", "REG_DWORD", 00000001)
HotKeySet("{F9}")
HotKeySet("{F10}")
HotKeySet("{F11}")
; HotKeySet("^!p") ;Ctrl-Alt-p
; HotKeySet("^!l") ;Ctrl-Alt-l

TraySetIcon("Shell32.dll", 47)

$ScreenyWindow = GUICreate("", @DesktopWidth + 2, @DesktopHeight + 2, -2, -2, $WS_POPUPWINDOW, $WS_EX_TOOLWINDOW)
GUISwitch($ScreenyWindow)
WinSetTrans($ScreenyWindow, "", 1)

Global $PassWindow = GUICreate("", 220, 80, -1, -1, $WS_POPUPWINDOW, $WS_EX_TOOLWINDOW)
GUISwitch($PassWindow)
GUISetState(@SW_HIDE)
Global $Label = GUICtrlCreateLabel("The screen has been locked.", 10, 10, -1, 15)
; GUICtrlSetColor(-1,0xff0000)
Global $PassInput = GUICtrlCreateInput("Password", 10, 30, 200, 20, $ES_PASSWORD)
Global $Label2 = GUICtrlCreateLabel("Type Password and hit Enter", 10, 55, -1, 15)
; GUICtrlSetColor(-1,0xff0000)
GUISetState(@SW_SHOW, $ScreenyWindow)
WinSetOnTop($ScreenyWindow, "", 1)
WinSetOnTop($PassWindow, "", 1)
$Lock = 1
Else
GUIDelete($ScreenyWindow)
GUIDelete($PassWindow)
HotKeySet("{F9}", "close")
HotKeySet("{F10}", "Pass")
HotKeySet("{F11}", "Lock")
; HotKeySet("^!p", "Pass") ;Ctrl-Alt-p
; HotKeySet("^!l", "Lock") ;Ctrl-Alt-l

TraySetIcon("Shell32.dll", 44)
RegWrite("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System", "DisableTaskMgr", "REG_DWORD", 00000000)
$Lock = 0
EndIf

EndFunc ;==>Lock

Func Pass()
$PassWord = InputBox("Create Password", "Enter your password", "", "", 100, 100)
If $PassWord = "" Then
MsgBox(16, "error", "Invalid password.")
Pass()
Else
RegWrite("HKEY_LOCAL_MACHINE\SOFTWARE\Andy\ScreenLock", "Password", "REG_SZ", _StringEncrypt(1, $PassWord, "4471"))
EndIf
EndFunc ;==>Pass


Func SplashMsg($S_Title = "", $S_Text = "", $S_Size_X = 300, $S_Size_Y = 300)
SplashTextOn($S_Title, $S_Text & @CRLF & "Press Enter to close this window.", $S_Size_X, $S_Size_Y)
HotKeySet("{ENTER}", "OffSplash")
EndFunc ;==>SplashMsg

Func OffSplash()
SplashOff()
HotKeySet("{ENTER}")
EndFunc ;==>OffSplash

Func close()
Exit
EndFunc ;==>close
Virtual Desktop
#include 
#Include
#NoTrayIcon
Opt("TrayMenuMode",1)

FileDelete(@tempdir & "\pangaeadesktops.ini")
HotKeySet("#{ESC}","_panic")
HotKeySet("#{LEFT}","_prevdesk")
HotKeySet("#{RIGHT}","_nextdesk")
HotKeySet("^#{LEFT}","_movetoprev")
HotKeySet("^#{RIGHT}","_movetonext")
HotKeySet("#{DOWN}", "_QuickSelect")

Global $activedesk = 1,$winlist[500],$hwnd,$textwin,$texton = 0,$texttime,$desktopitem, $inaction = 0

_winget()

$desktopitem = TrayCreateItem("Desktop " & $activedesk)
TrayItemSetState(-1,$TRAY_DISABLE)
TrayCreateItem("")
$nextitem = TrayCreateItem("Next desktop win + right")
$previtem = TrayCreateItem("Prev desktop win + left")
TrayCreateItem("")
$tonextitem = TrayCreateItem("Move to next desktop ctrl + win + right")
$toprevitem = TrayCreateItem("Move to prev desktop ctrl + win + left")
TrayCreateItem("")
$displayall = TrayCreateItem("Quick Desktop Select win + down")
TrayCreateItem("")
$aboutitem = TrayCreateItem("About")
$exititem = TrayCreateItem("Exit win + esc")

TraySetState()

While 1
$msg = TrayGetMsg()
Select
Case $msg = $nextitem
_nextdesk()
Case $msg = $previtem
_prevdesk()
Case $msg = $tonextitem
_movetonext()
Case $msg = $toprevitem
_movetoprev()
Case $msg = $displayall
_QuickSelect()
Case $msg = $aboutitem
Msgbox(64,"about:","Pangaea Desktops" & @crlf & "by Rakudave, Pangaea WorX 2006" & @crlf & @crlf & "www.pangaeaworx.ch.vu")
Case $msg = $exititem
_panic()
EndSelect
If $texton = 1 then
If TimerDiff($texttime) > 2000 Then _text2()
Endif
WEnd

Func _showwins()
$var = IniReadSection(@tempdir & "\pangaeadesktops.ini", $activedesk)
If @error Then
return
Else
For $x = 1 To $var[0][0]
WinSetState($var[($var[0][0] +1) -$x][0],"",@SW_SHOW)
Next
EndIf
EndFunc ;==>_showwins

Func _hidewins()
$var = IniReadSection(@tempdir & "\pangaeadesktops.ini", $activedesk)
If @error Then
return
Else
For $x = 1 To $var[0][0]
WinSetState($var[($var[0][0] +1) -$x][0],"",@SW_HIDE)
Next
EndIf
EndFunc ;==>_hidewins

Func _QuickSelect()
If $inaction = 1 Then Return
$inaction = 1
For $i = 1 To 4
If $activedesk = $i Then
DllCall("captdll.dll", "int", "CaptureScreen", "str", @tempdir & "\pangaeaprtsc" & $i & ".jpg", "int", 85)
Else
_hidewins()
$olddesk = $activedesk
$activedesk = $i
_showwins()
DllCall("captdll.dll", "int", "CaptureScreen", "str", @tempdir & "\pangaeaprtsc" & $i & ".jpg", "int", 85)
_hidewins()
$activedesk = $olddesk
_showwins()
EndIf
Next
$hwnd = GUICreate("AnimatedWindow",@desktopwidth,@desktopheight,0,0,$WS_POPUP,$WS_EX_TOOLWINDOW + $WS_EX_TOPMOST)
$one = GUICtrlCreatePic(@tempdir & "\pangaeaprtsc1.jpg",0,0,@DesktopWidth/2,@DesktopHeight/2)
$two = GUICtrlCreatePic(@tempdir & "\pangaeaprtsc2.jpg",@DesktopWidth/2,0,@DesktopWidth/2,@DesktopHeight/2)
$three = GUICtrlCreatePic(@tempdir & "\pangaeaprtsc3.jpg",0,@DesktopHeight/2,@DesktopWidth/2,@DesktopHeight/2)
$four = GUICtrlCreatePic(@tempdir & "\pangaeaprtsc4.jpg",@DesktopWidth/2,@DesktopHeight/2,@DesktopWidth/2,@DesktopHeight/2)
GUISetState()
While 1
Switch GUIGetMsg()
Case $one
GUIDelete()
_hidewins()
$activedesk = 1
_showwins()
ExitLoop
Case $two
GUIDelete()
_hidewins()
$activedesk = 2
_showwins()
ExitLoop
Case $three
GUIDelete()
_hidewins()
$activedesk = 3
_showwins()
ExitLoop
Case $four
GUIDelete()
_hidewins()
$activedesk = 4
_showwins()
ExitLoop
EndSwitch
WEnd
$inaction = 0
EndFunc ;==>QuickSelect

Func _nextdesk()
If $inaction = 1 then return
$inaction = 1
If $texton = 1 Then _text2()
_winget()
_animate1("r")
_hidewins()
$activedesk = $activedesk + 1
If $activedesk = 5 Then $activedesk = 1
_showwins()
_animate2()
$inaction = 0
_text1()
EndFunc ;==>_nextdesk

Func _prevdesk()
If $inaction = 1 then return
$inaction = 1
If $texton = 1 Then _text2()
_winget()
_animate1("l")
_hidewins()
$activedesk = $activedesk - 1
If $activedesk = 0 Then $activedesk = 4
_showwins()
_animate3()
$inaction = 0
_text1()
EndFunc ;==>_prevdesk

Func _movetonext()
If $inaction = 1 then return
$inaction = 1
_winget()
IniDelete (@tempdir & "\pangaeadesktops.ini",$activedesk,$winlist[1])
$activedesk = $activedesk + 1
If $activedesk = 5 Then $activedesk = 1
Iniwrite(@tempdir & "\pangaeadesktops.ini",$activedesk,$winlist[1],"moved")
$activedesk = $activedesk - 1
If $activedesk = 0 Then $activedesk = 4
WinSetState($winlist[1],"",@SW_HIDE)
$inaction = 0
_nextdesk()
EndFunc ;==>_movetonext

Func _movetoprev()
If $inaction = 1 then return
$inaction = 1
_winget()
IniDelete (@tempdir & "\pangaeadesktops.ini",$activedesk,$winlist[1])
$activedesk = $activedesk - 1
If $activedesk = 0 Then $activedesk = 4
Iniwrite(@tempdir & "\pangaeadesktops.ini",$activedesk,$winlist[1],"moved")
$activedesk = $activedesk + 1
If $activedesk = 5 Then $activedesk = 1
WinSetState($winlist[1],"",@SW_HIDE)
$inaction = 0
_prevdesk()
EndFunc ;==>_movetoprev

Func _winget()
$y = 0
$var = WinList()
IniDelete(@tempdir & "\pangaeadesktops.ini",$activedesk)
For $x = 1 to $var[0][0]
If $var[$x][0] <> "" AND IsVisible($var[$x][1]) AND $var[$x][0] <> "Program Manager" AND $var[$x][0] <> "Desktop 1" AND $var[$x][0] <> "Desktop 2" AND $var[$x][0] <> "Desktop 3" AND $var[$x][0] <> "Desktop 4" Then
Iniwrite(@tempdir & "\pangaeadesktops.ini",$activedesk,$var[$x][0],$var[$x][1])
$y = $y + 1
$winlist[$y] = $var[$x][0]
EndIf
Next
$winlist[0] = $y
EndFunc ;==>_winget

Func _panic()
for $y = 1 to 4
$var = IniReadSection(@tempdir & "\pangaeadesktops.ini", $y)
If @error = 0 then
For $x = 1 To $var[0][0]
WinSetState($var[($var[0][0] +1) -$x][0],"",@SW_SHOW)
Next
EndIf
next
FileDelete(@tempdir & "\pangaeadesktops.ini")
FileDelete(@tempdir & "\pangaeaprtsc.jpg")
FileDelete(@tempdir & "\pangaeaprtsc1.jpg")
FileDelete(@tempdir & "\pangaeaprtsc2.jpg")
FileDelete(@tempdir & "\pangaeaprtsc3.jpg")
FileDelete(@tempdir & "\pangaeaprtsc4.jpg")
exit
EndFunc ;==>_panic

Func _animate1($direction)
If $direction ="r" Then
$activedesktemp = $activedesk + 1
If $activedesktemp = 5 Then $activedesktemp = 1
ElseIf $direction = "l" Then
$activedesktemp = $activedesk - 1
If $activedesktemp = 0 Then $activedesktemp = 4
EndIf
DllCall("captdll.dll", "int", "CaptureScreen", "str", @tempdir & "\pangaeaprtsc.jpg", "int", 85)
DllCall("captdll.dll", "int", "CaptureScreen", "str", @tempdir & "\pangaeaprtsc" & $activedesktemp & ".jpg", "int", 85)
$hwnd = GUICreate("AnimatedWindow",@desktopwidth,@desktopheight,0,0,$WS_POPUP,$WS_EX_TOOLWINDOW + $WS_EX_TOPMOST)
GUICtrlCreatePic(@tempdir & "\pangaeaprtsc.jpg",0,0,@desktopwidth,@desktopheight)
GUISetState()
EndFunc ;==>_animate1

Func _animate2()
DllCall("user32.dll", "int", "AnimateWindow", "hwnd", $hwnd, "int", 500, "long", 0x00050002);slide out to left
GUIDelete($hwnd)
EndFunc ;==>_animate2

Func _animate3()
DllCall("user32.dll", "int", "AnimateWindow", "hwnd", $hwnd, "int", 500, "long", 0x00050001);slide out to right
GUIDelete($hwnd)
EndFunc ;==>_animate3

Func _text1()
$text = "Desktop " & $activedesk
TrayItemSetText($desktopitem,$text)
$textwin = TextWindow($text,600,40,"",-1,10,10,0xFF0000)
GUISetState()
$texton = 1
$texttime = TimerInit()
EndFunc ;==>_text1

Func _text2()
GUIDelete($textwin)
$texton = 0
EndFunc ;==>_text2

Func OnAutoItExit()
_panic()
EndFunc ;==>OnAutoItExit

Func IsVisible($handle)
If BitAnd(WinGetState($handle),2) Then
Return 1
Else
Return 0
EndIf
EndFunc ;==>IsVisible

Func TextWindow($zText,$width,$height,$font="Microsoft Sans Serif",$weight=1000,$x=-1,$y=-1,$color=-1)
Local Const $ANSI_CHARSET = 0
Local Const $OUT_CHARACTER_PRECIS = 2
Local Const $CLIP_DEFAULT_PRECIS = 0
Local Const $PROOF_QUALITY = 2
Local Const $FIXED_PITCH = 1
Local Const $RGN_XOR = 3

If $font = "" Then $font = "Microsoft Sans Serif"
If $weight = -1 Then $weight = 1000
Local $gui = GUICreate("Text Window",$width,$height,$x,$y,$WS_POPUP,$WS_EX_TOOLWINDOW + $WS_EX_TOPMOST)
If $color <> -1 Then GUISetBkColor($color)
Local $hDC= DLLCall("user32.dll","int","GetDC","hwnd",$gui)
Local $hMyFont = DLLCall("gdi32.dll","hwnd","CreateFont","int",$height, _
"int",0,"int",0,"int",0,"int",1000,"int",0, _
"int",0,"int",0,"int",$ANSI_CHARSET, _
"int",$OUT_CHARACTER_PRECIS,"int",$CLIP_DEFAULT_PRECIS, _
"int",$PROOF_QUALITY,"int",$FIXED_PITCH,"str",$font )
Local $hOldFont = DLLCall("gdi32.dll","hwnd","SelectObject","int",$hDC[0], _
"hwnd",$hMyFont[0])
DLLCall("gdi32.dll","int","BeginPath","int",$hDC[0])
DLLCall("gdi32.dll","int","TextOut","int",$hDC[0],"int",0,"int",0, _
"str",$zText,"int",StringLen($zText))
DLLCall("gdi32.dll","int","EndPath","int",$hDC[0])
Local $hRgn1 = DLLCall("gdi32.dll","hwnd","PathToRegion","int",$hDC[0])
Local $rc = DLLStructCreate("int;int;int;int")
DLLCall("gdi32.dll","int","GetRgnBox","hwnd",$hRgn1[0], _
"ptr",DllStructGetPtr($rc))
Local $hRgn2 = DLLCall("gdi32.dll","hwnd","CreateRectRgnIndirect", _
"ptr",DllStructGetPtr($rc))
DLLCall("gdi32.dll","int","CombineRgn","hwnd",$hRgn2[0],"hwnd",$hRgn2[0], _
"hwnd",$hRgn1[0],"int",$RGN_XOR)
DLLCall("gdi32.dll","int","DeleteObject","hwnd",$hRgn1[0])
DLLCall("user32.dll","int","ReleaseDC","hwnd",$gui,"int",$hDC[0])
DLLCall("user32.dll","int","SetWindowRgn","hwnd",$gui,"hwnd",$hRgn2[0],"int",1)
DLLCall("gdi32.dll","int","SelectObject","int",$hDC[0],"hwnd",$hOldFont[0])
Return $gui
EndFunc ;==>TextWindow

Nguyên lý hoạt động của 1 số virus viết bằng AutoIT

Nguyên lý hoạt động của 1 số virus viết bằng AutoIT gần giống nhau:
1.tạo file autorun.inf ở mỗi ổ đĩa của máy. Trong file này sẽ gọi thực thi cái file .exe của virus mỗi khi bạn double click vào ổ đĩa. dó là nguyên do tại sao virus dạng này lây lan nhanh và khó trị
2. chạy ngầm các process có tên gần giống của window như CVHOST, SVHOST, SVHOSST...
3. sinh ra ở mỗi thư mục trong máy 1 file có dạng folder.exe (với folder là tên thư mục mà nó lây nhiễm, đây cũng là nghuyên nhân phát tán virus khi bạn lầm tưỡng nó là 1 thư muc
Disable folder option và taskmanager
Cách nhận biết và điều trị
với những máy chưa bị nhiễm:
Mở Mycomputer- thanh menu chon tool - folder option, bỏ dấu check ở các dòng hide extension...., chọn show hiden files and folders. Cách này giúp bạn phân biệt được phần mở rộng của file,tránh trường hợp click nhầm vào các file virus giả dạng
dùng các soft antivirus được update thường xuyên (khuyên dùng Bitdefender,Kapersky, NDO32), có thể dùng BKAV để quét thử coi có virus hay không (chứ khả năng chú này diệt được rất chi là kém)
Với những máy đã bị nhiễm
người dùng bỉnh thường có thể dùng những soft kể trên để quét, sau khi quét xong thi down các công cụ hoặc vào group policy để enable foder option và task manager. Dùng công cụ search của windows để tìm kiếm và xóa các file autorun.inf (1 số trường hợp file này vẫn tồn tại dù virus dã diệt được. Cũng có thể dùng hiren boot verson mới nhất để quét ngoài DOS (khá hiệu quả)
Đối với người am hiểu về hệ thống
dùng các tool như hijack this, hoặc các tool tương tự để scan và fix các key trong registry sinh ra do virus (thường là gọi thực thi 1 file.exe nào đó khi khởi động windows), scan và kill các process do virus sinh ra.Cuối cùng là xóa bằng tay các file do virus sinh ra
Reply With Quote

nhưng thành công viết virut

1) Thêm một virus lây lan mạnh qua Yahoo! IM - 2/8/2006 8h:4

NHÀ TÀI TRỢ

Chiều qua 1-8, một loại virus có tên VloveYM đã lây đến hàng loạt máy tính ở VN. Theo phân tích của Trung tâm An ninh mạng (BKAV), virus này xuất hiện ngày 28-7.

Cũng giống như các virus Gaixinh (Xrobot) và YMHeart trước đây, VloveYM chủ yếu lây lan trong cộng đồng người Việt sử dụng Yahoo! Messenger.

Khi click vào link, người dùng sẽ thấy một bảng chọn yêu cầu tải file Vlove về máy.

Loại virus mới xuất hiện và đang phát tán mạnh mẽ qua Yahoo Messenger - chúng tôi tạm gọi là "VLove" (Gọi theo cách đặt tên file Vlove.exe của link virus) - được phát tán từ một website có địa chỉ http://nguoiiu.com/funny/.

Nếu máy tính đã bị nhiễm VloveYM thì virus sẽ tự thay trang Homepage của trình duyệt IE thành fun.nguoiiu.com. Dù có thay đổi địa chỉ trang chủ hay dùng các chương trình quét spyware cũng không thể gỡ bỏ được địa chỉ trang chủ này. Tiếp đến những người có trong sổ địa chỉ của máy này sẽ đồng loạt nhận được những đường link trên cửa sổ chat như “http ...oiiu.com/funny/ :D Vui qua ne”, “http …oiiu.com/funny/ Truyen cuoi do, vao di =))”, “http …oiiu.com/life/ Tang ban ne =))”, “http …oiiu.com/life/ Tang ban tam thiep ne`...” và sẽ tưởng là do bạn chat gửi sang. Chính người bị dính virus cũng không biết mình đang phát tán các link nguy hiểm này. Nếu nhấp chuột vào đó thì máy tính sẽ bị nhiễm virus. Các đường link này ngay lập tức yêu cầu người dùng tải về một file virus có tên "Vlove.exe".

Ngay sau khi có thông tin này, VietNamNet đã liên hệ với Bùi Hải Nam - tác giả của virus Xrobots trước đây. Nam khẳng định đây không phải là "kiệt tác" mình, nhưng đưa ra nhận định ban đầu, nhiều khả năng người phát tán virus Vlove đã xử dụng mã nguồn của Xrobots do Nam viết bằng cách phân tích ngược (reverse) từ file .exe.

"Theo tôi, con virus này cũng được viết bằng Autoit - đây chính là chương trình tôi dùng để viết ra Xrobots. Hơn nữa, các mã nguồn có được từ việc reverse file virus Xobots.exe hiện được phát tán khá nhiều trên mạng" - Nam khẳng định.

Tuy nhiên theo chúng tôi nhận định, nếu có lấy mã nguồn từ Xrobots, thì Vlove rõ ràng cũng đã được "cải tiến" hơn. Bằng chứng là dù đã cập nhật virus Xrobots, nhưng phiên bản diệt virus mới nhất của BKAV vẫn không diệt được Vlove. (Thử nghiệm tiến hành vào 14h ngày 1/8/2006).

Trung tâm an ning mạng BKIS cho biết, hiện tại họ đã tiến hành phân tích thành công Vlove và tìm ra thủ phạm phát tán virus này. "Đó là một thanh niên sinh năm 1987" - Ông Nguyễn Tử Quảng - giám đốc BKIS cho biết kèm theo lời hứa, sẽ cập nhật Vlove vào cuối ngày hôm nay trong phiên bản BKAV.

Tối qua, BKAV đã cập nhật mẫu virus này trong phiên bản diệt virus Bkav881. Người sử dụng có thể vào đây để tải về hoặc tham khảo cách diệt virus này tại đây.





2)

những hiểu biết cơ bản về autoit

trích nguồn updatesofts.com/forum
AutoIt - Cái nhìn tổng quan
Thread này - coi như là để chào đón bài viết thứ 1000 của identical. Và phấn đấu lên 1000 thanked trong thời gian sớm nhất

Dedicated to cleo


1. Giới thiệu về AutoIt. Lịch sử phát triển

AutoIt là gì? Nó có được coi là một ngôn ngữ lập trình ko? Đó là câu hỏi thường được nhắc đi nhắc lại :104:

AutoIt là một ngôn ngữ dễ học, dễ sử dụng, giúp người dùng có thể thực thi những công việc mình thường phải làm trên máy tính một cách tự động. Bằng cách giả lập các phím bấm, các nút click chuột, cùng với khả năng tương tác với các cửa sổ, các chương trình, các file trong máy tính... AutoIt có thể làm được rất nhiều việc. Nhỏ, nhẹ, thậm chí có thể ko cần cài đặt, khả năng tương thích cao (từ Win 95 đến Win 2k3) và khả năng xuất ra file exe đã khiến AutoIt trở nên thông dụng và ngày càng được nhiều người biết đến

Riêng ở VN, AutoIt được biết đến thông qua hàng loạt những "virus" phát tán qua YM Có thể nói đây là một "hướng đi" khác của các chương trình viết bằng AutoIt, góp phần ko nhỏ khiến cho ngày càng nhiều các công cụ anti-virus nhận diện chương trình viết bằng AutoIt là virus, bất luận mục đích thực sự của những chương trình này là tốt hay xấu :107:

Ban đầu, các file mã nguồn AutoIt mang đuôi .ini (AutoIt 1), sau chuyển sang .aut (AutoIt 2) và giờ là .au3 (AutoIt 3). Mã nguồn chương trình AutoIt từ chỗ khá rắc rối (phiên bản 2) đã trở nên cực kỳ đơn giản và dễ hiểu (phiên bản 3), do khá gần gũi với ngôn ngữ BASIC. Cũng nên nói thêm một chút, trong quá trình đi từ AutoIt 2 lên AutoIt 3, một lập trình viên trong nhóm phát triển AutoIt đã quyết định tách ra thực hiện một dự án mới, mang lại nhiều tính năng mạnh mẽ thậm chí còn hơn AutoIt - tuy vậy cú pháp ngôn ngữ này cực kỳ phức tạp và khó hiểu :107:, ko trong sáng như AutoIt 3.

AutoIt có thể được tải về từ trang chủ www.autoitscript.com


2. Những công cụ cần dùng để viết các chương trình bằng AutoIt

Hiển nhiên, trước tiên bạn cần có AutoIt.

AutoIt được phân phối ở 2 dạng: Installer và ZIP. Phiên bản mới nhất là 3.2.0.1.

Ở dạng Installer, bạn sẽ down về một file exe: http://www.autoitscript.com/cgi-bin/....0.1-setup.exe - bộ cài của AutoIt. Down bộ cài đồng nghĩa với việc bạn sẽ có thêm nhiều tiện ích khi sử dụng AutoIt. Ví dụ, khi bạn kích chuột phải vào 1 file .au3, sẽ có tùy chọn cho phép bạn chạy script / sửa script bằng editor...

Còn dạng ZIP: http://www.autoitscript.com/cgi-bin/...t-v3.2.0.1.zip - dạng này cho phép bạn sử dụng AutoIt ở bất cứ đâu mà ko cần phải cài đặt (tạo rác trong registry ). Đây chính là bản portable mà bạn có thể đặt trong USB stick của mình

Để soạn thảo file .au3, bạn có thể dùng bất cứ trình soạn thảo nào, thậm chí là Notepad của Windows :104: Nếu muốn pzo hơn, có tính năng highlight code, chạy thử code bằng cách bấm F5... bạn có thể sử dụng SciTE. Đây là bản SciTE đã được sửa đổi để giúp bạn trong quá trình sử dụng AutoIt: http://www.autoitscript.com/autoit3/scite/downloads.php

Hoặc, bạn có thể dùng Textpad, Crimson Editor hay PSPad để viết các chương trình AutoIt. Các file syntax dành cho 3 trình soạn thảo này được kèm trong thư mục Extras\Editors của AutoIt.

Sau khi tiến hành cài đặt / giải nén AutoIt, bạn sẽ thấy một số file quan trọng nằm trong thư mục này và các thư mục con:
  • AutoIt3.exe - Công cụ dùng để chạy các mã nguồn viết bằng AutoIt
  • Aut2Exe.exe - Công cụ biên dịch file .au3 thành .exe để phân phối
  • Exe2Aut.exe - Công cụ dịch ngược file .exe (viết bằng AutoIt - hiển nhiên) về .au3
  • Au3Info.exe - Công cụ cho biết thông tin về các cửa sổ trên màn hình

Còn khá nhiều file khác, tuy nhiên trên đây là những công cụ cần thiết nhất.

3. Ngôn ngữ AutoIt qua cái nhìn khái quát

Làm thế nào để biết cách sử dụng và làm chủ sức mạnh của AutoIt?

Câu trả lời hết sức đơn giản: Tham khảo file Help + Forum của AutoIt.

Tất cả những j` cần thiết đều đã được trình bày một cách kỹ càng và đầy đủ trong file Help của AutoIt. Ở đây, tớ chỉ dẫn ra những điểm quan trọng nhất về ngôn ngữ AutoIt.

3.1. Cấu trúc file .au3

Một file script viết bằng AutoIt có định dạng .au3

File au3 này bao gồm các dòng lệnh, ví dụ như sau:

Code:
; 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
Như bạn có thể thấy, dòng đầu tiên là một chú thích, được đặt sau dấu ;. Nếu chú thích dài nhiều dòng, bạn có thể đặt trong khối #cs - #ce:

Code:
#cs
Comment goes here
Line 1
Line 2
#ce
3.2. Biến trong AutoIt

Trong AutoIt, các biến bắt đầu bằng dấu $, giống như ngôn ngữ PHP. Biến có thể được khai báo bằng các từ khóa Dim, Local hay Global:

Code:
  Dim $var1, $myvariable
Hoặc, bạn có thể dùng trực tiếp biến mà ko cần khai báo:

Code:
$var1 = "create and assign"
AutoIt hiển nhiên cũng hỗ trợ mảng nhiều chiều. Bạn chỉ việc sử dụng chúng cùng với chỉ số đặt trong dấu ngoặc vuông. Ví dụ:

Code:
$Array[1]="A"
$Array[1][1]="Upper-Left"


3.3. Các kiểu dữ liệu

AutoIt gồm các kiểu dữ liệu: Số; Xâu (hay chuỗi); Logic; Xâu nhị phân.

Dữ liệu kiểu số có thể là số nguyên (10, -6) hay số thực (3.334, 1.4e5) hay thậm chí ở dạng Hex (0x4FFFF, 0x409 - bắt đầu bằng 0x)

Dữ liệu kiểu xâu (chuỗi) được đặt trong dấu nháy đơn / nháy kép:

Code:
 'This "sentence" contains "lots" of "double-quotes" does it not?'
Dữ liệu kiểu logic có 1 trong 2 giá trị: true hoặc false:

Code:
$Boolean1 = true
$Boolean2 = false
Cuối cùng, kiểu xâu nhị phân là xâu bao gồm ký tự chr(0):

Code:
$bin = "abc" & chr(0) & "def"
$bin = BinaryString("abc")
3.4. Các toán tử

Cũng như các ngôn ngữ lập trình khác, AutoIt có các toán tử quen thuộc: +, -, *, /, ^...

Hoàn toàn có thể sử dụng các toán tử như +=, -=, *=, /=

Với kiểu logic, AND, OR và NOT là các toán tử hợp lệ.

3.5. Cấu trúc điều khiển

Có 3 loại cấu trúc điều khiển trong AutoIt:
  1. If...ElseIf...Else...EndIf
  2. Select...Case...EndSelect
  3. Switch...Case...EndSwitch

Cấu trúc If...ElseIf...Else...EndIf kiểm tra điều kiện, sau đó thực thi các lệnh:

Code:
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
Cấu trúc Select...Case sử dụng trong trường hợp cấu trúc If trở nên rườm rà:

Code:
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
Cấu trúc Switch...Case...EndSwitch hoàn toàn tương tự, tuy nhiên nó tiến bộ ở chỗ cho phép bạn chỉ rõ khoảng giá trị cần kiểm tra:

Code:
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


3.6. Các vòng lặp

Các loại vòng lặp trong AutoIt gồm có:
  1. For...Next
  2. While...WEnd
  3. Do...Until
  4. With...Endwith
  5. For...In...Next

For...Next được sử dụng để lặp từ giá trị ban đầu đến giá trị kết thúc, theo bước nhảy định sẵn:

Code:
For $i = 5 to 1 Step -1
MsgBox(0, "Count down!", $i)
Next
MsgBox(0,"", "Blast Off!")
While...WEnd và Do...Until tương tự như While Do và Repeat Until của Pascal:

Code:
$i = 0
While $i <= 10
MsgBox(0, "Value of $i is:", $i)
$i = $i + 1
WEnd
Code:
$i = 0
Do
MsgBox(0, "Value of $i is:", $i)
$i = $i + 1
Until $i = 10
With...EndWith dùng với các đối tượng, giúp tiết kiệm công sức khi gõ:

Code:
$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
Tương tự, bằng cách sử dụng For...In...Next, ta có thể duyệt qua tất cả mảng / tập các đối tượng:

Code:
FOR $element IN $aArray
$string = $string & $element & @CRLF
NEXT


3.7. Hàm

Hàm trong AutoIt được định nghĩa bằng cách dùng khối Func...EndFunc:

Code:
Func MyDouble($value)
$value = $value * 2
Return $value
EndFunc
Sử dụng hàm cũng rất đơn giản:

Code:
$val = 10 
For $i = 1 To 10
$doubled = MyDouble($val)
MsgBox(0, "", $val & " doubled is " & $doubled)
$val = $doubled
Next


4. Sử dụng các hàm built-in của AutoIt

Đây có thể coi là yếu tố tạo nên 80% sức mạnh của AutoIt. AutoIt bao gồm một số lượng lớn các hàm built-in, với tính năng trải rộng từ Quản lý file, thư mục đến quản lý các process, từ tương tác với registry đến giả lập các phím bấm...

Nói chung, các hàm này đã được liệt kê và hướng dẫn hết sức chi tiết về cách sử dụng trong file Help của AutoIt, do đó việc kể tên ra đây là vô nghĩa và ko cần thiết :]]

Hãy thử ví dụ với script sau, được dùng để tự động hóa quá trình cài đặt WinZip - giả lập bàn phím và gửi các phím cần thiết tới trình cài đặt:

Code:
; Run the winzip installer
Run("winzip90.exe")

; Initial Setup Screen
WinWaitActive("WinZip® 9.0 SR-1 Setup", "&Setup")
Send("!s")

; Install location
WinWaitActive("WinZip Setup", "into the following folder")
Send("{ENTER}")

; Features overview
WinWaitActive("WinZip Setup", "WinZip features include")
Send("!n")

; License agreement
WinWaitActive("License Agreement")
Send("!y")

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

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

; Installation type (custom/express)
WinWaitActive("WinZip Setup", "&Express setup (recommended)")
Send("!e")
Send("!n")

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

; Completed installation screen
WinWaitActive("WinZip Setup", "Thank you for installing this evaluation version")
Send("{ENTER}")

; Wait for winzip to load then close it
WinWaitActive("WinZip (Evaluation Version)")
WinClose("WinZip (Evaluation Version)")
Hoặc, vài ba lệnh dùng để tương tác với registry:

Code:
; Write a single REG_SZ value
RegWrite("HKEY_LOCAL_MACHINE\SOFTWARE\Test", "TestKey", "REG_SZ", "Hello this is a test")

; Write the REG_MULTI_SZ value of "line1" and "line2"
RegWrite("HKEY_LOCAL_MACHINE\SOFTWARE\Test", "TestKey1", "REG_MULTI_SZ", "line1" & @LF & "line2")
Một lời khuyên duy nhất: Bạn chỉ cần file Help + Forum của AutoIt để làm mọi thứ

5. Các hàm do người dùng tự định nghĩa

Các hàm này, nằm trong các file au3 được phân phối kèm với AutoIt. Điểm phân biệt hàm này với các hàm built-in là ở tên của hàm - Hàm tự định nghĩa thường có dấu gạch dưới ở trước tên, hàm built-in thì ko.

Để sử dụng các hàm tự định nghĩa, bạn cần include file mã nguồn của hàm vào script mình đang thực hiện. Ví dụ:

Code:
#include 



MsgBox(0,"Today","Today's date is " & Now())
Số lượng hàm tự định nghĩa rất nhiều và có thể được lấy về từ autoitscript.com






6.1. Thiết kế GUI

Nếu như các script viết bằng AutoIt có thể hoạt động một cách hoàn toàn âm thầm, nghĩa là click và chạy mà người dùng ko biết j` (mở ngoặc: giống "virus" YM nhờ :49, thì đôi khi bạn lại muốn tạo một GUI cho script cho giống một soft hoàn chỉnh

Khả năng tạo GUI trong AutoIt góp phần làm cho nó trở nên phổ biến và tiện dụng hơn

Trong GUI, bạn có thể tạo label, button, checkbox, radiobox, list, progress bar, context menu... nói chung là tất tần tật những j` mà một GUI có thể có.

Để tạo một ứng dụng có GUI, bạn có thể tạo bằng cách tự viết code lấy - Cái này chả khác j` với việc làm đồ họa bằng Pascal. Phải căn ke từng mili trên màn hình, sửa đổi vị trí cho hợp nhãn,... túm lại là rất phiền

Thử ví dụ một GUI cho dễ hình dung nhé:

Code:
; GUI
GuiCreate("Sample GUI", 400, 400)
GuiSetIcon(@SystemDir & "\mspaint.exe", 0)


; MENU
GuiCtrlCreateMenu("Menu&One")
GuiCtrlCreateMenu("Menu&Two")
GuiCtrlCreateMenu("MenuTh&ree")
GuiCtrlCreateMenu("Menu&Four")

; CONTEXT MENU
$contextMenu = GuiCtrlCreateContextMenu()
GuiCtrlCreateMenuItem("Context Menu", $contextMenu)
GuiCtrlCreateMenuItem("", $contextMenu) ;separator
GuiCtrlCreateMenuItem("&Properties", $contextMenu)

; PIC
GuiCtrlCreatePic("logo4.gif",0,0, 169,68)
GuiCtrlCreateLabel("Sample pic", 75, 1, 53, 15)
GuiCtrlSetColor(-1,0xffffff)


; AVI
GuiCtrlCreateAvi("sampleAVI.avi",0, 180, 10, 32, 32, $ACS_AUTOPLAY)
GuiCtrlCreateLabel("Sample avi", 170, 50)

; GUI MESSAGE LOOP
GuiSetState()
Một cách khác, thuận tiện hơn, đó là sử dụng một soft dạng GUI Builder. Có nhiều GUI Builder dành cho AutoIt, nhưng theo quan điểm cá nhân, có lẽ Koda là khá nhất. Công cụ này có thể tại về từ trang web: http://www.autoitscript.com/fileman/...ormdesign.html

Phiên bản mới nhất là 1.6, cập nhật ngày 19/9.

Koda cho phép bạn dễ dàng tạo GUI chỉ bằng cách drag-and-drop vào form, sau đó sẽ tự động sinh code AutoIt để bạn đưa vào script của mình. Rất rất tiện lợi nếu so sánh với việc code từ đầu bằng tay.

6.2. Gắn GUI với code

Có GUI rồi, là đến lúc bạn muốn gắn nó với các mã AutoIt thực thi các lệnh đã viết từ trước.

AutoIt hỗ trợ 2 chế độ tương tác với GUI: OnEvent và MessageLoop. Có thể đảo qua lại 2 chế độ bằng cách dùng lệnh:

Code:
Opt("GUIOnEventMode", 1)
Ở chế độ OnEvent, ta sẽ gắn từng "sự kiện" với một hàm tương ứng. Ví dụ, ta gắn "sự kiện" người dùng click nút Close với hàm Close():

Code:
GUISetOnEvent($GUI_EVENT_CLOSE, "CLOSE")
Func CLOSE()
MsgBox(0, "GUI Event", "You clicked CLOSE! Exiting...")
Exit
EndFunc
Ở chế độ MessageLoop, ta có một cách tiếp cận hoàn toàn khác. AutoIt sẽ tạo một vòng lặp vô hạn, liên tục kiểm tra xem có sự kiện nào xảy ra với GUI ko - thông qua một hàm mang tên GUIGetMsg.

Toàn bộ việc gắn code với GUI được thực hiện qua một vòng lặp While:

Code:
While 1
$msg = GUIGetMsg()

Select
Case $msg = $GUI_EVENT_CLOSE
MsgBox(0, "GUI Event", "You clicked CLOSE! Exiting...")
ExitLoop
EndSelect
WEnd


7. Chạy thử, biên dịch, đóng gói và phân phối

Có script hoàn chỉnh. Có GUI hoàn hảo. Đó là lúc bạn nghĩ đến việc tiếp theo. Phân phối tới càng nhiều người càng tốt (nhưng đừng dùng cách phát tán qua YM nhé )

Để chạy script viết bằng AutoIt, bạn hãy mở file AutoIt3.exe và chọn đến file .au3 tương ứng.

Để biên dịch thành file exe và đem đi phân phối, bạn cần đến công cụ Aut2Exe. Bạn cần chỉ định file mã nguồn, tên exe sẽ tạo, icon (nếu thích) và bấm Convert.

Nếu bạn muốn mình có thể dịch ngược từ exe về au3 trong trường hợp đánh mất file .au3 gốc , hãy chọn Allow decompilation và gõ vào password của mình. Pass này sẽ dùng để tránh người khác dịch ngược file script của bạn.

Nếu để ý kỹ, bạn sẽ thấy khi kích phải chuột vào file exe đã tạo + chọn properties, sẽ có thông tin File Version là phiên bản của AutoIt. Bạn rất có thể sẽ muốn loại bỏ thông tin này + đưa thông tin của riêng mình vào cho personal

Điều đó hoàn toàn có thể thực hiện được khi bạn dùng Resource Editor.

Tuy nhiên, nếu cố edit file exe đã biên dịch, bạn sẽ thấy mình phí công vô ích, bởi file exe mới sẽ ko hoạt động

Hãy edit file AutoItSC.bin cùng thư mục với Aut2Exe.exe với những thông tin mà bạn thích, sau đó mới tiến hành biên dịch. Lần này, kết quả sẽ như mong đợi

Bạn sẽ có một file .exe của riêng mình, với icon tùy ý, info ở mục properties tùy ý. Khó có thể nhận ra đó là script viết bằng AutoIt :]]

8. Phụ lục 1: AutoIt or not AutoIt?

Có thể nói ko ngoa, AutoIt là một con dao 2 lưỡi. Nó được tạo ra để giúp người dùng làm các script tự động hóa, giúp mình dễ thở hơn . Tuy vậy, AutoIt cũng có thể được dùng để tạo một con trojan, một con virus, whatever :49:

Phát tán con "virus" này là quá đơn giản. Hãy nhìn những j` các "virus" YM đã làm.

Như đã nói ở trên, một file exe có thể được edit để khi mới nhìn vào, bạn khó có thể biết nó có phải là một script AutoIt hay ko.

Nhưng, điều đó thực ra cũng ko hoàn toàn đúng. Một script viết bằng AutoIt, cho dù có được biên dịch với toàn bộ info trong file .bin bị luộc mất, vẫn có thể bị lộ danh tính, bằng chính một script AutoIt.

Đây là hàm nhận diện script viết bằng AutoIt, được tớ sưu tầm từ forum của nó:

Code:
Func _IsAutoItExe($hFile)
Local $hNew = StringTrimRight($hFile, 4) & 'verify.exe'
FileCopy($hFile, $hNew)
RunWait('"' & @ProgramFilesDir & '\AutoIt3\Aut2Exe\UPX.exe" -d "' & $hNew & '"', '', @SW_HIDE)
Local $sString = String(BinaryString(FileRead($hNew)))
FileDelete($hNew)
Local $sFind = '3C6465736372697074696F6E3E4175746F497420333C2F6465736372697074696F6E3E'
If StringInStr($sString, $sFind) Then Return 1
Return SetError(1, 0, 0)



EndFunc

9. Phụ lục 2: Công cụ xem thông tin về các cửa sổ - Au3Info.exe

Tự động hóa các công việc - đó cũng là lý do AutoIt có khả năng tương tác với các chương trình khác. Nhận diện một cửa sổ, xác định tọa độ chuột để giả lập việc click,... đó là những ứng dụng của Au3Info.exe.

Bạn chỉ việc chạy file này, trỏ đến cửa sổ cần xem thông tin. Mọi điều cần biết - title, class, mouse position, pixel color, control info... sẽ hiện lên. Bạn có thể bấm Ctrl + Alt + F để giữ nguyên trạng thái của cửa sổ thông tin, và copy những thông tin đó vào script mình đang viết để dùng.

10. Kết

Trên đây là tut dài nhất, mất công nhất mà tớ từng viết. Hết vụ này xin phép nghỉ viết tut dài hạn :]]

Hãy coi đây là cái nhìn tổng quan về AutoIt, về ngôn ngữ AutoIt, các công cụ đi kèm, những thứ cần thiết, những điều mà bạn có thể quan tâm...

Xin hết

autoitscripts-a

Tutorial - HelloWorld

This tutorial explains the basics of creating an AutoIt script and running it. The tutorial assumes that you have already fully installed AutoIt v3 using the supplied installer.

First open a folder where you wish to create the script. Right-click in the folder and select New / AutoIt v3 Script.

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

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

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

The code you see is simply some comments that you can use to organise your scripts. The lines that start with a semi-colon ; and are treated as comments (ignored). ; is similar to the REM statement in a DOS batch file.

Now we want to tell AutoIt to display a message box - this is done with the MsgBox function.

At the bottom of the file type the following:

MsgBox(0, "Tutorial", "Hello World!")

All functions take parameters, MsgBox takes three - a flag, a title and a message. The flag is a number that changes the way MsgBox displays - we will use 0 for now. The title and message are both string parameters - when using strings in AutoIt surround the text in double or single quotes. "This is some text" or 'This is some text' - both will work fine.

Now save the script and close the editor. You've just written your very first AutoIt script! To run the script simply double-click the helloworld.au3 file (you may also right-click the file and select Run Script) .

You should see this:

Now, let's look at the flag parameter for the MsgBox function again. From the manual page we can see various values listed which change the way MsgBox displays. The value of 0 simply shows a simple message box with an OK button. A value of 64 displays the message box with an information icon.

Edit the script again and change the 0 to 64 so you have:

MsgBox(64, "Tutorial", "Hello World!")

Run the script and you will see:

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

Tutorial - Notepad

This tutorial explains how to automate the opening of Notepad, automatically type some text and then close Notepad. It is assumed that you are already familiar with creating and running AutoIt scripts as shown in the HelloWorld tutorial.

First create an empty script called npad.au3 and then edit the file (using Notepad or SciTe as you prefer).

The first thing we need to know is the name of the Notepad executable. It is notepad.exe - you can get this information by looking at the properties of the Notepad shortcut icon in the Start Menu. To execute Notepad we use the AutoIt Run function. This function simply launches a given executable and then continues.

Type in the first line of script as:

Run("notepad.exe")

Run the script - if all goes well then a new instance of Notepad should open.

When automating applications AutoIt can check for window title so that it knows which window it should work with. With Notepad the window title is obviously Untitled - Notepad. AutoIt is case-sensitive when using window titles so you must get the title exactly right - the best way to do this is to use the AutoIt Window Information Tool. Run the Information Tool from Start Menu \ AutoIt v3 \ AutoIt Window Info.

With the Info Tool open click on the newly opened Notepad window to activate it; the Info Tool will give you information about it. The information we are interested in is the window title.

Highlight the title in the AutoIt Info Tool window and press CTRL-C to copy it to the clipboard - we can then paste the title into our script without fear of misspelling it.

After Running a copy of Notepad we need to wait for it to appear and become active before we send any keystrokes. We can wait for a window using the WinWaitActive function. Most window-related functions in AutoIt take a window title as a parameter.

Enter the following as the second line in the script (use CTRL-V or Edit\Paste to paste our window title from the clipboard).

WinWaitActive("Untitled - Notepad")

After we are sure the Notepad window is visible we want to type in some text. This is done with the Send function.

Add this line to our script.

Send("This is some text.")

The entire script will now look like this:

Run("notepad.exe")
WinWaitActive("Untitled - Notepad")
Send("This is some text.")

Close the copy of Notepad that we previously opened (you will need to do this every time you run the script otherwise you will end up with lots of copies running!). Run the script.

You should see Notepad open, and then some text will magically appear!


Next we want to close notepad, we can do this with the WinClose function.

WinClose("Untitled - Notepad")

When Notepad tries to close you will get a message asking you to save the changes. Use the Window Info Tool to get details of the dialog that has popped up so that we can respond to it :)

So, we add a line to wait for this dialog to become active (we will also use the window text to make the function more reliable and to distinguish this new window from the original Notepad window):

WinWaitActive("Notepad", "Do you want to save")

Next we want to automatically press Alt-N to select the No/Don't save button (Underlined letters in windows usually indicate that you can use the ALT key and that letter as a keyboard shortcut). In the Send function to send an ALT key we use ! .

Send("!n")

Our complete script now looks like this:

Run("notepad.exe")
WinWaitActive("Untitled - Notepad")
Send("This is some text.")
WinClose("Untitled - Notepad")
WinWaitActive("Notepad", "Do you want to save")
Send("!n")

Run the script and you will see Notepad open, some text appear, then close! You should be able to use the techniques learned in this tutorial to automate many other applications.

Tutorial - WinZip

This tutorial explains how to automate the installation of WinZip 9 SR-1. It is assumed that you are already familiar with creating and running AutoIt scripts and the use of the AutoIt Window Information Tool to read window titles and text, as shown in the HelloWorld and Notepad tutorials.

The WinZip installation consists of approximately 10 dialog boxes that you must click buttons (usually Next) to continue. We are going to write a script that simply waits for these dialog boxes to appear and then clicks the appropriate buttons. As usual with these types of installations the window title of each dialog is the same (WinZip Setup) so we must use window text to tell the difference between windows. Screenshots of each dialog will be provided and you can click on the picture to see the Information Tool output for that dialog.

First create a directory that we will use for the WinZip installer and our script file. Copy the WinZip installer to this directory and create a blank script called winzipinstall.au3.

We will now run through the installation manually and write the script as we go. The script lines to automate each dialog will be shown after each picture (remember to click on the picture to see the AutoIt Window Information Tool output). You can also look at the completed script for reference.

The first script line is easy, we want to run the winzip90.exe installer. So the first line is:

Run("winzip90.exe")

The first dialog will pop-up:

We need to wait for this window to popup and become active, and then we need to send the keystroke ALT-s to click the Setup button. The resulting script lines are:

WinWaitActive("WinZip® 9.0 SR-1 Setup", "&Setup")
Send("!s")

(Remember to click on the picture to see the AutoIt Window Information Tool output, this is especially important as the title contains the special (R) character which would be difficult to type).

The installation location dialog will appear next:

We need to wait for this screen to be active and then click ENTER to accept the install location. The script lines are:

WinWaitActive("WinZip Setup", "into the following folder")
Send("{ENTER}")

The WinZip Features dialog will appear next:

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

WinWaitActive("WinZip Setup", "WinZip features include")
Send("!n")

The License dialog will appear next:

Wait for the window to appear and then press ALT-y to accept the agreement:

WinWaitActive("License Agreement")
Send("!y")

Setup continues in a similar fashion for a few dialogs. The picture of each dialog is shown along with the script lines needed to automate it.

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

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

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

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

This is the final dialog of the setup. Notice that the Finish button doesn't have a keyboard shortcut - luckily it is the default button on this dialog so we can just press ENTER to select it. If this were not the case then we would have to TAB between controls or better yet use the ControlClick function.

WinWaitActive("WinZip Setup", "Thank you for installing this evaluation version")
Send("{ENTER}")

After installation WinZip will automatically start:

We simply wait for the main WinZip window to appear and then close it with the WinClose function.

WinWaitActive("WinZip (Evaluation Version)")
WinClose("WinZip (Evaluation Version)")

Here is the completed script - note that I have commented each dialog separately which makes it easier to follow and to change in the future (the next version of WinZip may be slightly different).

And that's it! Run the winzipinstaller.au3 script and watch as WinZip is installed in just a few seconds! The techniques used in this tutorial can be used to automate the installation of most programs.

As an exercise for the reader, try and redo the script but instead of using the Send function (which sends keys to the active window) to click on buttons try and use ControlClick instead which can be much more reliable. You will need to read up on Controls to do this.

Tutorial - Regular Expression

Here's a smallish guide on unravelling the seeming mysteries of StringRegExp().

StringRegExp( "test", "pattern" [, flag ] )

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

The Very Basics

As you may have figured out, the "pattern" string is the only difficult part of calling a StringRegExp() (forthwith: SRE). I find it best to think of patterns as telling the function to match a string character by character. There are different ways to find a certain character: If you want to match the string "test", that should be simple enough. You want to tell SRE to first search the string for a "t". If it finds one, then it assumes it has a match, and the rest of the pattern is used to try to prove that what it's found is not a match. So, if the next character is an "e", it could still be a match. Let's say the next letter is an "x". SRE knows immediately that it hasn't found a match because the third character you tell it to look for is an "s".

Example 1

MsgBox(0, "SRE Example 1 Result", StringRegExp("text", 'test'))

In this example, the message box should read "0", which means the pattern "test" was not found in the test string "text". I know this seems pretty simple, but now you know why it wasn't found.

The next way of specifying a pattern is by using a set ("[ ... ]"). You can equate a set to the logic function "OR". Let's use the previous Example. We want to find either the string "test" or the string "text". So, the way I start looking for a pattern is to think like SRE would think: The first character I want to match is "t", then the letter "e", this is the same for both strings we want to match. Now we want to match "s" OR "x", so we can use a set as a substitute: "[sx]" means match an "s" or an "x". Then the last letter is a "t" again.

Example 2

MsgBox(0, "SRE Example 2 Result", StringRegExp("text", 'te[sx]t'))
MsgBox(0, "SRE Example 2 Result", StringRegExp("test", 'te[sx]t'))

These should both provide the result "1", because the pattern should match both "test" and "text".

You can also specify how many times to match each character by using "{number of matches}" or you can specify a range by using "{min, max}". The first example below is redundant, but shows what I mean:

Example 3

MsgBox(0, "SRE Example 3 Result", StringRegExp("text", 't{1}e{1}[sx]{1}t{1}'))
MsgBox(0, "SRE Example 3 Result", StringRegExp("aaaabbbbcccc", 'b{4}'))



The Not-So Basics

Right now you're probably thinking "Isn't this just a glorified StringInStr() function?". Well, using a "flag" value of 0, most of the time you're right. But SRE is much more powerful than that. As you use SRE's more and more, you'll find you might know less and less about the type of pattern you are looking for. There are ways to be less and less specific about each character you wish to specify in the pattern. Take, for example, a line from the chat log of a game: "Gnarly Monster hits you for 18 damage." You want to find out how much damage Gnarly Monster hit you for. Well, you can't use StringInStr() because you aren't looking for "18", you're looking for "????", where ? could be any digit.

Here's how I would assemble this pattern. Look at what you do and do not know about what you want to find:
1) You know that it will ALWAYS contain nothing but digits.
2) You know that it will SOMETIMES be 2 characters long.
2a) You know from playing the game that the maximum damage a monster can do is 999.
2b) You know that the minimum damage a monster can do is 0.
3) You know that it will ALWAYS be between 1 and 3 characters long.
4) You know that there are no other digits in the test string.

At this point, I'd like to introduce the FLAG value of "1" and the grouping characters "()". The flag value of "1" means that SRE will not only match your pattern, but also return an array, with each element of the array consisting of a captured "group" of characters. So without veering off course too much, take this example:

Example 4

$asResult = StringRegExp("This is a test example", '(test)', 1)
If @error == 0 Then
MsgBox(0, "SRE Example 4 Result", $asResult[0])
EndIf
$asResult = StringRegExp("This is a test example", '(te)(st)', 1)
If @error == 0 Then
MsgBox(0, "SRE Example 4 Result", $asResult[0] & "," & $asResult[1])
EndIf

So, first the pattern must match somewhere in the test string. If it does, then SRE is told to "capture" any groups ("()") and store them in the return array. You can use multiple captures, as demonstrated by the second piece of code in Example 4.

Ok, back to the Gnarly Monster. Now that we know how to "capture" text, let's construct our pattern: Since you know what you're looking for is digits, there are 3 ways to specify "match any digit": "[:digit:]", "[0-9]", and "\d". The first is probably the easiest to understand. There are a few classes (digit, alnum, space, etc. Check the helpfile for a full list) you can use to specify sets of characters, one of them being digit. "[0-9]" just specifies a range of all the digits 0 through 9. "\d" is just a special character that means the same as the first two. There is no difference between the three, and with all SRE's there are usually at least a couple ways to construct any pattern.

So, first we know we want to capture the digits, so indicate that with the opening parentheses "(". Next, we know we want to capture between 1 and 3 characters, all consisting of digits, so our pattern now looks like "([0-9]{1,3}". And finally close it off with the closing parentheses to indicate the end of our group: "([0-9]{1,3})". Let's try it:

Example 5

$asResult = StringRegExp("Gnarly Monster hits you for 18 damage.", _
'([0-9]{1,3})', 1)
If @error == 0 Then
MsgBox(0, "SRE Example 5 Result", $asResult[0])
EndIf

There you go, the message box correctly displays "18".

Next we need to cover non-capturing groups. The way you indicate these groups is by opening the group with "(?:" instead of just "(". Let's say your log says "You deflect 36 of Gnarly Monster's 279 damage." Now if you run Example 5's SRE on this, you'll come up with "36" instead of "279". Now what I like to do here is just determine what's different between the numbers. One that jumps out at me is that the second number is always followed by a space and then the word "damage". We could just modify our previous pattern to be "([0-9]{1,3} damage)", but what if our script is just looking for the amount of damage, without " damage" tacked onto the end of the number? Here's where you can use a non-capturing group to accomplish this.

Example 6

$asResult = StringRegExp("You deflect 36 of Gnarly Monster's 279 damage.", '([0-9]{1,3})(?: damage)', 1)
If @error == 0 Then
MsgBox(0, "SRE Example 6 Result", $asResult[0])
EndIf

This could get lengthy, but mostly I just wanted to lay out the foundation for how regular expressions work, and mainly how SRE "thinks". A few things to keep in mind:
- Remember to think about the pattern one character at a time
- The StringRegExp() function finds the first character in the pattern, then it's your job to provide enough
evidence to "prove" whether or not it truly is a match. Example 6 is a good display of this.
- Remember [ ... ] means OR ([xyz] match an "x", a "y", OR a "z")
If you have any other questions, consult the help file first! It explains in detail all of the nitty gritty syntax that comes along with SRE's. One thing to look at in particular is the section on "Repeating Characters". It can make your pattern more readible by substituting certain characters for ranges. For example: "*" is equivalent to {0,} or the range from 0 to any number of characters.

Good luck, Regular Expressions can greatly decrease the length of your code, and make it easier to modify later. Corrections and feedback are welcome!

Resources


Wikipedia Article - Regular Expressions - Thanks blindwig.

The 30 Minute Regex Tutorial - by Jim Hollenhorst.


GUI for testing various StringRegExp() patterns - Thanks steve8tch. Credit: w0uter

Thanks to neogia for this tutorial.

Language Reference - Datatypes

In AutoIt there is only one datatype called a Variant. A variant can contain numeric or string data and decides how to use the data depending on the situation it is being used in. For example, if you try and multiply two variants they will be treated as numbers, if you try and concatenate (join) two variants they will be treated as strings.

Some examples:

10 * 20 equals the number 200 (* is used to multiply two numbers)

10 * "20" equals the number 200

"10" * "20" equals the number 200

10 & 20 equals the string "1020" (& is used to join strings)

If a string is used as a number, an implicit call to Number() function is done. So if it doesn't contain a valid number, it will be assumed to equal 0. For example,

10 * "fgh" equals the number 0.

If a string is used as a boolean and it is an empty string "" , it will be assumed to equal False (see below). For example,

NOT "" equals the Boolean true.

Numbers

Numbers can be standard decimal numbers like 2, 4.566, and -7.

Scientific notation is also supported; therefore, you could write 1.5e3 instead of 1500.

Integers (whole numbers) can also be represented in hexadecimal notation by preceding the integer with 0x as in 0x409 or 0x4fff (when using hex notation only 32-bit numbers are valid).

Strings

Strings are enclosed in double-quotes like "this". If you want a string to actually contain a double-quote use it twice like:

"here is a ""double-quote"" - ok?"

You can also use single-quotes like 'this' and 'here is a ' 'single-quote' ' - ok?'

You can mix quote types to make for easier working and to avoid having to double-up your quotes to get what you want. For example if you want to use a lot of double-quotes in your strings then you should use single-quotes for declaring them:

'This "sentence" contains "lots" of "double-quotes" does it not?'

is much simpler than:

"This ""sentence"" contains ""lots"" of ""double-quotes"" does it not?"

When evaluated, strings can have Env variables or Var variables substitution according to Opt() function definition.

Booleans

Booleans are logical values. Only two Boolean values exist: true and false.

They can be used in variable assignments, together with the Boolean operators and, or and not.

Examples:
$Boolean1 = true
$Boolean2 = false
$Boolean3 = $Boolean1 AND $Boolean2

This will result in $Boolean3 being false

$Boolean1 = false
$Boolean2 = not $boolean1

This will result in $Boolean2 being true


If Boolean values are used together with numbers, the following rules apply:

A value 0 will be equal to Boolean false
Any other number value will be equal to Boolean true

Example:
$Number1 = 0
$Boolean1 = true
$Boolean2 = $Number1 and $Boolean1

This will result in $Boolean2 being false


If you use arithmetics together with Boolean values (which is not advisable!), the following rules apply:

A Boolean true will be converted into the numeric value 1
A Boolean false will be converted into the numeric value 0

Example:
$Boolean1 = true
$Number1 = 100
$Number2 = $Boolean1 + $Number1

This will result in $Number2 to be the numeric value 101


If you use strings together with Boolean values, they will be converted as follows:

A Boolean true will be the string value "True"
A Boolean false will be the string value "False"

Example:
$Boolean1=true
$String1="Test is: "
$String2=$String1 & $Boolean1

This will result in $String2 being the string value "Test is: True"

The other way around however is different. When you use string comparisons with Boolean values, the following rules apply:
Only an empty string ("") will be a Boolean false
Any other string values (including a string equal "0") will be a Boolean true

Binary

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


Pointer

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

Datatypes and Ranges

The following table shows the internal variant datatypes and their ranges.

Data Sub-type Range and Notes
Int32 A 32bit signed integer number.
Int64 A 64bit signed integer number
Double A double-precision floating point number.
String Can contain strings of up to 2147483647 characters.
Binary Binary data, can contain up to 2147483647 bytes.
Pointer A memory address pointer. 32bit or 64bit depending on the version of AutoIt used.

Some functions in AutoIt only work with 32 bit numbers (e.g. BitAND) and are converted automatically - these functions are documented where required.

Language Reference - User Functions

A function is a section of code that can be called from the script to perform a certain "function". There are two sorts of functions in AutoIt, built-in functions and user functions.

built-in Functions

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

User Functions

User functions are declared using the Func...EndFunc statements.

Functions can accept parameters and return values as required.

Function names must start with either a letter or an underscore, and the remainder of the name can contain any combination of letters and numbers and underscores. Some valid function names are:

MyFunc

Func1

_My_Func1

Here is an example of using a function to double a number 5 times:

$val = 10
For $i = 1 To 10
$doubled = MyDouble($val)
MsgBox(0, "", $val & " doubled is " & $doubled)
$val = $doubled
Next

Exit


Func MyDouble($value)
$value = $value * 2
Return $value
EndFunc

Language Reference - Comments

Although only one statement per line is allowed, a long statement can span multiple lines if an underscore " _" preceded by a blank is placed at the end of a "broken" line. String definition cannot be split in several lines, concatenation need to be used.

MsgBox(4096,"", "This is a rather long line, so I " & _
"broke it with the underscore, _, character.")

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

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

You can combine underscore and semicolon to put comments on lines and still have a long statement span on next line.

dim $b_ ; This _ is not a continuation character, nor is the next one
dim $k_
Dim $a[8][2] = [ _
[ "Word", 4 ], _ ; Comment 1
[ "Test", 3 ], _
[ "pi", 3.14159], _ ; Associate the name with the value
[ "e", 2.718281828465], _ ; Same here
[ "test;1;2;3", 123], _
[ ';', Asc(';') ], _ ; This comment is removed, but the strings remain.
["", 0] ]

It is also possible to comment of large blocks of script by using the #comments-start and #comments-end directives.

autoitcripts

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

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

AutoIt can:

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

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

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

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

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

What's New?

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

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

Controls

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

Language Upgrades

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

Key and Mouse Simulation

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

Window Management

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

And much, much more.

Software License

AutoIt v3


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

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

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

SOFTWARE PRODUCT LICENSE

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

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

1. GRANT OF LICENSE.

This EULA grants you the following rights:

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

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

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

2. COPYRIGHT.

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

MISCELLANEOUS

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

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

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

LIMITED WARRANTY

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

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

Install Directory Structure

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

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

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

Aut2Exe.exe The script compiler.

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

AutoItSC.bin Executable stub for compiled scripts

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

GUI\ Contains examples of GUIs written in AutoIt.

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

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

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

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

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

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

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

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

Contains a light version of SciTe which allows syntax coloring.

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

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

Registry Keys

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

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

(Default) REG_SZ (value not set)

InstallDir REG_SZ C:\Program Files\AutoIt3

Version REG_SZ Version Number


HKEY_CURRENT_USER\Software\AutoIt v3\
Aut2Exe

(Default) REG_SZ (value not set)

AllowDecompile REG_DWORD 0x1

LastCompression REG_DWORD 0x2

LastExeDir REG_SZ My Documents

LastIcon REG_SZ

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

LastScriptDir REG_SZ My Documents
AutoUpdateIt

(Default) REG_SZ (value not set)

DoneOption REG_SZ Notify

DownloadDir REG_SZ C:\Downloads\ForExample\
Exe2Aut

(Default) REG_SZ (value not set)

LastExeDir REG_SZ C:\ForExample\

LastScriptDir REG_SZ
AU3Info

Default REG_SZ (value not set)

AlwaysOnTop REG_DWORD 0x1

ColorMode REG_DWORD 0x1

CoordMode REG_DWORD 0x1

HighlightColor REG_DWORD 0x0

HighlightControls REG_DWORD 0x1

Magnify REG_DWORD 0x0

WinH REG_DWORD 0x01c2

WinW REG_DWORD 0x012c

WinX REG_DWORD 0x0064

WinY REG_DWORD 0x0064

Frequently Asked Questions (FAQ)

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

Questions

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

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

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

4. Where is the "goto" command?

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

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

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

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

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

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

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

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

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

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

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

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

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

v3 has a different language structure to v2.64.

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

Back To Top

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

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

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

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

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

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

Back To Top

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

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

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

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

Back To Top

4. Where is the "goto" command?

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

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

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

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

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

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

Back To Top

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

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

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

Back To Top

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

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

RunWait("msiexec myfile.msi")

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

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

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

ShellExecuteWait("myfile.msi")

Back To Top

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

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

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

or use single quotes instead:

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

Back To Top

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

There is a detailed description here.

Back To Top

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

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

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

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

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

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

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

Back To Top

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

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

Send($myvar, 1)

Back To Top

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

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

Back To Top

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

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

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

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

Back To Top

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

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

Back To Top

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

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


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

Back To Top

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

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

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

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

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

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

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

Back To Top

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

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

Back To Top

Running Scripts

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

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

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

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

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

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

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

Command Line Parameters

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

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

So if your script is run like this:

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

$CmdLine[0] equals... 2

$CmdLine[1] equals... param1

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

@ScriptName equals... myscript.au3

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

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

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

myscript.exe param1 "this is another param"

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

Note that $CmdLineRaw just return the parameters.

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

AutoIt specific command Line Switches

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


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

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

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

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


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

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

The tray icon will not be displayed when using /AutoIt3ExecuteLine

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

AutoIt on Windows Vista

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

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

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

; This script requires full Administrative rights
#requireadmin

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

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

UAC Prompts

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

Standard User Prompt

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

Administrator User Prompt

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

Compiled Scripts

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

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

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

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

Even signed code can be malicious!

Command Line Parameters

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

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

So if your script is run like this:

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

$CmdLine[0] equals... 2

$CmdLine[1] equals... param1

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

@ScriptName equals... myscript.au3

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

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

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

myscript.exe param1 "this is another param"

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

Note that $CmdLineRaw just return the parameters.

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

AutoIt specific command Line Switches

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


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

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

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

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


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

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

The tray icon will not be displayed when using /AutoIt3ExecuteLine

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

Script Editors

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

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

Some other recommended editors are:

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

Compiling Scripts with Aut2Exe

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

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

Aut2Exe can be used in three ways:

Method 1 - Start Menu

Only available if full install performed.

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

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

3. The main Aut2Exe interface should appear.

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

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

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

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

8. Click on Convert to compile the script.

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

Method 2 - Right Click

Only available if full install performed.

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

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

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

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

Method 3 - The Command Line

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

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

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

Technical Details

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

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

AutoIt Window Information Tool

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

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

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

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

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

Window Titles and Text (Basic)

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

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

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

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

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

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

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

WinWaitActive("Untitled - Notepad")

and

WinWaitActive("Untitled - Notepad", "")

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

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

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

Window Text

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

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

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

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

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

Window Titles and Text (Advanced)

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

Mode 1 (default)

Matches partial titles from the start.

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

e.g.

WinWait("Untitled")

Mode 2

Matches any substring in the title.

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

e.g.

WinWait("Notepad")

Mode 3

Exact title match.

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

Mode 4

Advanced mode.

See Advanced Window Descriptions.

Mode -1 to -4

Force lower case match according to other type of match.

Advanced Window Descriptions

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

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

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

[PROPERTY1:Value1; PROPERTY2:Value2]

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

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

e.g. Close the currently active window

WinClose("[ACTIVE]", "")

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

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

Window Handles / HWNDs

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

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

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

Controls

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

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

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

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

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

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

[PROPERTY1:Value1; PROPERTY2:Value2]

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

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

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

or

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

or

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

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

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

or

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

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

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

Control Handle (HWND)

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

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

Unicode Support

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

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

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

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

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

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

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

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

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

Current Limitations

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

These limits will be addressed in future versions if possible.

Intended Use

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

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

Notes for users familiar with AutoIt 2.64

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

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


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

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

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


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

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

- Scripts have the extension .au3 instead of .aut


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

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