【问题标题】:UIAutomation throws AccessViolationException on Windows 11UIAutomation 在 Windows 11 上引发 AccessViolationException
【发布时间】:2022-07-07 14:39:03
【问题描述】:

问题:

我们有一个用 C# 编写的应用程序,它使用 UIAutomation 来获取其他应用程序(Word、OpenOffice、记事本等)中的当前文本(选择的文本或括号后面的词)。

在 Windows 10 上一切正常,甚至到 21H2,今天完成了最后一次更新检查。 但是我们有几个客户通知我们,该应用程序在 Windows 11 上突然关闭。

经过一些调试后,我发现在尝试使用 TextPatternRange.GetText() 方法时抛出了一些 System.AccessViolationException:

System.AccessViolationException: '试图读取或写入受保护的内存。这通常表明其他内存已损坏。'

到目前为止我们所做的尝试:

可重复的示例

为了能够隔离问题(并检查导致异常的不是我们应用程序中的其他问题),我迅速进行了以下测试(基于:How to get selected text of currently focused window? 验证答案)

private void btnRefresh_Click(object sender, RoutedEventArgs e)
    {
        var p = Process.GetProcessesByName("notepad").FirstOrDefault();
        var root = AutomationElement.FromHandle(p.MainWindowHandle);

        var documentControl = new
                PropertyCondition(AutomationElement.ControlTypeProperty,
                                  ControlType.Document);

        var textPatternAvailable = new PropertyCondition(AutomationElement.IsTextPatternAvailableProperty, true);

        var findControl = new AndCondition(documentControl, textPatternAvailable);

        var targetDocument = root.FindFirst(TreeScope.Descendants, findControl);
        var textPattern = targetDocument.GetCurrentPattern(TextPattern.Pattern) as TextPattern;

        string text = "";
        foreach (var selection in textPattern.GetSelection())
        {
            text += selection.GetText(255);
            Console.WriteLine($"Selection: \"{selection.GetText(255)}\"");
        }

        lblFocusedProcess.Content = p.ProcessName;
        lblSelectedText.Content = text;
    }

按下按钮时,会调用此方法并将结果显示在标签中。 该方法使用 UIAutomation 获取记事本进程并提取所选文本。

这在具有最新更新的 Windows 10 中运行良好,在 Windows 11 上立即崩溃并出现 AccessViolationException。 在 Windows 10 上,即使清单中没有 uiaccess=true 设置,它也可以工作。

问题/后续步骤

有没有人知道/知道是什么原因造成的? Windows 11 是否更倾向于 UIAutomation?

在我这边,我可能会打开 Microsoft 的问题。 我们可能会遵循的一条途径是获得 EV 并签署应用程序本身和安装程序,因为它还将增强安装过程,消除大红色警告。但由于这是一个免费分发的应用程序,我们没有这样做,因为它在没有它的情况下也能正常工作。

我还将继续使用可重现的代码进行测试,并在出现任何新问题时更新此问题。

【问题讨论】:

    标签: c# selection ui-automation uiaccessibility windows-11


    【解决方案1】:

    我在 MSDN 论坛上发布了同样的问题并得到了这个答案: https://docs.microsoft.com/en-us/answers/questions/915789/uiautomation-throws-accessviolationexception-on-wi.html

    使用 IUIautomation 代替 System.Windows.Automation 在 Windows 11 上工作。

    所以我将其标记为已解决,但如果有人有其他想法或知道会发生什么,欢迎您发表评论!

    【讨论】: