Figure 14-6 shows the execution screen of the program example Ch14_demoform006.cs. We found that when you click a button on a form, you start the default browser and connect to the specified URL. The related program code is written in the Click event handler for the button, as follows:
Figure 14-6
Use the Start method of the Process class to start the default browser and specify the URL, FTP, or file you want to open. Because the Start method is a shared method, you do not need to create an instance of the process class to invoke the Start method. For example, the following is the correct wording:
string target = "http://liminzhang.cnblogs.com/";
System.Diagnostics.Process.Start(target); or string target = "ftp:// ftp.microsoft.com";
System.Diagnostics.Process.Start(target);or string target = @"C:\Program Files\Microsoft
Visual Studio .NET 2005\readme.htm";
System.Diagnostics.Process.Start(target);
When you call the Start method, you take advantage of the default UseShellExecute property, so you do not need an explicit query login (Registry) to verify which browser is the default browser. However, if you use this method on a computer that does not have a default browser installed, an exception will be thrown. You should try to intercept this exception in order to take the appropriate path. For this reason, this example uses a try ... Catch blocks to intercept errors when the required login password is not found. In addition, a general exception handling function is provided to intercept other possible errors.
Try ... The complete program code for the Catch block is listed as follows:
try
{
System.Diagnostics.Process.Start(target);
}
catch (System.ComponentModel.Win32Exception noBrowser)
{
MessageBox.Show(noBrowser.Message);
}