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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With