Récupérer l’URL actuelle de l’application de formulaire Windows C #

J’ai conçu un programme à l’aide de Visual C # et j’ai eu du mal à faire en sorte que mon programme interagisse avec les navigateurs Web. Fondamentalement, ce dont j’ai besoin, c’est de récupérer l’adresse URL depuis un navigateur Web (Internet Explorer, Firefox, Chrome, etc.).

Je pensais que cela ne serait pas trop difficile, mais après des jours et des journées de recherches et de tests, cela semble presque impossible! Jusqu’ici, j’ai rencontré ce …

Obtenir l’URL de Firefox?

Qui a le code ci-dessous:

using NDde.Client; Class Test { public static ssortingng GetFirefoxURL() { DdeClient dde = new DdeClient("Firefox", "WWW_GetWindowInfo"); dde.Connect(); ssortingng url = dde.Request("URL", int.MaxValue); dde.Disconnect(); return url; } } 

Ce qui est parfait pour Firefox, mais pour une raison quelconque, je ne peux pas le faire fonctionner avec autre chose. J’ai changé la partie du code qui dit “Firefox” en “Iexplore” comme je l’ai trouvé partout sur Internet, en essayant d’autres formes d’expression d’Internet Explorer, et j’obtiens l’erreur suivante:

“Le client n’a pas pu se connecter à” IExplorer | WWW_GetWindowInfo “, assurez-vous que l’application serveur est en cours d’exécution et qu’elle prend en charge la paire nom de service et nom de sujet spécifiés”

Toute aide sur la question serait très appréciée, car il est devenu une tâche ardue à résoudre.

Voici ce que j’ai jusqu’à présent (bien que Chrome, je ne trouve aucun article utile, mis à part l’utilisation de FindWindowEx (personnellement, je n’aime pas particulièrement cette méthode).

 public class BrowserLocation { ///  /// Structure to hold the details regarding a browed location ///  public struct URLDetails { ///  /// URL (location) ///  public Ssortingng URL; ///  /// Document title ///  public Ssortingng Title; } #region Internet Explorer // requires the following DLL added as a reference: // C:\Windows\System32\shdocvw.dll ///  /// Resortingeve the current open URLs in Internet Explorer ///  ///  public static URLDetails[] InternetExplorer() { System.Collections.Generic.List URLs = new System.Collections.Generic.List(); var shellWindows = new SHDocVw.ShellWindows(); foreach (SHDocVw.InternetExplorer ie in shellWindows) URLs.Add(new URLDetails() { URL = ie.LocationURL, Title = ie.LocationName }); return URLs.ToArray(); } #endregion #region Firefox // This requires NDde // http://ndde.codeplex.com/ public static URLDetails[] Firefox() { NDde.Client.DdeClient dde = new NDde.Client.DdeClient("Firefox", "WWW_GetWindowInfo"); try { dde.Connect(); Ssortingng url = dde.Request("URL", Int32.MaxValue); dde.Disconnect(); Int32 stop = url.IndexOf('"', 1); return new URLDetails[]{ new URLDetails() { URL = url.Subssortingng(1, stop - 1), Title = url.Subssortingng(stop + 3, url.Length - stop - 8) } }; } catch (Exception) { return null; } } #endregion } class Program { static void Main(ssortingng[] args) { Console.WriteLine("Internet Explorer: "); (new List(BrowserLocation.InternetExplorer())).ForEach(u => { Console.WriteLine("[{0}]\r\n{1}\r\n", u.Title, u.URL); }); Console.WriteLine(); Console.WriteLine("Firefox:"); (new List(BrowserLocation.Firefox())).ForEach(u => { Console.WriteLine("[{0}]\r\n{1}\r\n", u.Title, u.URL); }); Console.WriteLine(); } } 

Voici un code basé sur Microsoft UI Automation :

 public static ssortingng 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 ssortingng; } public static ssortingng GetInternetExplorerUrl(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 rebar = element.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "ReBarWindow32")); if (rebar == null) return null; AutomationElement edit = rebar.FindFirst(TreeScope.Subtree, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit)); return ((ValuePattern)edit.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as ssortingng; } public static ssortingng GetFirefoxUrl(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 doc = element.FindFirst(TreeScope.Subtree, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Document)); if (doc == null) return null; return ((ValuePattern)doc.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as ssortingng; } 

