如何在Mac OSX应用程序(如OSK)上的其他应用程序的光标位置插入文本?
问题描述:
我正在尝试创建一个OSX应用程序,它将成为屏幕键盘的复制品。是否可以将某些文本插入到另一个活动应用程序的光标位置?提前致谢!如何在Mac OSX应用程序(如OSK)上的其他应用程序的光标位置插入文本?
答
不知道这是否会有所帮助,但在AppleScript的,你可以这样做
tell application "System Events"
keystroke "Stuff here"
end tell
因此,也许你可以尝试调用使用NSApplescript
或使用NSTask
可可内运行
osascript -e 'tell application "System Events" to keystroke "Stuff here"'
+0
这也不适用于Mac App Store,因此您最好澄清一下。 – SevenBits 2014-02-26 13:41:13
答
这是可能。辅助功能可以更改其他应用程序的内容,但是您的应用程序不能被沙箱化,因此无法通过AppStore访问。
CFTypeRef focusedUI;
AXUIElementCopyAttributeValue(AXUIElementCreateSystemWide(), kAXFocusedUIElementAttribute, &focusedUI);
if (focusedUI) {
CFTypeRef textValue, textRange;
// get text content and range
AXUIElementCopyAttributeValue(focusedUI, kAXValueAttribute, &textValue);
AXUIElementCopyAttributeValue(focusedUI, kAXSelectedTextRangeAttribute, &textRange);
NSRange range;
AXValueGetValue(textRange, kAXValueCFRangeType, &range);
// replace current range with new text
NSString *newTextValue = [(__bridge NSString *)textValue stringByReplacingCharactersInRange:range withString:newText];
AXUIElementSetAttributeValue(focusedUI, kAXValueAttribute, (__bridge CFStringRef)newTextValue);
// set cursor to correct position
range.length = 0;
range.location += text.length;
AXValueRef valueRef = AXValueCreate(kAXValueCFRangeType, (const void *)&range);
AXUIElementSetAttributeValue(focusedUI, kAXSelectedTextRangeAttribute, valueRef);
CFRelease(textValue);
CFRelease(textRange);
CFRelease(focusedUI);
}
此代码不检查错误,并假定焦点元素是文本区域。
仅供参考,以防万一:答案(无论细节,对不起,我不知道它们)是一个*合格*是 - 例如,这是辅助软件的工作原理。 *但是*在沙箱下,因此在App Store中,一般的答案肯定是否定的 - 输入到另一个应用程序可能是一个严重的安全问题。当然,如果您的应用程序不在沙箱中,那么它的限制就不会有问题。 – CRD 2013-04-29 18:55:21
@CRD沙盒的含义是什么。你的意思是说,如果我提交应用程序到appstore它不会工作?但作为一名苹果开发人员,我可以在我的系统中运行这个应用程序?你可以请详细说明..谢谢。 – Selvin 2013-04-30 09:01:37
应用程序沙箱是一个安全系统,它限制了应用程序可以执行的操作 - 可以访问哪些文件,是否可以进行网络连接等。所有iOS应用程序都是沙盒,对于OS X,它是可选的。但是,所有在Mac App Store中销售的应用程序都必须进行沙盒处理。在Apple文档中查找App Sandbox了解详细信息。 – CRD 2013-04-30 10:13:32