c# - Windows 用户界面自动化

标签 c# user-interface automation

我正在测试以下示例代码,不知何故每当我尝试运行它时,都会出现如下所示的错误。但是,calc.exe 进程执行成功了,那么句柄怎么可能为空或零呢?我希望你明白我想表达的意思。谢谢!代码示例来自http://www.mathpirate.net/log/tag/system-windows-automation/

An unhandled exception of type 'System.ArgumentException' occurred in UIAutomationClient.dll Additional information: hwnd cannot be IntPtr.Zero or null.

//Launches the Windows Calculator and gets the Main Window's Handle.
Process calculatorProcess = Process.Start("calc.exe");
calculatorProcess.WaitForInputIdle();
IntPtr calculatorWindowHandle = calculatorProcess.MainWindowHandle;

//Here I use a window handle to get an AutomationElement for a specific window.
AutomationElement calculatorElement = AutomationElement.FromHandle(calculatorWindowHandle);

if(calculatorElement == null)
{
    throw new Exception("Uh-oh, couldn't find the calculator...");
}

//Walks some of the more interesting properties on the AutomationElement.
Console.WriteLine("--------Element");
Console.WriteLine("AutomationId: {0}", calculatorElement.Current.AutomationId);
Console.WriteLine("Name: {0}", calculatorElement.Current.Name);
Console.WriteLine("ClassName: {0}", calculatorElement.Current.ClassName);
Console.WriteLine("ControlType: {0}", calculatorElement.Current.ControlType.ProgrammaticName);
Console.WriteLine("IsEnabled: {0}", calculatorElement.Current.IsEnabled);
Console.WriteLine("IsOffscreen: {0}", calculatorElement.Current.IsOffscreen);
Console.WriteLine("ProcessId: {0}", calculatorElement.Current.ProcessId);

//Commented out because it requires another library reference. However, it's useful to see that this exists.
//Console.WriteLine("BoundingRectangle: {0}", calculatorElement.Current.BoundingRectangle);

Console.WriteLine("Supported Patterns:");
foreach (AutomationPattern supportedPattern in calculatorElement.GetSupportedPatterns())
{
    Console.WriteLine("\t{0}", supportedPattern.ProgrammaticName);
}

最佳答案

你误会了WaitForInputIdle (对于该功能当前的功能来说,这是一个非常糟糕的名称)。您甚至在创建主窗口之前就询问了主窗口的地址。结果,您最终将无效的窗口句柄传递给其他函数。

编辑:我强烈建议使用 UI 自动化库,例如 white如果您要认真地使用它。

关于c# - Windows 用户界面自动化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3162958/

相关文章:

android - 如何让一个TextView有多行?

c# - "Debug only"只应在 "turned on"时运行的代码

c# - 在 View 中访问 session 变量

c# - 如何在 SharePoint 2013 中使用 REST API 将附件文件附加到列表项

mysql - 在 shell 脚本中提供 mysql 命令

html - 自动化 (IE ComObject) 填充文本框

testing - 如何按特定顺序在 robotframework 中执行 TEST SUITES?

c# - 这是实现线程安全读/写 Guid 属性的正确方法吗?

Java CardLayout : Is it possible to use same object on two different cards?

android - 从服务访问 UI 线程处理程序