You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过UiAutomation获取LegacyIAccessible数据?

获取LegacyIAccessible属性及UIA缓存机制说明

一、解决get_CurrentState报错并获取LegacyIAccessible属性

你遇到的class "IUIAutomationElement" has no member "get_CurrentState"错误,是因为State属于LegacyIAccessible模式下的属性,不能直接通过IUIAutomationElement调用,必须先获取IUIAutomationLegacyIAccessiblePattern接口,再通过该接口读取对应属性。

修改后的代码示例

在你的遍历循环中加入以下逻辑,即可获取LegacyIAccessible相关属性:

for (int nItem = 0; nItem <= nNbItems - 1; nItem++)
{
    IUIAutomationElement* pElement = nullptr;
    hr = pEA->GetElement(nItem, &pElement);
    if (FAILED(hr) || !pElement) continue;

    // 原有属性读取逻辑(Name、HWND等)...

    // 获取LegacyIAccessible模式接口
    IUIAutomationLegacyIAccessiblePattern* pLegacyPattern = nullptr;
    hr = pElement->GetCurrentPattern(UIA_LegacyIAccessiblePatternId, reinterpret_cast<IUnknown**>(&pLegacyPattern));
    if (SUCCEEDED(hr) && pLegacyPattern)
    {
        // 读取State属性
        DWORD currentState = 0;
        if (SUCCEEDED(pLegacyPattern->get_CurrentState(&currentState)))
        {
            // 此处可处理state值,比如打印或存储
        }

        // 可选:读取其他LegacyIAccessible属性,比如Value、Role等
        BSTR legacyValue = nullptr;
        if (SUCCEEDED(pLegacyPattern->get_CurrentValue(&legacyValue)))
        {
            // 处理value数据
            SysFreeString(legacyValue);
        }

        pLegacyPattern->Release();
    }

    pElement->Release();
}

如果要结合缓存机制优化性能,需在创建CacheRequest时添加LegacyIAccessible模式:

hr = pUIAutomation->CreateCacheRequest(&pCacheRequest);
// 添加需要缓存的属性
pCacheRequest->AddProperty(UIA_NamePropertyId);
pCacheRequest->AddProperty(UIA_AutomationIdPropertyId);
pCacheRequest->AddProperty(UIA_LocalizedControlTypePropertyId);
// 将LegacyIAccessible模式加入缓存
pCacheRequest->AddPattern(UIA_LegacyIAccessiblePatternId);

之后在遍历中用GetCachedPattern替代GetCurrentPattern,避免重复跨进程交互:

hr = pElement->GetCachedPattern(UIA_LegacyIAccessiblePatternId, reinterpret_cast<IUnknown**>(&pLegacyPattern));

二、缓存(Cache)与非缓存方式的区别

  • 非缓存方式(GetCurrentXXX/GetCurrentPattern):

    • 每次调用都会实时从目标控件所在进程获取最新的属性/模式数据,保证数据是当前最新状态。
    • 缺点是频繁调用会产生跨进程通信开销,遍历大量元素时性能较低。
  • 缓存方式(GetCachedXXX/GetCachedPattern):

    • 在调用FindAllBuildCache或BuildCache时,一次性将指定的属性、模式批量缓存到本地内存中。
    • 后续读取直接从本地缓存获取,无需再和目标进程交互,批量遍历场景下性能大幅提升。
    • 缺点是缓存的数据是快照,不会自动更新,适合不需要实时数据的场景。

内容的提问来源于stack exchange,提问作者Cesar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 12:54:23