上篇文章介紹了AutoHotKey的準系統和大致模組,這次用一個簡單的例子來說說AutoHotKey的指令碼編寫。和流行的自動化測試載入器一樣,可以通過錄製在編寫指令碼,也可以直接手工寫指令碼。但是對於GUI的應用程式來說,基本上都需要錄製操作,產生針對記錄遊歷過的對象或座標的指令碼。AutoHotKey功能相對簡單,基本上只記錄座標,少數對於Window的操作是用對象表示的,相當於流行自動化測試載入器中的低級錄製。
下面就是我用AutoHotKey中的AutoScriptWriter (recorder)錄製開啟案頭坐下方“Quick Launch”欄中的IE瀏覽器,然後在地址欄中直接輸入www.google.com,然後斷行符號,在google的搜尋中輸入test,在斷行符號的一個過程。
---------
WinWait, ,
IfWinNotActive, , , WinActivate, ,
WinWaitActive, ,
MouseClick, left, 125, 22
Sleep, 100
WinWait, Blank Page - Windows Internet Explorer,
IfWinNotActive, Blank Page - Windows Internet Explorer, , WinActivate, Blank Page - Windows Internet Explorer,
WinWaitActive, Blank Page - Windows Internet Explorer,
Send, www.google.com{ENTER}
WinWait, Google - Windows Internet Explorer,
IfWinNotActive, Google - Windows Internet Explorer, , WinActivate, Google - Windows Internet Explorer,
WinWaitActive, Google - Windows Internet Explorer,
Send, test{ENTER}
WinWait, test - Google Search - Windows Internet Explorer,
IfWinNotActive, test - Google Search - Windows Internet Explorer, , WinActivate, test - Google Search - Windows Internet Explorer,
WinWaitActive, test - Google Search - Windows Internet Explorer,
MouseClick, left, 1016, 13
Sleep, 100
--------------
大家可以看到輸入用Send, <字元>表示,點擊為MouseClick, left, <x>, <y>。至於很多的IfWinNotActive類似於測試載入器中的同步語句。因為座標經常會變,所以如果能用按鍵的盡量用按鍵,避免座標。象上面的Enter其實是可以用滑鼠點擊“Google search”按鈕來實現的,但保險起見用Enter鍵更好。
AutoHotKey也提供比較好的指令碼語言,還是和vbscript比較相似。很好學習,可以開啟AutoHotkey Help File來尋找。經過簡單的修改後,指令碼如下:
--------------
Run %A_ProgramFiles%/Internet Explorer/iexplore.exe ; start IE browser
Sleep 5000 ; wait launch IE browser
Send, www.google.com{ENTER} ; input google's website in address bar
Sleep 5000 ; wait open google's home page
Send, test{ENTER} ; input keyword in search field
Sleep 5000 ; wait search result
MouseClick, left, 1016, 13 ; click x button to close IE window
--------------
在上面的指令碼我用Sleep來同步操作,其實還有很多別的方法,例如WaitObject語句就是通過等待某個地區或點的顏色為期望的顏色時執行下一步操作,還有類似等待某個圖片的。由於不提供針對對象的,其他的方式不是太靈活而且太多地方需要使用,也就沒有採用。對於一些比較重要的地方,可以使用如下方法
Loop, 5
{
IfWinExist, Save As ; check whether Save As dialogbox exists
break
else
sleep %ShortSleepTime%
}
關閉視窗也可以用WinClose, A來關閉當前活動的視窗。類似還有很多的這樣的語句,就和以前寫代碼一樣,唯一的就是沒發現可以調用其他的指令碼,只能在當前指令碼內有效。不過自己本來就不是正道使用,呵呵。
先說到這,有興趣的朋友可以一起探討。