【发布时间】:2022-07-07 14:39:03
【问题描述】:
问题:
我们有一个用 C# 编写的应用程序,它使用 UIAutomation 来获取其他应用程序(Word、OpenOffice、记事本等)中的当前文本(选择的文本或括号后面的词)。
在 Windows 10 上一切正常,甚至到 21H2,今天完成了最后一次更新检查。 但是我们有几个客户通知我们,该应用程序在 Windows 11 上突然关闭。
经过一些调试后,我发现在尝试使用 TextPatternRange.GetText() 方法时抛出了一些 System.AccessViolationException:
System.AccessViolationException: '试图读取或写入受保护的内存。这通常表明其他内存已损坏。'
到目前为止我们所做的尝试:
- 在清单中设置 uiaccess=true 并对应用程序进行签名:如此处提到的https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/350ceab8-436b-4ef1-8512-3fee4b470c0a/problem-with-manifest-and-uiaccess-set-to-true?forum=windowsgeneraldevelopmentissues => 没有变化(应用程序位于 C:\Program Files\
- 除了上述之外,我确实尝试在清单中将级别设置为“requireAdministrator”,也没有任何更改
- 我发现它可能来自 Windows 11 中的错误 (https://forum.emclient.com/t/emclient-9-0-1317-0-up-to-9-0-1361-0-password-correction-crashes-the-app/79904),我尝试安装 22H2 预览版,但仍然没有任何变化。
可重复的示例
为了能够隔离问题(并检查导致异常的不是我们应用程序中的其他问题),我迅速进行了以下测试(基于: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