2010-07-02 79 views
5

我正在测试下面的示例代码,并且每当我尝试运行它时,我都会遇到下面显示的错误。但是,calc.exe进程执行成功,那么句柄如何可能为null或零?我希望你明白我想表达的意思。谢谢!该代码样品来自http://www.mathpirate.net/log/tag/system-windows-automation/Windows用户界面自动化

类型 “System.ArgumentException”的未处理的异常发生在 UIAutomationClient.dll 其他信息:HWND不能IntPtr.Zero或空。

//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); 
} 

回答

2

你误会WaitForInputIdle(这是什么功能目前做了窘况坏名)。在主窗口创建之前,您正在询问主窗口的地址。因此,最终会将无效的窗口句柄传递给其他函数。

编辑:我会强烈建议使用一个UI自动化库,如white,如果你要做的严肃的工作。

+0

如果您使用的是白色,请注意它有几个问题;我发现那些对我目前的项目非常重要。你可以在http://white.codeplex.com/workitem/list/basic – 2010-07-02 02:53:35

+0

看到白色问题列表,这是一个推荐的想法,使用UI自动化进行监控? 我有一个第三方应用程序,其中我想要监视的值和基于这些值,我想要执行一些操作,即UI操作,单击按钮,更改文本字段值等。 至于监视值,我必须单独监视每个控件吗? 谢谢! – user303907 2010-07-02 05:53:07