3

My application is agent type (running in background) and I have a button in window. when user select some text in TextEdit and trigger an action from my application I need to get the range of selection text. I am using below code but I am getting below error

kAXErrorAttributeUnsupported

I am using below code

AXUIElementRef systemWideElement = AXUIElementCreateSystemWide();
AXUIElementRef focussedElement = NULL;
AXError error = AXUIElementCopyAttributeValue(systemWideElement, kAXFocusedUIElementAttribute, (CFTypeRef *)&focussedElement);
if (error != kAXErrorSuccess) {
    NSLog(@"Could not get focussed element");
} else {
    AXValueRef selectedRangeValue = NULL;
    AXError getSelectedRangeError = AXUIElementCopyAttributeValue(focussedElement, kAXSelectedTextRangeAttribute, (CFTypeRef *)&selectedRangeValue);
    if (getSelectedRangeError == kAXErrorSuccess) {
        CFRange selectedRange;
        AXValueGetValue(selectedRangeValue, kAXValueCFRangeType, &selectedRange);
        AXValueRef selectionBoundsValue = NULL;
        AXError getSelectionBoundsError = AXUIElementCopyParameterizedAttributeValue(focussedElement, kAXBoundsForRangeParameterizedAttribute, selectedRangeValue, (CFTypeRef *)&selectionBoundsValue);
        CFRelease(selectedRangeValue);
        if (getSelectionBoundsError == kAXErrorSuccess) {
            CGRect selectionBounds;
            AXValueGetValue(selectionBoundsValue, kAXValueCGRectType, &selectionBounds);
            NSLog(@"Selection bounds: %@", NSStringFromRect(NSRectFromCGRect(selectionBounds)));
        } else {
            NSLog(@"Could not get bounds for selected range");
        }
        if (selectionBoundsValue != NULL) CFRelease(selectionBoundsValue);
    } else {
        NSLog(@"Could not get selected range");
    }
}
if (focussedElement != NULL) CFRelease(focussedElement);
CFRelease(systemWideElement);

In above code getSelectedRangeError == kAXErrorAttributeUnsupported

Update : I am working in Sandboxed environment, Is that the reason of not working .

kulss
  • 2,057
  • 1
  • 14
  • 16

1 Answers1

0

Have you tried registering a Service instead? Services are the mechanism Apple intends to be used for modifying selected text contents from another application.

uliwitness
  • 8,532
  • 36
  • 58
  • yes this is working fine with Services, but I also need to get selection range using button action. Can I trigger Service Action by any simple button action also ? – kulss Jul 24 '17 at 11:55
  • Where is that button? In your application? In TextEdit? – uliwitness Jul 24 '17 at 12:03