AppleScript 程式設計/系統事件
外觀
System Events 是 AppleScript 可以用到的眾多功能之一。要使用 System Event 應用程式,您首先需要向其傳送 "tell" 命令。
tell application "System Events"
-- add code here.
end tell
這將指示 AppleScript 執行與 System Events 程式相關的命令。例如,命令
keystroke "e"
將在當前應用程式中鍵入字母 "e"。
這是一個簡單的程式
tell application "TextEdit"
activate
make new document
end tell
tell application "System Events"
keystroke "Support Wikibooks!"
end tell
它將開啟 TextEdit 應用程式,啟動一個新文件,並鍵入短語 "Support Wikibooks!"。
您還可以使用 keystroke tab(注意沒有引號)鍵入製表符,以及 keystroke return 來換行。
tell application "TextEdit"
activate
make new document
end tell
tell application "System Events"
keystroke "Support Wikibooks!"
keystroke return
keystroke "by donating!"
end tell
這將建立一個包含 "Support Wikibooks!" 的新文件,並在另一行上顯示 "by donating"。
現在您可能想知道,如何執行像 command+q 這樣的組合鍵(適用於其他修飾鍵,如 option 和 control)?
組合鍵是由三行程式碼組成的,包括
key down {command}
keystroke "q"
key up {command}
您還可以使用 "key down" 和 "key up" 的增強功能同時按下多個鍵,但要用逗號隔開各個鍵。
這是一個開啟 TextEdit 應用程式,然後使用 command+q 退出應用程式的程式。
tell application "TextEdit"
activate
end tell
delay 3.0
tell application "System Events"
key down {command}
keystroke "q"
key up {command}
end tell
您也可以使用單行命令來執行鍵擊,例如
tell application "System Events" to keystroke "c" using command down
這將在大多數 Mac 應用程式中呼叫 "複製" 命令。
也可以像這樣在一行中使用組合鍵
keystroke "h" using {command down, shift down}