在 TextEdit 中以编程方式选择文本范围

问题描述:

是否可以在 TextEdit(通过 AppleScript、Cocoa 或 Carbon)中选择(突出显示)一系列文本?我试过这段代码但没有用:

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.

不确定如何使用 AppleScript(虽然应该可以),使用可访问性 API,您可以执行以下操作:

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);

如果 TextEdit 窗口被聚焦,这将选择前 10 个字符.

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