V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Wqr2048
V2EX  ›  macOS

AppleScript 使用 keystroke 时无法输入中文

  •  
  •   Wqr2048 · May 29, 2020 · 3872 views
    This topic created in 2169 days ago, the information mentioned may be changed or developed.

    执行 tell application "System Events" to keystroke "你我他 123efg"
    会打出 aaa123efg

    类似的 执行 tell application "System Events" to keystroke "Русский & abcdefg"
    会打出 aaaaaaa & abcdefg

    看少数派的教程的话keystroke这个命令是支持非 ascii 字符的, 不知道为啥所有非 ascii 字符都被替换成了 'a'

    系统版本 10.15.5

    7 replies    2022-04-08 11:12:46 +08:00
    fatestigma
        1
    fatestigma  
       May 29, 2020
    keystroke 本身需要 map 到键盘上的实际键吧,除非有每个汉字一个键的键盘布列,否则应该是不支持的。。
    workaround:可以先把文字保存到剪切板,然后 keystroke "v" using command down 粘贴进去,事前可以临时保存一下剪贴板,事后恢复
    fatestigma
        2
    fatestigma  
       May 29, 2020
    set _clipboard to get the clipboard
    set the clipboard to "你我他 123efg"
    tell application "System Events" to keystroke "v" using command down
    set the clipboard to _clipboard
    Wqr2048
        3
    Wqr2048  
    OP
       May 29, 2020
    @fatestigma
    因为一个奇葩的场景需要把字符一个一个打进去才搞的这种奇怪操作...
    不过开来 keystroke 确实是不支持非 ascii 字符了

    感谢你的解答!!
    Wqr2048
        4
    Wqr2048  
    OP
       May 29, 2020
    @Wqr2048 想到了折中的解决办法了 再次感谢~
    fatestigma
        5
    fatestigma  
       May 29, 2020
    @Wqr2048 #3 这样啊,那你要不看下 keyboardSetUnicodeString(stringLength:unicodeString:),好像可以用 AppleScriptObjC 来调用
    LudwigWS
        6
    LudwigWS  
       Jun 1, 2020
    @fatestigma 这个有点神奇,Mark
    isaced
        7
    isaced  
       Apr 8, 2022
    通过剪贴板可以实现一个一个字符的敲击效果:

    tell application "System Events"
    set textBuffer to "你好!"
    repeat with i from 1 to count characters of textBuffer
    set the clipboard to (character i of textBuffer)
    delay 0.05
    keystroke "v" using command down
    end repeat
    end tell
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   917 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 21:44 · PVG 05:44 · LAX 14:44 · JFK 17:44
    ♥ Do have faith in what you're doing.