使用AutomationElement从Chrome获取URL
本文关键字:获取 URL Chrome AutomationElement 使用 | 更新日期: 2023-09-27 18:21:32
我有一个监视浏览器URL的应用程序。目前我正在使用chrome。我遵循了这个答案的解决方案:
public static string GetChromeUrl(Process process) {
if (process == null)
throw new ArgumentNullException("process");
if (process.MainWindowHandle == IntPtr.Zero)
return null;
AutomationElement element = AutomationElement.FromHandle(process.MainWindowHandle);
if (element == null)
return null;
AutomationElement edit = element.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
return ((ValuePattern)edit.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as string;
}
然后我有这样的方法来将URL记录在一个文本文件中(使用log4net):
while (true) {
foreach (Process process in Process.GetProcessesByName("chrome")) {
string url = GetChromeUrl(process);
if (url == null)
continue;
Console.WriteLine(url); //for viewing purpose, it actually logs in orig code
}
Thread.Sleep(1000);
}
它运行得很好。但不知何故,与GetChromeUrl
方法不一致。有时它会返回null
,这是我的大问题。有人有更好的解决方案吗?
哪个位返回null?Windows经常会忽略ShowInTaskbar属性已更改的程序。这可能是第一次检查(和第二次检查)为null的原因。关于第二个错误,我无法提供任何帮助,但几周前我也遇到了同样的问题。我决定使用Chrome的URL栏的位置元素,将光标位置更改为它,然后在光标下获得AutomationElement:
Form1_Load()
{
Cursor.Position = element's position;
Timer.Start();
}
Timer_Tick()
{
AutomationElement element = AutomationElement.FromPoint(new System.Windows.Point(mouse.X, mouse.Y));
string current = element.Current.Name;
Console.WriteLine(current); //log in text file...
}
这是否为您的查询提供了答案?