Retrieve current URL from C# windows forms application - c#

I have been designing a program using Visual C# and have came across an issue with making my program interact with web browsers. Basically what I need is to retrieve the URL address from a web browser (Internet Explorer, Firefox, Chrome etc...).
I figured this wouldn't be too difficult of a task, but after days and days of research and tests, it seems almost impossible! Thus far, I have come across this...
Get Firefox URL?
Which has the code below:
using NDde.Client;
Class Test
{
public static string GetFirefoxURL()
{
DdeClient dde = new DdeClient("Firefox", "WWW_GetWindowInfo");
dde.Connect();
string url = dde.Request("URL", int.MaxValue);
dde.Disconnect();
return url;
}
}
Which is perfect for Firefox, but for some reason I cannot get it to work with anything else. I have changed the portion of the code that says "Firefox" to "Iexplore" like I found all over the internet, along with trying other forms of expressing Internet Explorer, and I get the following error:
"Client failed to connect to "IExplorer|WWW_GetWindowInfo", Make sure the server application is running and that it supports the specified service name and topic name pair"
Any help on the issue would be much appreciated as it has become quite a task to figure out.

Here is a code based on Microsoft UI Automation:
public static string 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 string;
}
public static string 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 string;
}
public static string 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 string;
}
You can use the UI Spy tool to understand the visual hierarchy for all 3 browsers. You may need to adapt things to make sure it really work in your specific cases, but you should get the general idea with these samples.
And an example that dumps all urls for all the 3 types of process (IE, FF, CH) currently running in the system:
static void Main(string[] args)
{
foreach (Process process in Process.GetProcessesByName("firefox"))
{
string url = GetFirefoxUrl(process);
if (url == null)
continue;
Console.WriteLine("FF Url for '" + process.MainWindowTitle + "' is " + url);
}
foreach (Process process in Process.GetProcessesByName("iexplore"))
{
string url = GetInternetExplorerUrl(process);
if (url == null)
continue;
Console.WriteLine("IE Url for '" + process.MainWindowTitle + "' is " + url);
}
foreach (Process process in Process.GetProcessesByName("chrome"))
{
string url = GetChromeUrl(process);
if (url == null)
continue;
Console.WriteLine("CH Url for '" + process.MainWindowTitle + "' is " + url);
}
}

Mourier, thank you for your solution Microsoft UI Automation.
Even so it didn't worked for Firefox 41.0,
I analysed the Firefox window structure with the little tool "Automation Spy".
Then I've changed the search conditions slightly, and it worked perfectly!
public static string 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 string;
}
And here is the solution for Chromium 48:
public static string 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 string;
}
Automation Spy shows Firefox window controls structure. The control of type 'edit' with the name 'Search or enter address' holds the url:
Note: In your .NET project you need 2 references:
UIAutomationClient.dll
UIAutomationTypes.dll

Use parameter "1" instead of "URL" in oDde.Request("URL", int.MaxValue) for IE.
public static void ProcessIEURLs()
{
string 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;
}
}

Here's what I have so far (though Chrome I'm not finding any helpful articles on, other than using FindWindowEx (I don't particularly like that method, personally).
public class BrowserLocation
{
/// <summary>
/// Structure to hold the details regarding a browed location
/// </summary>
public struct URLDetails
{
/// <summary>
/// URL (location)
/// </summary>
public String URL;
/// <summary>
/// Document title
/// </summary>
public String Title;
}
#region Internet Explorer
// requires the following DLL added as a reference:
// C:\Windows\System32\shdocvw.dll
/// <summary>
/// Retrieve the current open URLs in Internet Explorer
/// </summary>
/// <returns></returns>
public static URLDetails[] InternetExplorer()
{
System.Collections.Generic.List<URLDetails> URLs = new System.Collections.Generic.List<URLDetails>();
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();
String url = dde.Request("URL", Int32.MaxValue);
dde.Disconnect();
Int32 stop = url.IndexOf('"', 1);
return new URLDetails[]{
new URLDetails()
{
URL = url.Substring(1, stop - 1),
Title = url.Substring(stop + 3, url.Length - stop - 8)
}
};
}
catch (Exception)
{
return null;
}
}
#endregion
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Internet Explorer: ");
(new List<BrowserLocation.URLDetails>(BrowserLocation.InternetExplorer())).ForEach(u =>
{
Console.WriteLine("[{0}]\r\n{1}\r\n", u.Title, u.URL);
});
Console.WriteLine();
Console.WriteLine("Firefox:");
(new List<BrowserLocation.URLDetails>(BrowserLocation.Firefox())).ForEach(u =>
{
Console.WriteLine("[{0}]\r\n{1}\r\n", u.Title, u.URL);
});
Console.WriteLine();
}
}

