2015-11-05 40 views
0

瀏覽器URL現在,我使用下面這個代碼從活動標籤的URL我的Chrome瀏覽器C#獲取主動標籤

/* 
    * GetUrlInternal 
    * */ 
    private string GetUrlInternal(IntPtr process) { 
     string sURL = null; 
     Process[] procsChrome = Process.GetProcessesByName("chrome"); 
     foreach (Process chrome in procsChrome) { 
      if (chrome.MainWindowHandle == IntPtr.Zero) { 
       continue; 
      } 
      AutomationElement element = AutomationElement.FromHandle(chrome.MainWindowHandle);   
      AutomationElement elm1 = element.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Google Chrome")); 
      AutomationElement elm2 = TreeWalker.RawViewWalker.GetLastChild(elm1); 
      AutomationElement elm3 = elm2.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "")); 
      AutomationElement elm4 = elm3.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ToolBar)); 
      AutomationElement elementx = elm1.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Pasek adresu i wyszukiwania")); 
      if (!(bool)elementx.GetCurrentPropertyValue(AutomationElement.HasKeyboardFocusProperty)) { 
       sURL = ((ValuePattern)elementx.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as string; 
      } 
     } 
     return sURL; 
    } 

此代碼的工作作爲一個魅力,但與閱讀的延遲來自Chrome的URL。它需要2到4秒才能得到這個URL。 有誰知道爲什麼? 感謝您的任何線索...

+1

多少'chrome.exe'過程你有跑步嗎?這可能是所有這些都是延遲的原因。你有沒有對代碼做過任何分析?哪條線最長?同一行在每次循環迭代中佔用相同的時間量嗎? – 2015-11-05 08:22:36

+0

[使用C#從谷歌瀏覽器中獲取當前標籤頁的URL]可能的副本(http://stackoverflow.com/questions/18897070/getting-the-current-tabs-url-from-google-chrome-using-c-sharp ) – mybirthname

+0

http://stackoverflow.com/questions/18897070/getting-the-current-tabs-url-from-google-chrome-using-c-sharp你可以看到接受答案的編輯。 – mybirthname

回答

0

我有七個進程chrome.exe運行。我已經檢查使用秒錶在我的代碼的延遲,我發現了一段代碼造成這種延遲

AutomationElement elementx = elm1.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Pasek adresu i wyszukiwania")); 

處理此行所花費1450毫秒

+0

嘗試將elm1更改爲elm4;) – Dyorgio