我有一個應用程式,如果打開的程式是瀏覽器,則焦點更改應該能夠檢索當前活動選項卡的 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 和不同的網站中嘗試了類似的所有方法,但要么真的過時了,要么就是不起作用。
提前致謝。
uj5u.com熱心網友回復:
我找到了適用于所有在(Yandex(基于鉻的)Chrome 和 Firefox 上測驗的所有瀏覽器,它適用于所有三個瀏覽器)的解決方案。
首先我從 using 更改為System.Windows.Automation,IUIAutomation因為前者真的很慢。
因此,對于尋找類似問題解決方案的每個人來說,首先轉到依賴項并右鍵單擊依賴項并按“添加 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;
而且你應該根據需要用你自己的類來改變“YourMainClass”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414837.html
標籤:
