AppleScript剪贴板竞争条件
我想使用AppleScript将一些文本粘贴到当前应用程序中,同时保留剪贴板中先前存在的内容AppleScript剪贴板竞争条件,applescript,clipboard,race-condition,Applescript,Clipboard,Race Condition,我想使用AppleScript将一些文本粘贴到当前应用程序中,同时保留剪贴板中先前存在的内容 on writeFromClipboard(someText) set oldClipboard to the clipboard log oldClipboard set the clipboard to someText log (the clipboard) tell application "System Events" keystroke
on writeFromClipboard(someText)
set oldClipboard to the clipboard
log oldClipboard
set the clipboard to someText
log (the clipboard)
tell application "System Events"
keystroke "v" using {command down}
end tell
log (the clipboard)
set the clipboard to oldClipboard
end writeFromClipboard
writeFromClipboard("new text")
运行此脚本时,如果剪贴板上有旧文本
,我将获得以下事件日志并粘贴旧文本
。我只能得出结论,文本实际上是在剪贴板内容被更改回来后粘贴的
tell application "AppleScript Editor"
the clipboard
--> "old text"
end tell
(*old text*)
tell application "AppleScript Editor"
set the clipboard to "new text"
the clipboard
--> "new text"
end tell
(*new text*)
tell application "System Events"
keystroke "v" using {command down}
end tell
tell application "AppleScript Editor"
the clipboard
--> "new text"
end tell
(*new text*)
tell application "AppleScript Editor"
set the clipboard to "old text"
end tell
除了在“粘贴”按键后添加暂停之外,还有什么方法可以让它工作吗?标准的“添加”字典说: (链接到AppleScript Wiki) 试着这样做:
on writeFromClipboard(someText)
tell application "TextEdit"
activate
set oldClipboard to the clipboard
set the clipboard to someText
--delay 0.2
tell application "System Events" to tell process "TextEdit"
keystroke "v" using {command down}
end tell
set the clipboard to oldClipboard
end tell
end writeFromClipboard
writeFromClipboard("new text")
为了安全起见,我仍然会增加一点延迟。我最后使用
pbcopy
和pbpaste
来保留剪贴板,并且只使用Applescript进行粘贴按键。