![](/img/trans.png)
[英]How to get active Google profile name when I get the active Url from google chrome browser using C#
[英]C# Get the URL of the active tab of browser
我有一个应用程序,如果打开的程序是浏览器,则焦点更改应该能够检索当前活动选项卡的 URL 否则应该只返回程序的名称。
例如,假设我在前台打开了记事本,然后我在浏览器中打开了 2 个选项卡,我希望应用程序提取活动选项卡的 URL。 下面的代码用于查找选项卡的名称,但 try catch 中的代码应该找到选项卡的 URL 不起作用,它只会打印空字符串。
我想拥有该站点的 URL 以便我可以不断引用它,因为同一站点中的选项卡名称可能不同
private void OnFocusChangedHandler(object src, AutomationFocusChangedEventArgs args)
{
Debug.WriteLine("Focus changed!");
AutomationElement element = src as AutomationElement;
if (element != null)
{
string name = element.Current.Name;
string id = element.Current.AutomationId;
int processId = element.Current.ProcessId;
try
{
using (Process process = Process.GetProcessById(processId))
{
AutomationElement elm = AutomationElement.FromHandle(process.MainWindowHandle);
AutomationElement elmUrlBar = elm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
AutomationPattern[] patterns = elmUrlBar.GetSupportedPatterns();
if (patterns.Length > 0)
{
ValuePattern val = (ValuePattern)elmUrlBar.GetCurrentPattern(patterns[0]);
Debug.WriteLine("URL found: " + val.Current.Value);
}
}
}
catch { }
Debug.WriteLine(" Name: {0}, Id: {1}", name, id);
}
}
我已经在 stackoverflow 和不同的网站中尝试了类似的所有方法,但要么真的过时了,要么就是不起作用。
提前致谢。
我找到了适用于所有在(Yandex(基于铬的)Chrome 和 Firefox 上测试的所有浏览器的解决方案,它适用于所有三个)。
首先,我从使用System.Windows.Automation
更改为IUIAutomation
,因为前者真的很慢。
因此,对于寻找类似问题解决方案的每个人来说,首先 go 到依赖项并右键单击依赖项并按“添加 COM 参考..”:
然后找到 UIAutomationClient 你可以把 UI 放在右上角的搜索栏里很容易找到它: 添加后,代码如下:
private readonly CUIAutomation _automation;
public YourMainClass()
{
_automation = new CUIAutomation();
_automation.AddFocusChangedEventHandler(null, new FocusChangeHandler(this));
}
public class FocusChangeHandler : IUIAutomationFocusChangedEventHandler
{
private readonly YourMainClass _listener;
public FocusChangeHandler(YourMainClass listener)
{
_listener = listener;
}
public void HandleFocusChangedEvent(IUIAutomationElement element)
{
if (element != null)
{
using (Process process = Process.GetProcessById(element.CurrentProcessId))
{
try
{
IUIAutomationElement elm = this._listener._automation.ElementFromHandle(process.MainWindowHandle);
IUIAutomationCondition Cond = this._listener._automation.CreatePropertyCondition(30003, 50004);
IUIAutomationElementArray elm2 = elm.FindAll(TreeScope.TreeScope_Descendants, Cond);
for (int i = 0; i < elm2.Length; i++)
{
IUIAutomationElement elm3 = elm2.GetElement(i);
IUIAutomationValuePattern val = (IUIAutomationValuePattern)elm3.GetCurrentPattern(10002);
if (val.CurrentValue != "")
{
Debug.WriteLine("URL found: " + val.CurrentValue);
}
}
}
catch { }
}
}
}
}
在最上面放这两行
using UIAutomationClient;
using TreeScope = UIAutomationClient.TreeScope;
您还应该根据需要用自己的 class 更改“YourMainClass”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.