2013-07-08 20 views
0

我有一个监视浏览器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,这是我的大问题。有没有人有更好的解决方案?

+0

什么行返回null? MainWindowHandle检查? FromHandle检查或Current.Value? –

+0

嗨Simon,This line Returns the null AutomationElement edit = element.FindFirst(TreeScope.Children,new PropertyCondition(AutomationElement.ControlTypeProperty,ControlType.Edit)); 我也注意到,当你在chrome中右键点击页面时什么都不做,它也会返回一个空值。 谢谢 – Fadz

+0

而我发现了另一种抛出null的方法。 如果你将鼠标悬停在链接或标题栏上, 带有长文本的标题栏(如果它弹出整个文本或作为工具提示弹出),它将抛出一个空值。 看起来像这会在我的工作中造成问题。 – Fadz

回答

1

哪位返回空? Windows会经常忽略ShowInTaskbar属性发生更改的程序。这可能是第一次检查为空(和第二次)的原因。关于第二个错误,我无法提供任何帮助,但几周前我遇到了同样的问题。我决定使用Chrome的地址栏的位置元素,改变光标的位置,然后拿到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... 
    } 

这是否能解答您的查询?

+0

我尝试你的代码,但我无法得到mouse.x和y?这是一个鼠标或url栏的值? – Fadz

+0

鼠标和URL栏我们将光标设置在其位置上。一旦你有自动化元素,你可能会得到一个ID,并继续得到它的名字,而不必鼠标悬停在那里。我会写,但我在我的手机上。至少不值得赞扬吗? –

+0

@Fadz你可能可以做新的Point(Cursor.Position),但我不确定。 –