2010-07-02 86 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