我有一个监视浏览器URL的应用程序。目前我正在使用chrome。我跟着从this answer解决方案:(使用log4net的)使用AutomationElement从Chrome获取URL
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;
}
然后,我有这样的方法记录在一个文本文件的网址:
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? MainWindowHandle检查? FromHandle检查或Current.Value? –
嗨Simon,This line Returns the null AutomationElement edit = element.FindFirst(TreeScope.Children,new PropertyCondition(AutomationElement.ControlTypeProperty,ControlType.Edit)); 我也注意到,当你在chrome中右键点击页面时什么都不做,它也会返回一个空值。 谢谢 – Fadz
而我发现了另一种抛出null的方法。 如果你将鼠标悬停在链接或标题栏上, 带有长文本的标题栏(如果它弹出整个文本或作为工具提示弹出),它将抛出一个空值。 看起来像这会在我的工作中造成问题。 – Fadz