I have the code below to get the currently selected text from the foreground application, but it only works with some apps. It works with Terminal and TextEdit, but doesn't work with Mail, Safari etc. I get stringSelection3 error -25212.
Do I have to resort to some kind of Pasteboard hack to force them to copy their selection to the clipboard, or is there a way to get it to work with these other apps through the accessibility
APIs?
+(NSString *)stringSelection; {
NSString *rtn = nil;
if (AXAPIEnabled()) {
AXError error = 0;
AXUIElementRef systemWide = AXUIElementCreateSystemWide();
AXUIElementRef app = nil;
if ((error = AXUIElementCopyAttributeValue(systemWide, kAXFocusedApplicationAttribute, (CFTypeRef *) &app)) != kAXErrorSuccess) {
[[ErrorLog log] error:@"stringSelection1: AXError: %d", error];
} else {
AXUIElementRef attr = nil;
if ((error = AXUIElementCopyAttributeValue(app, kAXFocusedUIElementAttribute, (CFTypeRef *)&attr)) != kAXErrorSuccess) {
[[ErrorLog log] error:@"stringSelection3: AXError: %d", error];
} else {
CFTypeRef value = nil;
if ((error = AXUIElementCopyAttributeValue(attr, kAXSelectedTextAttribute, &value)) != kAXErrorSuccess) {
[[ErrorLog log] error:@"stringSelection3: AXError: %d", error];
} else {
rtn = [(id)value description];
CFRelease(value);
}
CFRelease(attr);
}
CFRelease(app);
}
}
return rtn;
}