Subscribe to Blog.Parse(typeof(PsychoCoder), Richard McCutchen);        RSS Feed
-----

Get default browser & more in C#

Icon 8 Comments
Recently there have been quite a few of the same question asked of me (and others on Dream.In.Code) and that's how, from their application, they can get the users default web browser, say for opening a support site or registration element, and open if from within their application (Valid question if you ask me as the application I'm currently working on requires the same functionality)

One of the better solutions I came up with was to search the users registry (the HKEY_CLASSES_ROOT\HTTP\\shell\\open\\command key) and get the default value like this

/// <summary>
/// method for retrieving the users default web browser
/// </summary>
/// <returns></returns>
internal string GetSystemDefaultBrowser()
{
	string name = string.Empty;
	RegistryKey regKey = null;

	try
	{
		//set the registry key we want to open
		regKey = Registry.ClassesRoot.OpenSubKey("HTTP\\shell\\open\\command", false);

		//get rid of the enclosing quotes
		name = regKey.GetValue(null).ToString().ToLower().Replace("" + (char)34, "");

		//check to see if the value ends with .exe (this way we can remove any command line arguments)
		if (!name.EndsWith("exe"))
			//get rid of all command line arguments (anything after the .exe must go)
			name = name.Substring(0, name.LastIndexOf(".exe") + 4);

	}
	catch (Exception ex)
	{
		name = string.Format("ERROR: An exception of type: {0} occurred in method: {1} in the following module: {2}", ex.GetType(), ex.TargetSite, this.GetType());
	}
	finally
	{
		//check and see if the key is still open, if so
		//then close it
		if (regKey != null)
			regKey.Close();
	}
	//return the value
	return name;

}



