为什么这个工作不是来自其他类或子类?

时间:2014-09-11 08:57:15

标签: cocoa

我试图获得系统选择文本的边界,我在这里找到了这个方法:

+ (void) getPosition{
    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);
}

但是,如果我从appDelegate.m类以外的任何地方调用它,它总是返回:

Could not get focussed element

我错过了什么设置?

或者是否有其他人知道如何获得系统选择的文字位置?

2 个答案:

答案 0 :(得分:1)

您不应该将focussedvalue(实际拼写为focusedvalue)初始化为AXUIElementRef,然后在将其作为参数传递给AXUIElementCopyAttributeValue时进行类型转换。<登记/> 而是将其初始化为CFTypeRef

试试看,并在此处查看示例代码以供参考: https://developer.apple.com/library/mac/samplecode/UIElementInspector/Listings/UIElementUtilities_m.html#//apple_ref/doc/uid/DTS10000728-UIElementUtilities_m-DontLinkElementID_14

答案 1 :(得分:0)

所以我找到了一种从我的App Delegate.m文件定位窗口的方法,所以我的想法是,如果我无法将Bounds放入我的自定义类,我从AppDelegate.m文件中取出它们并将Window放在里面好吧,很好的想法,但是,无论我做什么,我都会收到2Could not get Selection Range&#34;错误消息,代码再一次-25212,这整个东西很糟糕......

我在Cocoa中必须处理的一个令人毛骨悚然的部分...

相关问题