Programmatically select a text range in TextEdit

Is it possible to select (highlight) a range of text in TextEdit (via AppleScript, Cocoa or Carbon)? I tried this code but did not work:

set value of attribute "AXSelectedTextRange" to {selStart, selLen}

This attribute seems to be read-only. Thank.

+3
source share
1 answer

Not sure how to do this with AppleScript (should be possible), with accessibility APIs you can do something like this:

AXUIElementRef systemWideElement = AXUIElementCreateSystemWide();
AXUIElementRef focussedElement = NULL;
AXError error = AXUIElementCopyAttributeValue(systemWideElement, kAXFocusedUIElementAttribute, (CFTypeRef *)&focussedElement);
CFRange range = CFRangeMake(0, 10);
AXUIElementSetAttributeValue(focussedElement, kAXSelectedTextRangeAttribute, AXValueCreate(kAXValueCFRangeType, &range));
CFRelease(focussedElement);
CFRelease(systemWideElement);

This will select the first 10 characters if the TextEdit window is highlighted.

+3
source

All Articles