Programming in C#

16. Using the Web in C#

In Visual Studio, it is now possible to add controls that can display web pages within your programs. Once you have your Window created, you can add the WebBrowser control from the Toolbox to your window.

The WebBrowser component will then take a URL and display it within the control and take care off all the formatting, layout and scripting execution for you. The component has a number of properties that you can configure within your project:

It is a good idea to add a TextBox so that the user can type in a web address of where to go. This can then be used to update the Url of the WebBrowser conrol.

private void Load_WebPage_Click(object sender, EventArgs e)
{
    string MyUrl;

    MyUrl = txt_Address.Text;

    if (MyUrl != "")
   {
      // Make sure url starts with HTTP protocol
      if (MyUrl.StartsWith("http://") == false & MyUrl.StartsWith("https://") == false)
      MyUrl = "http://" + MyUrl;

     try
    {
        webBrowser1.Navigate(new Uri(MyUrl, UriKind.RelativeOrAbsolute));
        Add_Url_to_History(MyUrl);
    }

      catch (SystemException sec) {
         Console.WriteLine(sec.Message);
      }
      catch (Exception x) {
           Console.WriteLine(x.Message);
      }

    } // End if
}

To ensure that the web control is changed, when the window is resized, you need to make sure the relative size of the control is set along with the window size.

private void Form1_Resize(object sender, EventArgs e)
{
    webBrowser1.Width = this.Width * 95 / 100;
    webBrowser1.Height = this.Height * 85 / 100;
}

If you want to keep a history of web pages, so that any pages the user visits, you can add then to an array. This history file can be loaded when the program starts and saved when the program is closed.

void Add_Url_to_History (string url)
{
Boolean found = false;
string entry = "";
Int32 n;

try
{
// Check if url has not already been added
Console.WriteLine("Checking web history");
if (web_counter > 1)
{
   for (n = 1; n < web_counter; n++)
   {
      entry = web_history[n];
      Console.WriteLine(n.ToString() + " : " + entry);
      if (entry.Contains(url))
          found = true;
     }
 }
Console.WriteLine("Found = " + found);
if (found == false)
{
   // Add page to history list
   web_history[web_counter] = url;
   Console.WriteLine("URL added to web history");
    web_counter = web_counter + 1;
    if (web_counter >= 80)
       web_counter = 1;

    // Add address to combo box
    txt_Address.Items.Add(url);
    Console.WriteLine("URL added to Combo box list");
  }
}
catch ( Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Web_counter = " + web_counter);
Console.WriteLine("URL = " + url);

}
}

Here is the result of my web program using the WebBrowser control.

It could be improved by adding some more buttons such as Back, Forward, Home, Print etc. But with this control and a few lines of code you can create your own web browser!