我有一个监控浏览器URL的应用程序。目前我正在使用chrome。我按照this answer:
的解决方案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
,这是我的大问题。有没有人有更好的解决方案?
答案 0 :(得分:1)
哪个位返回null? Windows通常会忽略其ShowInTaskbar属性已更改的程序。这可能是第一次检查(和第二次)中为空的原因。关于第二个故障,我无法提供任何帮助,但几周前我遇到了同样的问题。我决定使用Chrome的URL栏的position元素,将光标位置更改为它,然后在光标下获取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...
}
这是否能为您的查询提供答案?