Windows UIAutomation 有时会挂起其他应用程序

Windows UIAutomation sometimes hangs other apps

我在 WPF 客户端应用程序中通过 COM 接口使用 UIAutomation。有些用户有时会挂起他们的特定应用程序(如 nVidia 控制面板)。我的应用收到该异常:

System.Runtime.InteropServices.COMException (0x80131505): Operation timed out. (Exception from HRESULT: 0x80131505) in UIAutomationClient.IUIAutomationElement.FindAll (TreeScope scope, IUIAutomationCondition condition).

我无法在我的 PC 上重现此内容。

我找到了一些关于这个问题的信息。

  • UIAutomation 仅在 Windows 10 与创作者更新 (source)
  • 上不稳定
  • 这是错误,已提交 here
  • NickAb 找到了解决方案:使用 TreeWalker (source)

Both FindAll and FindFirst are prone to this exception, which is raised when trying to find elements in WebView that has loaded its data recently, exception is thrown when methods try to build cache, so it might be due to trying to iterate visual tree while it is being rebuild by another thread.

Replacing FindAll with

private IEnumerable<WiniumElement> GetChildrens()
{
    var elementNode = TreeWalker.ControlViewWalker.GetFirstChild(this.AutomationElement);

    while (elementNode != null)
    {
        yield return new WiniumElement(elementNode);
        elementNode = TreeWalker.ControlViewWalker.GetNextSibling(elementNode);
    }
}

Solves the problem. Needs further investigation. Most likely we will have to replace both FindFirst and FindAll calls with custom TreeWalker iteration method.

This will solve the problem with not being able to get page source for views with WebViews and not being able to find element in WebView due to same error.