使用autoit实现windows桌面程序自动化

date: 2024/6/22

https://www.autoitscript.com/site/autoit/downloads/下载压缩包解压安装或者安装程序都行

在vscode中下载autoit插件,通过调用安装目录下的AutoIt3_x64.exe并输入参数test.au3执行脚本。

AutoIt3_x64.exe test.au3

基本语法

;单行注释
#cs
这是一个多行注释
可以包含多行文字
#ce

$stringVar = "Hello, AutoIt!"; 声明一个字符串变量
$intVar = 123; 声明一个整数变量
$arrayVar = ["Apple", "Banana", "Cherry"]; 声明一个数组

; If...ElseIf...Else 结构
If $intVar > 100 Then
    MsgBox(0, "Info", "The variable is greater than 100")
ElseIf $intVar = 100 Then
    MsgBox(0, "Info", "The variable is exactly 100")
Else
    MsgBox(0, "Info", "The variable is less than 100")
EndIf

; For...Next 循环
For $i = 1 To 5
    MsgBox(0, "Info", "This is loop iteration " & $i)
Next

; While...WEnd 循环
$i = 1
While $i <= 5
    MsgBox(0, "Info", "This is loop iteration " & $i)
    $i += 1
WEnd

; Do...Until 循环
$i = 1
Do
    MsgBox(0, "Info", "This is loop iteration " & $i)
    $i += 1
Until $i > 5

; 带参数和返回值的函数
Func Add($a, $b)
    Return $a + $b
EndFunc

; 调用带参数和返回值的函数
$result = Add(5, 10)

文件操作

; 写入文件
$filePath = "example.txt"
$fileHandle = FileOpen($filePath, 2) ; 2 = write mode
FileWriteLine($fileHandle, "This is a line of text.")
FileClose($fileHandle)

; 读取文件
$fileHandle = FileOpen($filePath, 0) ; 0 = read mode
If $fileHandle = -1 Then
    MsgBox(0, "Error", "Failed to open the file.")
Else
    $line = FileReadLine($fileHandle)
    MsgBox(0, "Content", $line)
    FileClose($fileHandle)
EndIf

GUI创建

#include <GUIConstantsEx.au3>
; 创建一个 GUI 窗口
$hGUI = GUICreate("My GUI", 400, 300)
; 创建一个按钮
$hButton = GUICtrlCreateButton("Click Me", 150, 130, 100, 30)
; 显示 GUI
GUISetState(@SW_SHOW)
; 等待用户操作
While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            Exit
        Case $hButton
            MsgBox(0, "Info", "Button Clicked!")
    EndSwitch
WEnd

窗口操作

WinActivate("Untitled - Notepad");激活窗口
WinWait("Untitled - Notepad");等待窗口出现
WinClose("Untitled - Notepad");关闭指定窗口
If WinExists("Untitled - Notepad") Then;检查窗口是否存在
    MsgBox(0, "Info", "Notepad is open")
EndIf

控制发送

Send("Hello, World!");活动窗口发送按键
ControlSend("Untitled - Notepad", "", "Edit1", "Hello, World!");指定窗口发送按键
MouseClick("left", 100, 200);模拟鼠标点击

系统操作

Sleep(1000) ; 暂停 1 秒
Run("notepad.exe");运行指定程序
Exit;终止脚本

网络操作,注册表操作等见文档