Vous pouvez utiliser l’ outil UI Spy pour comprendre la hiérarchie visuelle des 3 navigateurs. Vous devrez peut-être adapter les choses pour vous assurer que cela fonctionne vraiment dans vos cas spécifiques, mais vous devriez en avoir une idée générale avec ces exemples.

Et un exemple qui affiche toutes les URL des 3 types de processus (IE, FF, CH) en cours d’exécution dans le système:

 static void Main(ssortingng[] args) { foreach (Process process in Process.GetProcessesByName("firefox")) { ssortingng url = GetFirefoxUrl(process); if (url == null) continue; Console.WriteLine("FF Url for '" + process.MainWindowTitle + "' is " + url); } foreach (Process process in Process.GetProcessesByName("iexplore")) { ssortingng url = GetInternetExplorerUrl(process); if (url == null) continue; Console.WriteLine("IE Url for '" + process.MainWindowTitle + "' is " + url); } foreach (Process process in Process.GetProcessesByName("chrome")) { ssortingng url = GetChromeUrl(process); if (url == null) continue; Console.WriteLine("CH Url for '" + process.MainWindowTitle + "' is " + url); } } 

Utilisez le paramètre “1” au lieu de “URL” dans oDde.Request (“URL”, int.MaxValue) pour IE.

  public static void ProcessIEURLs() { ssortingng sURL; try { DdeClient oDde = new DdeClient("IExplore", "WWW_GetWindowInfo"); try { oDde.Connect(); sURL = oDde.Request("1", int.MaxValue); oDde.Disconnect(); bool bVisited = false; if ( oVisitedURLList != null && oVisitedURLList.Count > 0 ) { bVisited = FindURL(sURL, oVisitedURLList); } if ( !bVisited ) { oVisitedURLList.Add(sURL); } } catch ( Exception ex ) { throw ex; } } catch ( Exception ex ) { throw ex; } } 

Mourier, merci pour votre solution Microsoft UI Automation . Même si cela n’a pas fonctionné pour Firefox 41.0, j’ai analysé la structure de la fenêtre de Firefox avec le petit outil “Automation Spy “. Ensuite, j’ai légèrement modifié les conditions de recherche et cela a parfaitement fonctionné!

  public static ssortingng GetFirefoxUrl(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; element = element.FindFirst(TreeScope.Subtree, new AndCondition( new PropertyCondition(AutomationElement.NameProperty, "search or enter address", PropertyConditionFlags.IgnoreCase), new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit))); if (element == null) return null; return ((ValuePattern)element.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as ssortingng; } 

Et voici la solution pour le chrome 48:

  public static ssortingng 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.Subtree, new AndCondition( new PropertyCondition(AutomationElement.NameProperty, "address and search bar", PropertyConditionFlags.IgnoreCase), new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit))); return ((ValuePattern)edit.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as ssortingng; } 

Automation Spy montre la structure des contrôles de la fenêtre Firefox. Le contrôle de type ‘edit’ avec le nom ‘Search or enter address’ contient l’URL: Automatisation Spy

Remarque: dans votre projet .NET, vous avez besoin de 2 références:

  • UIAutomationClient.dll
  • UIAutomationTypes.dll

WWW_GetWindowInfo est pris en charge dans IE et remonte à la version 3.02 depuis 16 jours! Fonctionne pour Firefox et Opera

Je pense que Chrome est en fait l’intrus.

Je ne sais pas comment les choses se passent au-delà de ces quatre.

le choix est d’utiliser le selenium WebDriver. meilleur et puissant api complet avec premision complète