title: Windows UI Automation
body: <p>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 <a href="http://www.mathpirate.net/log/tag/system-windows-automation/" rel="noreferrer">http://www.mathpirate.net/log/tag/system-windows-automation/</a></p>
  
  <blockquote>
    <p>An unhandled exception of type
    'System.ArgumentException' occurred in
    UIAutomationClient.dll
    Additional information: hwnd cannot be IntPtr.Zero or null.</p>
  </blockquote>
  
  <pre><code>//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);
  }
  </code></pre>