Then from within your application you can use it on a controls click event, say a PictureBox, like this. I would create a new method (for my implementation it opens a support site for an application I'm working on), which looks like this

internal bool OpenSupportSite(string url)
{
	string browser = GetSystemDefaultBrowser();
	if (!browser.Contains("ERROR"))
	{
		Process process = new Process();
		process.StartInfo.FileName = browser;
		process.StartInfo.Arguments = url;
		process.Start();
		return true;
	}
	else
	{
		MessageBox.Show(string.Format("{0}", browser), "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
		return false;
	}
	
}



Then in the PictureBox click event I use this
void pictureBox1_Click(object sender, EventArgs e)
{
	//NOTE: site is a variable holding the url of the site
	DialogResult result = MessageBox.Show(string.Format("This will open the {0} homepage, do you want to continue?", site), "Open Site?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

	if (result == DialogResult.Yes)
		if (obj.isConnectionAvailable())
			OpenSupportSite(@"http://www.utilasoft.com");
		else
			MessageBox.Show("No internet connection was found.");
}



NOTE: isConnectionAvailable uses the Ping Class to determine if an Internet connection is available so I'll offer that snippet as well since it's mentioned in the code.

/// <summary>
/// Method used to check for internet connectivity by piging
/// varoaus websites and looking for the response.
/// </summary>
/// <returns>True if a ping succeeded, False if otherwise.</returns>
/// <remarks></remarks>
public bool isConnectionAvailable()
{
	//build a list of sites to ping, you can use your own
	string[] sites = { "www.bing.com", "dreamincode.net" };
	//create an instance of the System.Net.NetworkInformation Namespace
	Ping ping = new Ping();
	//Create an instance of the PingReply object from the same Namespace
	PingReply pingReply;
	//int variable to hold # of pings not successful
	int badPing = 0;
	try
	{
		//start a loop that is the lentgh of th string array we
		//created above
		for (int i = 0; i <= sites.Length; i++)
		{
			//use the Send Method of the Ping object to send the
			//Ping request
			pingReply = ping.Send(sites[i], 10);
			//now we check the status, looking for,
			//of course a Success status
			if (pingReply.Status != IPStatus.Success)
			{
				//now valid ping so increment
				badPing++;
			}
			//check to see if any pings came back
			if (badPing == sites.Length)
			{
				return false;
				//comment this back in if you have your own exception
				//library you use for you applications (use you own
				//exception names)
				//throw new ConnectivityNotFoundException(@"There doest seem to be a network/internet connection.\r\n 
				//Please contact your system administrator");
				//use this is if you don't your own custom exception library
				throw new Exception(@"There doest seem to be a network/internet connection.\r\n 
			Please contact your system administrator");
			}
			else
			{
				return true;
			}
		}
		return true;
	}
	//comment this back in if you have your own excerption
	//library you use for you applications (use you own
	//exception names)
	//catch (ConnectivityNotFoundException ex)
	//use this line if you don't have your own custom exception 
	//library
	catch (Exception ex)
	{
		//MessageBox.Show(ex.Message);
		return false;
	}
}



And there you go, you can now get the users default browser and open it to a specific URL with this code. Thanks for reading and happy coding! :)

8 Comments On This Entry

Page 1 of 1

eclipsed4utoo Icon

20 January 2010 - 12:22 PM
If you are simply wanting to open a link in the user's default browser, there is no need to look in the registry or doing anything fancy. Simply use the Process.Start and pass it the URL.

Process.Start("http://www.google.com");



The link will open in the user's default browser.
0

remorseless Icon

20 January 2010 - 08:05 PM

eclipsed4utoo, on 21 Jan, 2010 - 04:22 AM, said:

If you are simply wanting to open a link in the user's default browser, there is no need to look in the registry or doing anything fancy. Simply use the Process.Start and pass it the URL.

Process.Start("http://www.google.com");



The link will open in the user's default browser.


That was not the point, it was more about how to get, use and maybe even change the user's default browser using C#. Very nice tutorial btw.
0

eclipsed4utoo Icon

22 January 2010 - 08:18 AM

remorseless, on 20 Jan, 2010 - 11:05 PM, said:

eclipsed4utoo, on 21 Jan, 2010 - 04:22 AM, said:

If you are simply wanting to open a link in the user's default browser, there is no need to look in the registry or doing anything fancy. Simply use the Process.Start and pass it the URL.

Process.Start("http://www.google.com");



The link will open in the user's default browser.


That was not the point, it was more about how to get, use and maybe even change the user's default browser using C#. Very nice tutorial btw.


Whether it was the point or not, he used the code to simply open a webpage with the default browser. Now if you want to know the default browser, or want to change it, then yeah, this would be perfect. But if you are simply wanting to open a URL in the default browser, it's not needed....which is why I preceded my post with that statement.

I didn't want a visitor to see this post and say, "Ok, to open a link in the default browser, I need to use Psycho's code". It would be overkill.

Not trying to take anything away from the tutorial. It's a great tutorial, which most of Psycho's tutorials are.
0

PsychoCoder Icon

23 January 2010 - 10:30 AM
@eclipsed4utoo I am the exception to the rule, and proof that that single line of code does not work 100% of the time (For me on my machine it always opens IE yet Firefox is my default browser), thus the reason for coming up with this code, so I would have something that works 150% of the time
0

eclipsed4utoo Icon

25 January 2010 - 07:17 AM

PsychoCoder, on 23 Jan, 2010 - 01:30 PM, said:

@eclipsed4utoo I am the exception to the rule, and proof that that single line of code does not work 100% of the time (For me on my machine it always opens IE yet Firefox is my default browser), thus the reason for coming up with this code, so I would have something that works 150% of the time


What version of .Net are you using? I assume you are on Windows 7? I have tried in both .Net 2.0 and .Net 3.5 in Windows XP and it works 100% of the time for Firefox, Chrome, and IE when each is set as the default browser.
0

PsychoCoder Icon

25 January 2010 - 09:30 AM
I'm using Windows 7 with .Net Framework 3.5 SP1 and sometimes it opened the default browser, but just as many times it opens in IE (which hasn't been my default since the real early 90's.

I got tired of fighting with it, and I wont release a piece of software unless it's 110% bug-free, and definitely not with a bug I know happens, but not all the time. Plus this application needed to have the ability to change the users default browser, thus this code was written and tested, and tested, and did I mention tested?
0

eclipsed4utoo Icon

25 January 2010 - 09:37 AM

PsychoCoder, on 25 Jan, 2010 - 12:30 PM, said:

I'm using Windows 7 with .Net Framework 3.5 SP1 and sometimes it opened the default browser, but just as many times it opens in IE (which hasn't been my default since the real early 90's.

I got tired of fighting with it, and I wont release a piece of software unless it's 110% bug-free, and definitely not with a bug I know happens, but not all the time. Plus this application needed to have the ability to change the users default browser, thus this code was written and tested, and tested, and did I mention tested?


Good to know. I haven't tested my code on Windows 7, but will be soon. I guess I need to change my application for the possibility of somebody installing it on Windows 7.
0

GustavWeler Icon

21 February 2010 - 01:02 PM
I don't think that this code is taking UserChoice into consideration. My default http handler is defined in HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice, not in the generic HKCR.

Also, although it's unlikely, a user could have different browsers chosen for http and https. Process.Start that eclipsed4utoo suggested would be the way to go for true accuracy if wanting to ~~launch~~ something in the default browser.

This is how it works on Windows 7. Perhaps it does in Vista as well, but I don't know since I skipped over that OS.
0
Page 1 of 1

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

October 2014

S M T W T F S
   1234
567891011
12131415161718
192021 22 232425
262728293031 

Recent Entries

Search My Blog

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)