如何在Mac OSX应用程序(如OSK)上的另一个应用程序的光标位置插入文本?

Sel*_*vin 3 macos cocoa on-screen-keyboard

我正在尝试创建一个OSX应用程序,它将是On Screen键盘的副本.是否可以将一些文本插入另一个活动应用程序的光标位置?提前致谢!

Mir*_*vik 6

有可能的.辅助功能可以更改其他应用程序的内容,但您的应用程序无法进行沙盒处理,因此无法通过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);
}
Run Code Online (Sandbox Code Playgroud)

此代码不检查错误并假设聚焦元素是文本区域.


The*_*mer 2

不确定这是否有帮助,但在 Applescript 中你可以做类似的事情

tell application "System Events"
    keystroke "Stuff here"
end tell
Run Code Online (Sandbox Code Playgroud)

所以也许你可以尝试在可可中使用NSApplescript或使用NSTask并运行来调用它

osascript -e 'tell application "System Events" to keystroke "Stuff here"'
Run Code Online (Sandbox Code Playgroud)