2013-03-16 52 views
2

對於檢測Firefox的URL我用的DDEC#從Firefox獲得的網址,但不使用DDE

DdeClient dde = new DdeClient("Firefox", "WWW_GetWindowInfo"); 
dde.Connect(); 
string url1 = dde.Request("URL", int.MaxValue); 
dde.Disconnect(); 
temp = url1.Replace("\"", "").Replace("\0", ""); 
dde = null; 

此代碼的工作完美!但它是連接速度太慢(dde.Connect();)太慢了7/8秒! 有沒有另一種方式從Firefox獲取URL? (例如使用API​​的窗口,如 「SendMessage函數」)

+0

SendMessage函數就太脆弱。不能保證UI中控件的名稱都保持完全相同。事實上,儘管Firefox已經完全重新設計,但我敢打賭他們已經改變了很多次。 – 2013-03-16 09:13:23

+0

你看過http://stackoverflow.com/questions/5317642/retrieve-current-url-from-c-sharp-windows-form? – 2013-03-16 16:25:26

回答

1

這很適合我:

   AutomationElement element = AutomationElement.FromHandle(intPtr); // intPtr is the MainWindowHandle for FireFox browser 
       element = element.FindFirst(TreeScope.Subtree, 
         new AndCondition(
          new PropertyCondition(AutomationElement.NameProperty, "Search or enter address"), 
          new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit))); 
       string url = ((ValuePattern)element.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as string; 
2
  Process[] process = Process.GetProcessesByName("firefox"); 

      foreach (Process firefox in process) 
      { 
       // the chrome process must have a window 
       if (firefox.MainWindowHandle == IntPtr.Zero) 
       { 
        return null; 
       } 

       AutomationElement element = AutomationElement.FromHandle(firefox.MainWindowHandle); 
       if (element == null) 
        return null; 

       //search for first custom element 
       AutomationElement custom1 = element.FindFirst(TreeScope.Descendants, 
       new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Custom)); 

       //search all custom element children 
       AutomationElementCollection custom2 = custom1.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Custom)); 

       //for each custom child 
       foreach (AutomationElement item in custom2) 
       { 
        //search for first custom element 
        AutomationElement custom3 = item.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Custom)); 
        //search for first document element 
        AutomationElement doc3 = custom3.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Document)); 



        if (!doc3.Current.IsOffscreen) 
        { 
         url = ((ValuePattern)doc3.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as string; 
         return url; 
        }      
       } 
      }    
      return url; 
    }