WWW_GetWindowInfo is supported in IE and has been since version 3.02 back in the 16 bit days! Works for Firefox and Opera
I believe that Chrome is in fact the odd one out.
I've got no knowledge of how things are beyond those four.

the bese choice is to use selenium webdriver. best and power full api with full premision

Related

windows application Memory consumption increase while tracking browser(chorme) url using C#

Hi i have a winForms application which runs a 10 sec threading timer and in that function i am calling this function whenever active process is chrome but it start with low system memory of 28 mb and goes upto 500-600mb with in hours if i use chrome constantly can someone tell what i am doing wrong
public string ChromeTabItemURL()
{
try
{
// Url Tracking Enable and Disabled From Web
if (!TrackDayWiseHelper.isTrackDayWiseActivated())
return string.Empty;
if (StorageBag.isUserDisableUrlTrack)
return string.Empty;
Process[] procsChrome = Process.GetProcessesByName("chrome");
if (procsChrome.Length == 0)
{
return "";
}
AutomationElement elm = null;
AutomationElement elmUrlBar = null;
AutomationPattern[] patterns = null;
foreach (Process chrome in procsChrome)
{
// the chrome process must have a window
if (chrome.MainWindowHandle == IntPtr.Zero)
{
continue;
}
// find the automation element
elm = AutomationElement.FromHandle(chrome.MainWindowHandle);
elmUrlBar = elm.FindFirst(TreeScope.Descendants,
new PropertyCondition(AutomationElement.NameProperty, "Address and search bar"));
// if it can be found, get the value from the URL bar
if (elmUrlBar != null)
{
if ((bool)elmUrlBar.GetCurrentPropertyValue(AutomationElement.HasKeyboardFocusProperty))
{
continue;
}
patterns = elmUrlBar.GetSupportedPatterns();
if (patterns.Length > 0)
{
ValuePattern val = (ValuePattern)elmUrlBar.GetCurrentPattern(patterns[0]);
elmUrlBar = null;
if (val.Current.Value != "")
{
if (Regex.IsMatch(val.Current.Value, #"^(https:\/\/)?[a-zA-Z0-9\-\.]+(\.[a-zA-Z]{2,4}).*$"))
{
// prepend http:// to the url, because Chrome hides it if it's not SSL
if (!val.Current.Value.StartsWith("http"))
{
string value = "http://" + val.Current.Value;
Console.WriteLine(value);
return value;
}
}
}
return val.Current.Value;
}
elmUrlBar = null;
}
}
procsChrome = null;
elm = null;
elmUrlBar = null;
patterns = null;
return "";
}
catch (System.ComponentModel.Win32Exception ex)
{
ExceptionLogging.SendExcepToDB(ex); Crashes.TrackError(ex);
}
catch (Exception ex)
{
ExceptionLogging.SendExcepToDB(ex); Crashes.TrackError(ex);
}
return "";
}
code seems to be working fine i tried using jettbrains dott trace and this didnt come up as most resource consuming process but dont know why it is happening if i run application without this everything seems to be working fine

Getting the active url of browser in C# windows form application

I have created a window form application.
This App get the active url of browser and save this into the text file.
And this works fine in chrome & IE.
But when i use firefox, this will not work. This code fails to get the active url of firefox browser.
I don't know why this happening.
I am using the following code to find the URL
public string GetBrowsedUrl()
{
IntPtr hwnd = APIFuncs.getforegroundWindow();
Int32 pid = APIFuncs.GetWindowProcessID(hwnd);
Process process = Process.GetProcessById(pid);
string appId = proc.Id.ToString();
string appName = proc.ProcessName;
string appltitle = APIFuncs.ActiveApplTitle().Trim().Replace("\0", "");
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.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
string result = ((ValuePattern)edit.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as string;
return result;
}
Finally i found the answer
public string GetBrowsedUrl(Process process)
{
if (process.ProcessName == "firefox")
{
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 string;
}
else
{
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.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
string result = ((ValuePattern)edit.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as string;
return result;
}
}
You can not use this code for firefox too.
I recommend a third party library named NDde to do this very easily.
Here is NDde link
public string GetFirefoxUrl()
{
try
{
Process[] pname = Process.GetProcessesByName("Firefox");
if (pname.Length != 0)
{
DdeClient dde = new DdeClient("Firefox", "WWW_GetWindowInfo");
dde.Connect();
string url = dde.Request("URL", int.MaxValue);
url= url.Replace("\"", "").Replace("\0", "");
dde.Disconnect();
return url;
}
else
return null;
}
catch
{
return null;
}
}

Global service of the Team explorer's Query results window

What is the Query results window's global service (interface)? Code below:
var dteService = Package.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
if (dteService == null)
{
Debug.WriteLine("");
return;
}
var something=Package.GetGlobalService(typeof(???)) as ???;
EDIT: The goal is, when I press the context menu button, I want the function callback to be able to access the service where the work item is selected (or the results list
Please check this case in MSDN forum for the details how to get it work: https://social.msdn.microsoft.com/Forums/vstudio/en-US/2d158b9c-dec1-4c59-82aa-f1f2312d770b/sdk-packageget-selected-item-from-query-results-list
The following code is quoted from above link for your quick reference:
Document activeDocument = _applicationObject.ActiveDocument;
if (activeDocument != null)
{
DocumentService globalService = (DocumentService)Package.GetGlobalService(typeof(DocumentService));
if (globalService != null)
{
string fullName = activeDocument.FullName;
IWorkItemTrackingDocument document2 = globalService.FindDocument(fullName, null);
if ((document2 != null) && (document2 is IResultsDocument))
{
int[] selectedItemIds = ((IResultsDocument)document2).SelectedItemIds;
}
}
}
var dteService = Package.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
if (dteService == null)
{
Debug.WriteLine("");
return;
}
DocumentService documentService = Package.GetGlobalService(typeof(DocumentService)) as DocumentService;
if (documentService == null)
return;
string fullName = dteService.ActiveDocument.FullName;
IWorkItemTrackingDocument activeDocument = documentService.FindDocument(fullName, null);
if (activeDocument == null || !(activeDocument is IResultsDocument))
return;

Get url from firefox 8 not working anymore

I have a windows applicaiton c# catching the url of a running firefox instance.
I have always used "MozillaContentWindow" to get firefox URL but i dont understand why it dont work anymore.
string s = GetUrlFromBrowsersWithIdentifier("MozillaContentWindow", foreGround);
public string GetUrlFromBrowsersWithIdentifier(string identifier, int foreground)
{
try
{
IntPtr ptr = new IntPtr(foreground);
var aeBrowser = AutomationElement.FromHandle(ptr);
return aeBrowser == null ? "" : GetURLfromBrowser(aeBrowser, identifier);
}
catch (Exception ex)
{
return "";
}
}
string GetURLfromBrowser(AutomationElement rootElement, string identifier)
{
try
{
Condition condition1 = new PropertyCondition(AutomationElement.IsContentElementProperty, true);
Condition condition2 = new PropertyCondition(AutomationElement.ClassNameProperty, identifier);
var walker = new TreeWalker(new AndCondition(condition1, condition2));
var elementNode = walker.GetFirstChild(rootElement);
if (elementNode != null)
{
var p = elementNode.GetSupportedPatterns();
if (p.Any(autop => autop.ProgrammaticName.Equals("ValuePatternIdentifiers.Pattern")))
{
var valuePattern = elementNode.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
if (valuePattern != null)
return (valuePattern.Current.Value);
}
}
}
catch
{
return "";
}
return "";
}
Now when it enters "walker.GetFirstChild(rootElement);" it just stops there. I cant figure out why. This only happend on latest version of firefox.
Did they change the name of the value bar containing the url?
Thank you
Try using MozillaWindowContentClass for newer versions.

How to find all the browsers installed on a machine

How can I find of all the browsers and their details that are installed on a machine.
A quick google search gave me Finding All Installed Browsers in Windows XP and Vista
In the application I’ve been working on, I needed to find all browsers that are installed on a user’s machine. The best way to go about this is to look in the registry under HKEY_LOCAL_MACHINE\SOFTWARE\Clients\StartMenuInternet. This is where browser manufacturers are told to put their information, per this MSDN article.
A short answer:
using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
{
RegistryKey webClientsRootKey = hklm.OpenSubKey(#"SOFTWARE\Clients\StartMenuInternet");
if (webClientsRootKey != null)
foreach (var subKeyName in webClientsRootKey.GetSubKeyNames())
if (webClientsRootKey.OpenSubKey(subKeyName) != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell") != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open") != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command") != null)
{
string commandLineUri = (string)webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command").GetValue(null);
//your turn
}
}
Simple example of an application (WPF) to launch all installed browsers:
cs:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
namespace WpfApplication94
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<ViewerApplication> viewers = new List<ViewerApplication>();
using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
{
RegistryKey webClientsRootKey = hklm.OpenSubKey(#"SOFTWARE\Clients\StartMenuInternet");
if (webClientsRootKey != null)
foreach (var subKeyName in webClientsRootKey.GetSubKeyNames())
if (webClientsRootKey.OpenSubKey(subKeyName) != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell") != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open") != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command") != null)
{
string commandLineUri = (string)webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command").GetValue(null);
if (string.IsNullOrEmpty(commandLineUri))
continue;
commandLineUri = commandLineUri.Trim("\"".ToCharArray());
ViewerApplication viewer = new ViewerApplication();
viewer.Executable = commandLineUri;
viewer.Name = (string)webClientsRootKey.OpenSubKey(subKeyName).GetValue(null);
viewers.Add(viewer);
}
}
this.listView.ItemsSource = viewers;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Process.Start(((sender as Control).Tag as ViewerApplication).Executable, #"http://news.google.de");
}
}
public class ViewerApplication
{
public string Name { get; set; }
public string Executable { get; set; }
public Icon Icon
{
get { return System.Drawing.Icon.ExtractAssociatedIcon(this.Executable); }
}
public ImageSource ImageSource
{
get
{
ImageSource imageSource;
using (Bitmap bmp = Icon.ToBitmap())
{
var stream = new MemoryStream();
bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
imageSource = BitmapFrame.Create(stream);
}
return imageSource;
}
}
}
}
xaml:
<Window x:Class="WpfApplication94.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<ListView x:Name="listView">
<ListView.ItemTemplate>
<DataTemplate>
<Button Tag="{Binding}" Click="Button_Click">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding ImageSource}" />
<TextBlock Text="{Binding Name}" />
</StackPanel>
</Button>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Window>
result:
Scan the contents of the Program Files folder for the filenames of known browser executables.
Necromancing, as the provided answers are incomplete.
First:
HKEY_LOCAL_MACHINE\SOFTWARE\Clients\StartMenuInternet.
won't get you all browsers.
If you're in a corporate environment, the user will not have admin rights.
If Google-Chrome and/or Chromium are installed that way (don't know if FF works like that), then the key will only be in HK_Current_User.
Also, this doesn't cover non-windows operating systems.
You'll need elaborate code to determine and cover all package-management system on Linux + Mac systems.
Here code for Windows + Debian-based Linuces
PlatformInfo:
using System.Diagnostics;
namespace PlatformInfo
{
public delegate int BrowserRatingCallback_t(string packageName);
public class BrowserInfo : System.IComparable<BrowserInfo>
{
public string Name;
public string Path;
public int Preference;
public int CompareTo(BrowserInfo other)
{
if (this == null || other == null)
return 0;
int pref = this.Preference.CompareTo(other.Preference);
if (pref != 0)
return pref;
return string.Compare(this.Name, other.Name, true);
} // End Function CompareTo
public static int DefaultBrowserRating(string packageName)
{
if (EmbeddedWebServer.StringHelpers.Contains(packageName, "Google")) return 1;
if (EmbeddedWebServer.StringHelpers.Contains(packageName, "Chromium")) return 2;
if (EmbeddedWebServer.StringHelpers.Contains(packageName, "Opera")) return 3;
if (EmbeddedWebServer.StringHelpers.Contains(packageName, "Firefox")) return 4;
if (EmbeddedWebServer.StringHelpers.Contains(packageName, "Midori")) return 5;
if (EmbeddedWebServer.StringHelpers.Contains(packageName, "Safari")) return 9000;
if (EmbeddedWebServer.StringHelpers.Contains(packageName, "Edge")) return 9998;
if (EmbeddedWebServer.StringHelpers.Contains(packageName, "Explorer")) return 9999;
return 9997;
}
public static System.Collections.Generic.List<BrowserInfo> GetPreferableBrowser()
{
return GetPreferableBrowser(BrowserInfo.DefaultBrowserRating);
}
public static System.Collections.Generic.List<BrowserInfo> GetPreferableBrowser(BrowserRatingCallback_t browserRatingCallback)
{
if (System.Environment.OSVersion.Platform != System.PlatformID.Unix)
return Win.GetPreferableBrowser(browserRatingCallback);
// ELSE: Linux / Unix / MacOS
if (DistroInfo.PackageManager == DistroInfo.PackageManager_t.dpkg)
return dpkg.GetInstalledBrowsers(browserRatingCallback);
return new System.Collections.Generic.List<BrowserInfo>();
}
} // End Class BrowserInfo : System.IComparable<BrowserInfo>
public class DistroInfo
{
public enum Distro_t : int
{
Debian
,Ubuntu
,Mint
,Arch
,Gentoo
,CentOS
,Fedora
,RedHat
,Mageia
,Suse
,Mandrake
,YellowDog
,Slackware
,SunJDS
,Solaris
,UnitedLinux
,Unknown
} // End Enum Distro_t
public enum PackageManager_t : int
{
dpkg
,rpm
,portage
,pacman
,pkgtool
,ips
,unknown
} // End Enum PackageManager_t
public enum DistroFamily_t : int
{
Debian, RedHat, Unknown
} // End Enum DistroFamily_t
public static DistroFamily_t DistroFamily
{
get {
if (Distro == Distro_t.Ubuntu)
return DistroFamily_t.Debian;
if (Distro == Distro_t.Debian)
return DistroFamily_t.Debian;
if (Distro == Distro_t.Mint)
return DistroFamily_t.Debian;
if (Distro == Distro_t.RedHat)
return DistroFamily_t.RedHat;
if (Distro == Distro_t.CentOS)
return DistroFamily_t.RedHat;
if (Distro == Distro_t.Fedora)
return DistroFamily_t.RedHat;
if (Distro == Distro_t.Suse)
return DistroFamily_t.RedHat;
if (Distro == Distro_t.Mageia)
return DistroFamily_t.RedHat;
if (Distro == Distro_t.Mandrake)
return DistroFamily_t.RedHat;
if (Distro == Distro_t.YellowDog)
return DistroFamily_t.RedHat;
return DistroFamily_t.Unknown;
}
} // End Property DistroFamily
public static PackageManager_t PackageManager
{
get {
if (DistroFamily == DistroFamily_t.Debian)
return PackageManager_t.dpkg;
if (DistroFamily == DistroFamily_t.RedHat)
return PackageManager_t.rpm;
if(Distro == Distro_t.Arch)
return PackageManager_t.pacman;
if(Distro == Distro_t.Gentoo)
return PackageManager_t.portage;
if(Distro == Distro_t.Slackware)
return PackageManager_t.pkgtool;
if(Distro == Distro_t.Solaris)
return PackageManager_t.ips;
if(Distro == Distro_t.SunJDS)
return PackageManager_t.ips;
return PackageManager_t.unknown;
}
} // End Property PackageManager
// Release Files in /etc (from Unix.com)
// Novell SuSE---> /etc/SuSE-release
// Red Hat--->/etc/redhat-release, /etc/redhat_version
// Fedora-->/etc/fedora-release
// Slackware--->/etc/slackware-release, /etc/slackware-version
// Old Debian--->/etc/debian_release, /etc/debian_version
// New Debian--->/etc/os-release
// Mandrake--->/etc/mandrake-release
// Yellow dog-->/etc/yellowdog-release
// Sun JDS--->/etc/sun-release
// Solaris/Sparc--->/etc/release
// Gentoo--->/etc/gentoo-release
// cat /etc/issue
// CentOS Linux release 6.0 (Final)
// Kernel \r on an \m
// cat /proc/version
// uname -a
// If you are in a container, beware cat /proc/version will give the host distro, not the container one.
// http://unix.stackexchange.com/questions/35183/how-do-i-identify-which-linux-distro-is-running
public static Distro_t Distro
{
get{
string issue = null;
if (System.IO.File.Exists("/etc/issue"))
issue = System.IO.File.ReadAllText("/etc/issue", System.Text.Encoding.UTF8);
if (EmbeddedWebServer.StringHelpers.Contains(issue, "Ubuntu"))
return Distro_t.Ubuntu;
if (System.IO.File.Exists("/etc/os-release"))
return Distro_t.Debian; // New Debian
if (System.IO.File.Exists("/etc/debian_release"))
return Distro_t.Debian; // Old Debian
if (System.IO.File.Exists("/etc/gentoo-release"))
return Distro_t.Gentoo; // Not yet supported
if (System.IO.File.Exists("/etc/SuSE-release"))
return Distro_t.Suse;
if (EmbeddedWebServer.StringHelpers.Contains(issue, "CentOS"))
return Distro_t.CentOS;
if (System.IO.File.Exists("/etc/fedora-release"))
return Distro_t.Fedora;
if (System.IO.File.Exists("/etc/redhat_version"))
return Distro_t.Fedora;
// Unsupported
if (System.IO.File.Exists("/etc/mandrake-release"))
return Distro_t.Mandrake;
if (System.IO.File.Exists("/etc/slackware-release"))
return Distro_t.Slackware;
if (System.IO.File.Exists("/etc/yellowdog-release"))
return Distro_t.YellowDog;
if (System.IO.File.Exists("/etc/yellowdog-release"))
return Distro_t.YellowDog;
if (System.IO.File.Exists("/etc/sun-release"))
return Distro_t.SunJDS;
if (System.IO.File.Exists("/etc/release"))
return Distro_t.Solaris;
if (System.IO.File.Exists("/etc/UnitedLinux-release"))
return Distro_t.Solaris;
return Distro_t.Unknown;
} // End Get
} // End Property Distro
} // End Class DistroInfo
public class dpkg
{
public static bool HasDPKG()
{
// if (System.IO.File.Exists("/usr/bin/dpkg")) return true;
if (DistroInfo.PackageManager == DistroInfo.PackageManager_t.dpkg)
return true;
return false;
} // End Function HasDPKG
public static bool IsPackageInstalled(string packageName)
{
Process process = new Process();
process.StartInfo.FileName = "dpkg";
process.StartInfo.Arguments = "-s \"" + packageName + "\"";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
process.WaitForExit();
int result = process.ExitCode;
if (result == 0)
return true;
return false;
} // End Function IsPackageInstalled
public static string GetExecutable(string packageName)
{
Process process = new Process();
process.StartInfo.FileName = "dpkg";
process.StartInfo.Arguments = "-L \"" + packageName + "\"";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
//* Read the output (or the error)
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
if (output != null)
output = output.Replace("\r", "\n");
string[] lines = output.Split(new char[] { '\n' }, System.StringSplitOptions.RemoveEmptyEntries);
string executable = null;
foreach (string line in lines)
{
if (line.IndexOf("/bin/") != -1)
{
executable = line;
break;
}
}
return executable;
} // End Function GetExecutable
public static System.Collections.Generic.List<BrowserInfo> GetInstalledBrowsers()
{
return GetInstalledBrowsers(BrowserInfo.DefaultBrowserRating);
} // End Function GetInstalledBrowsers
public static System.Collections.Generic.List<BrowserInfo> GetInstalledBrowsers(BrowserRatingCallback_t browserRatingCallback )
{
System.Collections.Generic.List<BrowserInfo> ls = new System.Collections.Generic.List<BrowserInfo>();
System.Collections.Generic.List<string> packageList = GetPossibleBrowsers();
foreach (string packageName in packageList)
{
if (IsPackageInstalled(packageName))
{
int sort = browserRatingCallback(packageName);
ls.Add(new BrowserInfo()
{
Name = packageName
,Path = GetExecutable(packageName)
,Preference = sort
});
} // End if (isPackageInstalled(packageName))
} // Next packageName
ls.Sort();
return ls;
} // End Function GetInstalledBrowsers
public static System.Collections.Generic.List<string> GetPossibleBrowsers()
{
return SearchPackages("www-browser");
} // End Function GetPossibleBrowsers
public static System.Collections.Generic.List<string> SearchPackages(string categoryName)
{
System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();
Process process = new Process(); // e.g. apt-cache search www-browser
process.StartInfo.FileName = "apt-cache";
process.StartInfo.Arguments = "search \"" + categoryName + "\"";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
//* Read the output (or the error)
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
if (output != null)
output = output.Replace("\r", "\n");
string[] lines = output.Split(new char[] { '\n' }, System.StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
if (string.IsNullOrEmpty(line))
continue;
int pos = line.IndexOf(" ");
if (pos < 0)
continue;
string packageName = line.Substring(0, pos);
ls.Add(packageName);
} // Next line
return ls;
} // End Function SearchPackages
} // End Class dpkg
public class Win
{
public static System.Collections.Generic.List<BrowserInfo> GetPreferableBrowser(BrowserRatingCallback_t browserRatingCallback)
{
System.Collections.Generic.List<BrowserInfo> ls = new System.Collections.Generic.List<BrowserInfo>();
if (System.Environment.OSVersion.Platform == System.PlatformID.Unix)
return ls;
using (Microsoft.Win32.RegistryKey hklm = Microsoft.Win32.Registry.LocalMachine)
{
Microsoft.Win32.RegistryKey webClientsRootKey = hklm.OpenSubKey(#"SOFTWARE\Clients\StartMenuInternet");
if (webClientsRootKey != null)
foreach (var subKeyName in webClientsRootKey.GetSubKeyNames())
if (webClientsRootKey.OpenSubKey(subKeyName) != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell") != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open") != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command") != null)
{
string commandLineUri = (string)webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command").GetValue(null);
if (string.IsNullOrEmpty(commandLineUri))
continue;
commandLineUri = commandLineUri.Trim("\"".ToCharArray());
// viewer.Executable = commandLineUri;
string Name = (string)webClientsRootKey.OpenSubKey(subKeyName).GetValue(null);
ls.Add(new BrowserInfo()
{
Name = Name
,
Path = commandLineUri
,
Preference = browserRatingCallback(Name)
});
}
} // End Using
using (Microsoft.Win32.RegistryKey hklm = Microsoft.Win32.Registry.CurrentUser)
{
Microsoft.Win32.RegistryKey webClientsRootKey = hklm.OpenSubKey(#"SOFTWARE\Clients\StartMenuInternet");
if (webClientsRootKey != null)
foreach (var subKeyName in webClientsRootKey.GetSubKeyNames())
if (webClientsRootKey.OpenSubKey(subKeyName) != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell") != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open") != null)
if (webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command") != null)
{
string commandLineUri = (string)webClientsRootKey.OpenSubKey(subKeyName).OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command").GetValue(null);
if (string.IsNullOrEmpty(commandLineUri))
continue;
commandLineUri = commandLineUri.Trim("\"".ToCharArray());
// viewer.Executable = commandLineUri;
string Name = (string)webClientsRootKey.OpenSubKey(subKeyName).GetValue(null);
ls.Add(new BrowserInfo()
{
Name = Name
,
Path = commandLineUri
,
Preference = browserRatingCallback(Name)
});
}
} // End Using
ls.Sort();
return ls;
} // End Function GetPreferableBrowser
}
public class rpm
{
public rpm()
{
throw new System.NotImplementedException("TODO");
}
// # rpm -q --whatprovides webclient
//links-graphic-2.1-0.pre11.1mdk
//lynx-2.8.5-1mdk
//links-2.1-0.pre13.3mdk
//kdebase-common-3.2.3-134.8.101mdk
//mozilla-1.7.2-12.2.101mdk
//epiphany-1.2.8-4.2.101mdk
//wget-1.9.1-4.2.101mdk
// Another rough method is apropos
// This lists unexpected results too, and misses firefox as well as konqueror, who didn't filled the man-pages correctly.
//snx]->~ > apropos browser
//alevt (1) - X11 Teletext browser
//amrecover (8) - Amanda index database browser
//elinks (1) - lynx-like alternative character mode WWW browser
//gnome-moz-remote (1) - remote control of browsers.
//goad-browser (1) - Graphical GOAD browser
//links (1) - lynx-like alternative character mode WWW browser
//LinNeighborhood (1) - an SMB Network Browser
//lynx (1) - a general purpose distributed information browser for the World Wide Web
//mozilla-1.5 (1) - a Web browser for X11 derived from Netscape Communicator
//opera (1) - a graphical web browser
//sensible-browser (1) - sensible editing, paging, and web browsing
//smbtree (1) - A text based smb network browser
//www (1) - the W3C Line Mode Browser.
//www-browser (1) - a general purpose distributed information browser for the World Wide Web
//xfhelp (1) - lauches an HTML browser to display online documentation for
// "The Cholesterol Free Desktop Environment"
//viewres (1x) - graphical class browser for Xt
//htsserver (1) - offline browser server : copy websites to a local directory
//httrack (1) - offline browser : copy websites to a local directory
//webhttrack (1) - offline browser : copy websites to a local directory
} // End Class RPM
} // End Namespace
String-Helpers
using System;
using System.Collections.Generic;
using System.Text;
namespace EmbeddedWebServer
{
internal class StringHelpers
{
public static bool Contains(string source, string value)
{
if (source == null || value == null)
return false;
return System.Globalization.CultureInfo.InvariantCulture.CompareInfo.IndexOf(source, value, System.Globalization.CompareOptions.IgnoreCase) != -1;
}
}
}
And this is the actual usage:
public void OpenBrowser()
{
System.Collections.Generic.List<PlatformInfo.BrowserInfo> bi = PlatformInfo.BrowserInfo.GetPreferableBrowser();
string url = "\"" + "http://127.0.0.1:" + this.m_Port.ToString() + "/Index.htm\"";
if (bi.Count > 0)
{
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
psi.FileName =bi[0].Path;
psi.Arguments = url;
System.Diagnostics.Process.Start(psi);
return;
}
System.Diagnostics.Process.Start(url);
} // End Sub OpenBrowser
This solution seems to work for me:
RegistryKey browserKeys;
//on 64bit the browsers are in a different location
browserKeys = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\WOW6432Node\Clients\StartMenuInternet");
if (browserKeys == null)
browserKeys = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Clients\StartMenuInternet");
string[] browserNames = browserKeys.GetSubKeyNames();
Enjoy coding! Chagbert.

Categories

Resources