【问题标题】:C#.NET Winform - Get Current Chrome URL takes a long timeC#.NET Winform - 获取当前 Chrome URL 需要很长时间
【发布时间】:2020-07-06 10:18:54
【问题描述】:

从下面的代码中,我可以获得当前的 Chrome URL,但这需要时间。有时它需要超过 2 分钟,有时它没有返回任何值。

请指导我解决这个问题。

public string GetActiveTabUrl_Google_Chrome()
{ 
                
    Process[] procsChrome = Process.GetProcessesByName("chrome");

    if (procsChrome.Length <= 0)
        return null;

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

        // to find the tabs we first need to locate something reliable - the 'New Tab' button 


        AutomationElement root = AutomationElement.FromHandle(proc.MainWindowHandle);
        var SearchBar = root.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Address and search bar"));
        if (SearchBar != null)
        {                    
            return (string)SearchBar.GetCurrentPropertyValue(ValuePatternIdentifiers.ValueProperty);

        }
    }
}

我搜索了很多,但没有得到确切的解决方案。我尝试了多台电脑,但发现同样的问题。

谢谢

【问题讨论】:

    标签: c# winforms google-chrome


    【解决方案1】:

    减少所需时间的关键是使用更多的条件,并且不要使用NameProperty,这似乎需要很多时间。使用以下代码,我能够在大约 4 秒内获得 URL。

    static string GetURL()
    {
        Process[] procsChrome = Process.GetProcessesByName("chrome");
    
        foreach (Process chrome in procsChrome)
        {
            if (chrome.MainWindowHandle == IntPtr.Zero)
                continue;
    
            AutomationElement root = AutomationElement.FromHandle(chrome.MainWindowHandle);
    
            if (root == null)
                return null;
    
            Condition conditions = new AndCondition( // using multiple conditions which seems to be faster and descibe URL bar
                new PropertyCondition(AutomationElement.ProcessIdProperty, chrome.Id),
                new PropertyCondition(AutomationElement.IsControlElementProperty, true),
                new PropertyCondition(AutomationElement.IsContentElementProperty, true),
                new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
    
            AutomationElement urlbar = root.FindFirst(TreeScope.Descendants, conditions);
            return (string)urlbar.GetCurrentPropertyValue(ValuePatternIdentifiers.ValueProperty);
        }
    
        return null;
    }
    

    截图:

    【讨论】:

    • 测试了一下,没有得到任何url。
    • 你有什么版本的chrome?
    • 版本 83.0.4103.116(官方版本)(64 位)
    • 我有相同的版本,它适用于我。你有什么特殊的 chrome 设置吗?
    • 否,默认设置。
    猜你喜欢
    • 1970-01-01
    • 2012-07-13
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 2019-09-24
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    相关资源
    最近更新 更多