有2種方法做的:
1)使用GUI腳本的方法:這是你已經開始做了。您可以像用戶一樣模擬鍵盤事件。這主要不是因爲3個原因而推薦的:它通常很慢(您需要添加延遲來爲系統打開窗口留出時間,關閉它們,..)。在腳本期間,如果用戶誤擊了鍵/鼠標,您的腳本將失敗。最後,你幾乎不依賴於應用程序的用戶界面:如果編輯器(這裏是帶有TextEdit的Apple)更改某些內容(如快捷鍵),則腳本將不再起作用。
儘管如此,如果你仍然想使用這種方式,這是腳本,它爲你做。我建議你像我一樣添加註釋(如何記住關鍵代碼8是'c'!)。我添加了一些額外的選項來選擇保存路徑(回家文件夾,輸入特殊路徑,...)。您可以使用它們:
tell application "TextEdit"
activate
tell application "System Events"
key code 126 using command down -- command up (cursor at start)
key code 125 using shift down -- shift down (select 1st line)
keystroke "c" using command down -- command C (copy)
keystroke "s" using command down -- open save dialog
delay 0.5 -- to let save as dialog time to open
keystroke "v" using command down -- paste the title from clipboard
-- other options
-- keystroke "h" using {command down, shift down} -- go home directory
delay 0.5
keystroke "g" using {command down, shift down} -- go to dialog
delay 0.5
keystroke "Desktop/Sample" -- path from Documents folder to Sample folder on Desktop
delay 0.5
keystroke return -- close the go to dialog
delay 0.5
keystroke return -- close the save as dialog
end tell
end tell
2)使用Applescript指令的方法。它通常更短,更優雅的腳本,運行速度更快,並且用戶在執行過程中無法將其分開。下面的腳本與上面的腳本相同:它選擇第一個文本行並用該標題保存文檔。第1行定義在哪裏保存的文件夾:
set myPath to (path to desktop folder) as string -- path where to save file
tell application "TextEdit"
activate
tell front document
set myTitle to first paragraph
set myTitle to text 1 thru -2 of myTitle -- to remove the return at end of paragraph
save in (myPath & myTitle)
end tell
end tell
我希望它能幫助
只需使用「另存爲」命令提供的名稱和路徑。 – pbell
該名稱在剪貼板上。我想通過這種方式自動命名。 – Jimmbo