【问题标题】:AppleScript clipboard race conditionAppleScript 剪贴板竞争条件
【发布时间】:2014-05-14 05:55:08
【问题描述】:

我想使用 AppleScript 将一些文本粘贴到当前应用程序中,同时保留剪贴板中已有的内容。

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")

当我在运行此脚本时剪贴板上有old text 时,我会收到以下事件日志并粘贴old 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 clipboard race-condition


    【解决方案1】:

    标准加法词典说:

    set the clipboard to v : Place data on an application’s clipboard. Use inside a ‘tell’ block and activate the application first.(链接到 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")
    

    为了安全,我还是会加一点延迟。

    【讨论】:

    • 我最终使用 pbcopypbpaste 来保留剪贴板,并且只使用 Applescript 进行粘贴击键。
    猜你喜欢
    • 2022-01-23
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多