问题
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