If 表达式
{
语句
}
如果 If 语句的表达式的计算结果为 true(即除空字符串或数字 0 以外的任何结果), 则执行其下面的行或区块. 否则, 如果存在相应的 Else 语句, 则执行将跳转到其下面的行或区块.
如果 If 拥有多行, 那么这些行必须用大括号括起来(创建一个区块). 但是, 如果只有一行属于 If, 则大括号是可选的. 请参阅此页面底部的示例.
如果表达式以小括号开头, 则 if 后面的空格是可选的, 例如 if(expression).
可以选择使用 One True Brace(OTB) 样式. 例如:
if (x < y) {
; ...
}
if WinExist("Untitled - Notepad") {
WinActivate
}
if IsDone {
; ...
} else {
; ...
}
与 If 语句不同, Else 语句支持任何类型的语句紧跟在其右边.
表达式, 三元运算符(a?b:c), 区块, Else, While-loop
如果 A_TickCount - StartTime 的结果大于 2*MaxTime + 100, 显示 "Too much time has passed." 并终止脚本.
if (A_TickCount - StartTime > 2*MaxTime + 100)
{
MsgBox "Too much time has passed."
ExitApp
}
if (Color = "Blue" or Color = "White")
{
MsgBox "The color is one of the allowed values."
ExitApp
}
else if (Color = "Silver")
{
MsgBox "Silver is not an allowed color."
return
}
else
{
MsgBox "This color is not recognized."
ExitApp
}
单个多语句行不需要用大括号括起来.
MyVar := 3
if (MyVar > 2)
MyVar++, MyVar := MyVar - 4, MyVar .= " test"
MsgBox % MyVar ; 报告 "0 test".
类似于 AutoHotkey v1 的 If Var [not] between Lower and Upper, 下面的例子检查变量的内容是否在两个值(包括) 之间, 以数字或字母表示.
检查 var 是否在 1 到 5 的范围内:
if (var >= 1 and var <= 5)
MsgBox var " is in the range 1 to 5, inclusive."
检查 var 是否在 0.0 到 1.0 的范围内:
if not (var >= 0.0 and var <= 1.0)
MsgBox var " is not in the range 0.0 to 1.0, inclusive."
检查 var 是否在 VarLow 和 VarHigh(包括) 之间:
if (var >= VarLow and var <= VarHigh)
MsgBox var " is between " VarLow " and " VarHigh "."
检查 var 是否按字母顺序排列在蓝色和红色(包括) 之间:
if (StrCompare(var, "blue") >= 0) and (StrCompare(var, "red") <= 0)
MsgBox var " is alphabetically between the words blue and red."
允许用户输入一个数字, 并检查它是否在 1 到 10 的范围内:
LowerLimit := 1
UpperLimit := 10
IB := InputBox("Enter a number between " LowerLimit " and " UpperLimit)
if not (IB.Value >= LowerLimit and IB.Value <= UpperLimit)
MsgBox "Your input is not within the valid range."
类似于 v1 的 If Var [not] in/contains MatchList, 下面的例子检查变量的内容是否匹配列表中的项目.
检查 var 是否是文件扩展名 exe, bat 或 com:
if (var ~= "i)\A(exe|bat|com)\z")
MsgBox "The file extension is an executable type."
检查 var 是否是质数 1, 2, 3, 5, 7 或 11:
if (var ~= "\A(1|2|3|5|7|11)\z")
MsgBox var " is a small prime number."
检查 var 是否包含数字 1 或 3:
if (var ~= "1|3")
MsgBox "Var contains the digit 1 or 3 (Var could be 1, 3, 10, 21, 23, etc.)"
检查 var 是否是 MyItemList 中的一个项目:
; 如果 MyItemList 包含除 | 之外的 RegEx 字符, 则取消下一行的注释
; MyItemList := RegExReplace(MyItemList, "[\Q\.*?+[{()^$\E]", "\$0")
if (var ~= "i)\A(" MyItemList ")\z")
MsgBox var " is in the list."
允许用户输入一个字符串并检查它是否是单词 yes 或 no:
IB := InputBox("Enter YES or NO")
if not (IB.Value ~= "i)\A(yes|no)\z")
MsgBox "Your input is not valid."
检查 active_title 是否包含 "Address List.txt" 或 "Customer List.txt", 并检查它是否包含 "metapad" 或 "Notepad":
active_title := WinGetTitle("A")
if (active_title ~= "i)Address List\.txt|Customer List\.txt")
MsgBox "One of the desired windows is active."
if not (active_title ~= "i)metapad|Notepad")
MsgBox "But the file is not open in either Metapad or Notepad."