我希望能够遍历 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/