此解决方案使用jackjr300在他的回答中编写的代码: Is it possible to keystroke special characters in AppleScript?
使用Xcode,我创建了命令行工具 TypeCharacters
并将其复制到/usr/local/bin/
然后我将其合并到以下示例 AppleScript 代码中:
set the clipboard to "Русские персонажи & 日本語の文字"
set thisText to the clipboard
tell application "Safari" to activate
delay 0.5
my typeCharactersOf(thisText)
to typeCharactersOf(thisString)
set theStringList to characters of thisString
repeat with thisCharacter in theStringList
do shell script ¬
"/usr/local/bin/TypeCharacters " & ¬
quoted form of thisCharacter
delay (random number from 0.05 to 0.25)
end repeat
end typeCharactersOf
其输出是:
![在此处输入图像描述](https://i.stack.imgur.com/Q2vCP.jpg)
笔记:
我使用谷歌翻译将“俄语字符”翻译成俄语,Русские персонажи,将“日语字符”翻译成日语,日本语の文字。
通过将本网站上的Safari写入答案文本框进行测试,无论输入源设置为什么,结果都是相同的。
上面显示的示例 AppleScript 代码在macOS Catalina下的脚本编辑器中进行了测试,系统偏好设置中 的语言和区域设置设置为英语(美国)——系统偏好设置>键盘>输入源中的主要和两个输入源,美国和俄语,以及为我工作,没有问题1。
- 1 假设系统偏好设置>安全和隐私>隐私中的必要和适当设置已根据需要进行设置/解决。
链接答案中用于在Xcode中创建命令行工具 的代码:TypeCharacters
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
if (argc > 1) {
NSString *theString = [NSString stringWithUTF8String:argv[1]];
UniChar uChar;
CGEventRef keyEvent = CGEventCreateKeyboardEvent(nil, 0, true);
for (int i = 0; i < [theString length]; i++)
{
uChar = [theString characterAtIndex:i];
CGEventKeyboardSetUnicodeString(keyEvent, 1, &uChar);
CGEventPost(kCGHIDEventTap, keyEvent); // key down
CGEventSetType(keyEvent, kCGEventKeyUp);
CGEventPost(kCGHIDEventTap, keyEvent); // key up (type the character)
CGEventSetType(keyEvent, kCGEventKeyDown);
[NSThread sleepForTimeInterval:0.001]; // wait 1/1000 of second, no need of this line on my computer, I use 0.001 to be safe, increase it If you still have issues
}
CFRelease(keyEvent);
}
}
return 0;
}
注意:示例 AppleScript 代码就是这样,并且没有任何包含的错误处理,不包含任何可能适当的额外错误处理。用户有责任根据需要或需要添加任何错误处理。查看AppleScript 语言指南中的try 语句和错误 语句。另请参阅处理错误。此外,在适当的情况下,可能需要在事件之间使用延迟命令,例如,使用延迟的值 delay 0.5
适当设置。