Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically select text range in TextEdit

Is it possible to select (Highlight) a range of text in TextEdit (by AppleScript,Cocoa or Carbon)? I tryed this code but not work:

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

It seems this attribute is readonly. Thanks.

like image 866
mh taqia Avatar asked Sep 16 '25 05:09

mh taqia


1 Answers

Not sure how to do it with AppleScript (should be possible though), with the accessibility APIs, you could 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);

That would select the first 10 characters if the TextEdit window is focussed.

like image 106
omz Avatar answered Sep 18 '25 19:09

omz