代码之家  ›  专栏  ›  技术社区  ›  Krishna Maru

从Mac中的Pages应用程序的当前光标位置获取文本

  •  1
  • Krishna Maru  · 技术社区  · 6 年前

    是否可以从当前光标位置获取Pages应用程序的文本? 我的要求是,当用户在“页面”中键入某些内容时,我必须为他们键入的单词显示建议。

    所以我想从“页面”应用程序中找到当前或最后一个单词,靠近当前光标位置。 使用AppleScript或Accessibility? 未选择文本。 我也不想找“服务”。 对于“页面”以外的应用程序,我使用了可访问性和appleScript。但我找不到任何方法。

    我也尝试过下面的AppleScript,但是由于某些原因,它在“脚本编辑器”中工作得很好,但是当我在代码中使用它时,它会进入无限循环。

    tell application "Pages"
        activate
    end tell
    tell application "System Events"
        tell application "System Events"
            key code 123 using {shift down, command down} -- shift-command-left
        end tell
        tell process "Pages"
            keystroke "c" using {command down}
            delay 1
            tell application "System Events"
                key code 124 -- shift-command-left
            end tell
            set myData to (the clipboard) as text
            return myData
        end tell
    end tell
    

    如果我在我的应用程序中运行这个AppleScript,它只会冻结我的Mac,我必须强制退出Mac来停止它。

    1 回复  |  直到 6 年前
        1
  •  2
  •   wch1zpink    6 年前

    这对我使用最新版本的macOS Mojave和Pages很有用

    property theApp : "Pages" -- change value to name of any other application (TextEdit)
    
    tell application theApp to activate
    delay 3
    tell application "System Events"
        tell application process theApp
            -- Move the insertion point to the beginning of the previous word.
            key code 123 using {option down} -- left arrow key while holding option down
            delay 0.2
            -- Move the insertion point to the end of the next word. (selects the word)
            key code 124 using {shift down, option down} -- right arrow key while holding option and shift down
            delay 0.2
            keystroke "c" using {command down} -- copies selected wprd 
            delay 0.2
            -- Next 2 key code commands attempt to restore cursor location  
            key code 124 using {option down} -- right arrow key while holding option down
            delay 0.2
            key code 123 using {option down} -- left arrow key while holding option down
            tell current application to set myData to (the clipboard) as text
            delay 4
            return myData
        end tell
    end tell