在尝试了两个月之后,我发现了如何从 TextEdit(或任何 NSTextView)的任何文本范围中获取 AttributedString。我的代码如下:
AXUIElementRef systemWideElement = AXUIElementCreateSystemWide();
AXUIElementRef focussedElement = NULL;
AXError error = AXUIElementCopyAttributeValue(systemWideElement,
kAXFocusedUIElementAttribute, (CFTypeRef*)&focussedElement);
if (error != kAXErrorSuccess) {
println("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 attributedString = NULL;
AXError getAttrStrError =
AXUIElementCopyParameterizedAttributeValue(focussedElement,
kAXAttributedStringForRangeParameterizedAttribute, selectedRangeValue,
(CFTypeRef*)&attributedString);
CFRelease(selectedRangeValue);
if (getAttrStrError == kAXErrorSuccess)
{
CFAttributedStringRef attrStr = (CFAttributedStringRef)attributedString;
CFTypeRef value = CFAttributedStringGetAttribute(
attrStr, 0, kAXFontTextAttribute, NULL);
println("value: %X", value); // value is not NULL, but I can't obtain font name from it.
CFRelease(attributedString);
}
else
{
println("Could not get attributed string for selected range");
}
}
else {
println("Could not get selected range");
}
}
if (focussedElement != NULL)
CFRelease(focussedElement);
CFRelease(systemWideElement);
我正确获得了 CFAttributedStringRef (我可以从中获得长度或纯文本),但我无法获得字体名称。
笔记:
代码下方返回的值不为 NULL:
CFTypeRef value = CFAttributedStringGetAttribute(
attrStr, 0, kAXFontTextAttribute, NULL);
该值不能假定为 CTFontRef 或 CGFontRef、ATSFontRef、...(导致异常)。
我也尝试使用 kCTFontAttributeName 而不是 kAXFontTextAttribute,但返回 NULL。
非常感谢。