简体   繁体   中英

Windows UI Automation

I was testing the follow sample code and somehow whenever I tried running it, I will have an error shown below. However, the calc.exe process was executed successfull, so how is it possible that the handle be null or zero? I hope you understand what I am trying to put across. Thanks! The code sample is from 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);
}

You're misunderstanding WaitForInputIdle (Which is a HORRENDOUSLY bad name for what that function currently does). You're asking for the address of the main window before a main window has even been created. As a result you end up passing an invalid window handle to your other functions.

EDIT: I would strongly recommend use of a UI Automation library such as white if you're going to be doing serious work with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM