V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Wqr2048
V2EX  ›  macOS

AppleScript 使用 keystroke 时无法输入中文

  •  
  •   Wqr2048 · 2020-05-29 22:38:40 +08:00 · 2693 次点击
    这是一个创建于 1400 天前的主题,其中的信息可能已经有所发展或是发生改变。

    执行 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 条回复    2022-04-08 11:12:46 +08:00
    fatestigma
        1
    fatestigma  
       2020-05-29 22:58:37 +08:00
    keystroke 本身需要 map 到键盘上的实际键吧,除非有每个汉字一个键的键盘布列,否则应该是不支持的。。
    workaround:可以先把文字保存到剪切板,然后 keystroke "v" using command down 粘贴进去,事前可以临时保存一下剪贴板,事后恢复
    fatestigma
        2
    fatestigma  
       2020-05-29 23:07:35 +08:00
    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
       2020-05-29 23:11:55 +08:00
    @fatestigma
    因为一个奇葩的场景需要把字符一个一个打进去才搞的这种奇怪操作...
    不过开来 keystroke 确实是不支持非 ascii 字符了

    感谢你的解答!!
    Wqr2048
        4
    Wqr2048  
    OP
       2020-05-29 23:12:53 +08:00
    @Wqr2048 想到了折中的解决办法了 再次感谢~
    fatestigma
        5
    fatestigma  
       2020-05-29 23:15:51 +08:00
    @Wqr2048 #3 这样啊,那你要不看下 keyboardSetUnicodeString(stringLength:unicodeString:),好像可以用 AppleScriptObjC 来调用
    LudwigWS
        6
    LudwigWS  
       2020-06-01 23:36:27 +08:00
    @fatestigma 这个有点神奇,Mark
    isaced
        7
    isaced  
       2022-04-08 11:12:46 +08:00
    通过剪贴板可以实现一个一个字符的敲击效果:

    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
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2786 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 15:05 · PVG 23:05 · LAX 08:05 · JFK 11:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.