AutomationElement.FromHandle(IntPtr Handle) stops the application

1.6k Views Asked by At
private string GetCurrentChromeUrl()
    {
        try
        {
            string url = null;

            int handle = GetForegroundWindow();
            AutomationElement elm = AutomationElement.FromHandle((IntPtr)handle);
            AutomationElement elmUrlBar = elm.FindFirst(TreeScope.Descendants,
                  new PropertyCondition(AutomationElement.NameProperty, "Address and search bar"));
            if (elmUrlBar != null)
            {
                AutomationPattern[] patterns = elmUrlBar.GetSupportedPatterns();
                if (patterns.Length > 0)
                {
                    ValuePattern val = (ValuePattern)elmUrlBar.GetCurrentPattern(patterns[0]);
                    url = val.Current.Value;
                    //break;
                }
            }
            return url;
        }
        catch (Exception e1)
        {
            return "";
        }
   }

I'm trying to find the URL from google chrome browser.

And I'm using above code. It is work good in other application but in my case it stops my application.

But the main issue is that it will work fine when I'm debugging it, so what wrong when no debugging.

please give your solutions.

thanx in advance

1

There are 1 best solutions below

0
On

I'm passing through this, it happen cause of the intptr type, it depends of the build of the machine, sometime the windowhandle is too big for an intptr of a 32bits machine.