AppleScript 使用 keystroke 时无法输入中文

2020-05-29 22:38:40 +08:00
 Wqr2048

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

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

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

系统版本 10.15.5

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

感谢你的解答!!
Wqr2048
2020-05-29 23:12:53 +08:00
@Wqr2048 想到了折中的解决办法了 再次感谢~
fatestigma
2020-05-29 23:15:51 +08:00
@Wqr2048 #3 这样啊,那你要不看下 keyboardSetUnicodeString(stringLength:unicodeString:),好像可以用 AppleScriptObjC 来调用
LudwigWS
2020-06-01 23:36:27 +08:00
@fatestigma 这个有点神奇,Mark
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

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/676847

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX