AutoIt实际上很强大,至少“足够强大”。除了它的内建函数相当丰富之外[1] ,还有大量的UDF,并且,在AutoIt论坛上时时刻刻都有人在不断地补充各种功用的新UDF。
尽管看起来很简单,这一节可能是最重要的内容。
先让我们拿MsgBox()这个函数作为讲解起点。打开MsgBox()这个函数的帮助文档,我们最先看到的是它的简要说明和参数定义:
MsgBox
Displays a simple message box with optional timeout.MsgBox ( flag, "title", "text" [, timeout [, hwnd]] )
参数定义中的方括号(“[ ]”)的含义是,“该参数在函数定义中设定了默认值,所以,这个参数是可选参数”,即,可以不指定这个参数,如果不指定的话,则直接使用函数定义的默认值──而这个默认值究竟是什么,在接下来的文档中有详细的解释。
Parameters
flag The flag indicates the type of message box and the possible button combinations. See remarks. title The title of the message box. text The text of the message box. timeout [optional] Timeout in seconds. After the timeout has elapsed the message box will be automatically closed. The default is 0, which is no timeout. hwnd [optional] The window handle to use as the parent for this dialog.
读过文档之后,就会知道
MsgBox(4096, "Test", "This box has no timeout limit", 0)
和
MsgBox(4096, "Test", "This box has no timeout limit")
是一样的。
而“4096”究竟是什么意思,在接下来的文档中可以找到:
| decimal flag | Button-related Result | hexadecimal flag |
| 4096 | System modal (dialog has an icon) | 0×1000 |
在使用MsgBox()的话,AutoIt用这个函数的返回值来判断用户究竟按下了对话框中的哪一个按钮,比如,如果用户按下的是“OK”(确定)按钮,那么返回值是1;如果按下的是“ABORT”(取消)按钮,则返回值是3;如果在Time Out的时间内没有任何动作,返回值是-1……
请尝试一下以下代码(Testing17.au3):
While 1 $n = MsgBox(3, 'MsgBox Demo', 'Please Press one of the buttons...') Select Case $n == 6 MsgBox(0, 'Info', 'You pressed "YES"', 2) Case $n == 7 MsgBox(0, 'Info', 'You pressed "NO"', 2) Case $n == 2 MsgBox(0, 'Info', 'You pressed "CANCEL", and quit the program...', 2) ExitLoop EndSelect WEnd
注意:在AutoIt中,每个函数都是有“返回值”的──即便在定义的时候没有给出返回值,AutoIt也会自动返回一个0……
请尝试一下以下代码(Testing18.au3):
Func __DoNothing() EndFunc MsgBox(0, "", "Function __DoNothing() returns " & __DoNothing())
如果函数调用处于表达式之中,那么它的返回值讲参与表达式计算;如果函数只是被调用(比如,一行代码中只有一个MsgBox()函数)而已,那么它的返回值将被“扔掉”(Throw out)。
另外,调用UDF的时候,需要“引用”定义文件,语法是:#Include <Filename.au3>。之前我们已经见过具体的例子,比如想使用_ArrayDisplay这个函数的话,那么就得在程序开头加上#Include <Array.au3>。_ArrayDisplay的参数定义如下:
#Include _ArrayDisplay(Const ByRef $avArray [, $sTitle = "Array: ListView Display" [, $iItemLimit = -1 [, $iTranspose = 0 [, $sSeparator = "" [, $sReplace = "|" [, $sHeader = ""]]]]]])
以后当你需要做什么事情的时候,
- 先去看看AutoIt帮助文档,看看有没有能够完成相应功能的函数
- 认真阅读该函数的帮助文档,以及其中的范例
- 将此函数把玩一阵,测试它的方方面面
- 将其应用到你的程序中去……
- 最后,如果你有兴趣的话,可以去阅读一下那些UDF的源码(都是公开的),学习它们的构建方法……
学会看帮助文档,就好像是学会查词典一样,是最基础,却又最重要的技能。听起来很荒唐,但确实有很多人学了一辈子英语却不懂如何查词典,于是一辈子有解决不完的问题,而又不知道症结究竟在哪里;同样的道理,有很多人学了很久的编程,却从来没有认真研究过如何查看文档,于是最终与那些学英语却不会查词典的人同一个下场,并且从不自知。
Wikipedia上有个很好的条目,建议所有人都去认真阅读一下:http://en.wikipedia.org/wiki/Rtfm
Footnotes:
- 以后你会知道,任何一种编程语言,真正强大的地方都在于它们各自的“函数库”(Library)…… [↩]



{ 2 comments… read them below or add one }
受教了。
我猜下一步要讲例子了,期待!