使用C#获取活动的chrome网址

时间:2014-05-13 15:45:58

标签: .net google-chrome

我找到了这个解决方案:

        Process[] procsChrome = Process.GetProcessesByName("chrome");
        foreach (Process chrome in procsChrome)
        {
            // the chrome process must have a window
            if (chrome.MainWindowHandle == IntPtr.Zero)
            {
                continue;
            }

            // find the automation element
            AutomationElement elm = AutomationElement.FromHandle(chrome.MainWindowHandle);
            AutomationElementCollection elmUrlBars = elm.FindAll(TreeScope.Descendants,
              new PropertyCondition(AutomationElement.NameProperty, ""));

            // if it can be found, get the value from the URL bar
            if (elmUrlBars != null)
            {
                foreach (AutomationElement item in elmUrlBars)
                {
                    AutomationPattern[] patterns = item.GetSupportedPatterns();
                    if (patterns.Length > 0)
                    {
                        ValuePattern val = (ValuePattern)item.GetCurrentPattern(patterns[0]);
                        Console.WriteLine("Chrome URL found: " + val.Current.Value);
                    }
                }
            }
        }
    }

但是在最后的chrome版本(34.0.1847.131 m)中没有使用。 有人可以告诉更常见的解决方案吗?

1 个答案:

答案 0 :(得分:1)

在我的情况下尝试此解决方案,它可以正常工作。

string GetChromeUrl(IntPtr hndl)
        {
            if (hndl.ToInt32() > 0)
            {
                string url = "";
                AutomationElement elm = AutomationElement.FromHandle(hndl);
                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;
                        return url;
                    }
                }

            }
            return "";
        }