c# - 循环浏览 chrome 选项卡并根据网址关闭页面

标签 c# .net wpf

我希望能够遍历 chrome 页面上的所有选项卡并关闭任何 youtube 页面的选项卡。

我已经做了一些谷歌搜索并找到了下面的代码。有两个(很可能更多)问题。首先,我创建了一个 WPF 应用程序并添加了 System.Windows.Automation 命名空间(使用 visual studio 2015 .net 4.5),但无法识别 AutomationElement。

我也不确定如何遍历选项卡并测试页面是否为 youtube 页面。

        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)
            {
                AutomationPattern[] patterns = SearchBar.GetSupportedPatterns();
                if(patterns.Length > 0)
                {
                    ValuePattern val = (ValuePattern)SearchBar.GetCachedPattern(patterns[0]);
                    if (val.Current.Value.Contains("youtube.com") || val.Current.Value.Contains("youtube.co.uk"))
                        proc.Close();
                }
            }
         }

最佳答案

System.Windows.Automation 位于 UIAutomationClient.dll 中。您是否将 UIAutomationClient.dll 添加为对项目的引用?

检查值“youtube”。

if (SearchBar != null) 
{
    AutomationPattern[] patterns = SearchBar.GetSupportedPatterns();
    if (patterns.Length > 0) 
    {
        ValuePattern val = (ValuePattern)SearchBar.GetCurrentPattern(patterns[0]);
        if(val.Current.Value.Contains("youtube.com"))
            proc.Close();
    }
}

关于c# - 循环浏览 chrome 选项卡并根据网址关闭页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41856121/

相关文章:

c# - EntityFramework 无法创建类型为 'Anonymous type' 的常量值。在此上下文中仅支持原始类型或枚举类型

c# - "Security"部署的 Web 应用程序上的 NHibernate 问题

c# - Int32 类型的枚举成员

.net - 使用 Nancy + TinyIoC 通过 Quartz JobFactory 注入(inject)依赖项

c# - MVC中划分资源文件的最佳实践

c# - 在一段时间内更改按钮的颜色和文本

c# - 如何在关联的XAML中获取C#属性?

c# - Repeater 控件中的 DropDownList,无法触发 SelectedIndexChanged

.net - 如何用回调包装 3rdParty 函数以便能够等待回调完成然后从回调函数返回结果?

c# - 如何将控件填充到 ListViewItem 中的整个可用空间?