How to insert text at cursor position of another application on Mac OSX Application (like OSK)?

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-02 08:26:15

问题


I'm trying to create an OSX application which would be a replica of On Screen keyboard. Is it possible to insert some text into the cursor position of another active application? Thanks in advance!


回答1:


It is possible. Accessibility enables to change content of other applications, but your app can't be sandboxed and thus not available via 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);
}

This code does not check for errors and makes assumption that focused element is text area.




回答2:


Not sure if this helps, but in Applescript you can do something like

tell application "System Events"
    keystroke "Stuff here"
end tell

So maybe you can try call that within cocoa using NSApplescript or using NSTask and run

osascript -e 'tell application "System Events" to keystroke "Stuff here"'


来源:https://stackoverflow.com/questions/16272717/how-to-insert-text-at-cursor-position-of-another-application-on-mac-osx-applicat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!