Windows Forms 2.0 – WebBrowser Control Recipes

Posted by: Suprotim Agarwal , on 3/26/2007, in Category WinForms & WinRT
Views: 30823
Abstract: In this article, we will explore how to perform some common tasks using the WebBrowser Control of Windows Forms 2.0.
Windows Forms 2.0 – WebBrowser Control Recipes
 
The WebBrowser control lets you host browser-enabled documents and pages into any Form-derived type application. In .NET 1.0 and 1.1, you could use a Web browser window through COM interop, which had its own drawbacks for deployment and versioning. In .NET 2.0, it has been included as a new Managed wrapper, of the WebBrowser ActiveX control .
How Do I Get Started With The WebBrowser Control
 
Nowadays, applications need to display web content and other such related files. With the inclusion of this control in .NET 2.0, you can place this control on a form to provide an integrated Web-based help or Web browsing capabilities in your application or use the control to add DHTML-based user interface elements to your form. Additionally, you can also use this control to add your existing Web-based widgets to your Windows Form applications, as well as provide support for printing and saving web documents. In short, this control gives you a full-featured IE browser, that can be embedded in your application and all this comes without the need to virtually code anything.
To Create a simple WebBrowser application, add a WebBrowser control and a textbox to the form as shown in the Figure --. When you type a URL into the textbox(txtURL) and press ENTER, the WebBrowser control navigates to the URL specified, in this case the URL is www.seedinfotech.com, the organization I work for.
 
The following example demonstrates how to use the Navigate method to implement an address bar similar to the one in Internet Explorer.
 
The following code example demonstrates how to navigate to the URL in the textbox when the ENTER key is pressed.
 
// Navigates to the URL in the textbox when the ENTER key is pressed while the textBox has focus.
private void txtURL_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        GoTo(txtURL.Text);
    }
}
 
// Navigates to the given valid URL. The same function can also be called on the
// Click of a button.
private void GoTo(String strUrl)
{
    if (String.IsNullOrEmpty(strUrl)) return;
    if (strUrl.Equals("about:blank")) return;
    if (!strUrl.StartsWith("http://"))
            strUrl = "http://" + strUrl;
    try
    {
        // Loads the document into the WebBrowser Control
        webBrowser1.Navigate(new Uri(strUrl));
    }
    catch (System.UriFormatException)
    {
        return;
    }
}
 
How Do I Navigate Back And Forth Using The WebBrowser
When the Navigate method is called, the WebBrowser control navigates to the specified site and adds it to a history list. The control also stores Web pages from recently visited sites in a cache on the local hard disk. This saves browsing time as the control serves a cached version whenever the page is re-visited.
Use the GoBack method to navigate to a previous page in the navigation history, if one is available. Similarly, the GoForward method allows you to return to a later page in the navigation history. To navigate the WebBrowser control to the home page of the current user, use the GoHome method.
 
private void btnBack_Click(object sender, EventArgs e)
{
        wbMyBrowser.GoBack();
}
 
private void btnForward_Click(object sender, EventArgs e)
{
       wbMyBrowser.GoForward();
}
 
To avoid the cached version, use the Refresh method of the WebBrowser control to reload the current page by downloading it. This ensures that the control displays the latest version of the webpage.
 
Note : Use the CanGoBack property to determine whether the navigation history is available and contains a previous page. The property returns true if the control can navigate backward; otherwise, false. Using this you can disable a back button if the property returns false Eg: btnback.Enabled = wbMyBrowser.CanGoBack;
 
Similarly, the CanGoForward property is used to determine whether the navigation history is available and a page is located after the current one.
 
How Do I Use A Progress Bar In A WebBrowser
 
To display a navigation progress bar similar to the one in Internet Explorer, use the ProgressChanged Event of the WebBrowser Control. This event occurs when the control supplies information on the download progress of a page it is navigating to.
The WebBrowserProgressChangedEventArgs.CurrentProgress property can be used to determine the number of bytes downloaded.
Similarly, the WebBrowserProgressChangedEventArgs.MaximumProgress property can be used to determine the number of bytes available for downloading.
private void wbMyBrowser_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
{
progBar.Value = (int)(e.CurrentProgress / e.MaximumProgress);
this.Refresh();
}
 
How Do I Add An Auto-Complete Text Box To Navigate A Url
This can be achieved using just 2 properties of the TextBox Control
AutoCompleteMode - automatically completes input strings by comparing the prefix being entered to the prefixes of all strings in a maintained source.
The table has been taken from MSDN.
 
Append
Appends the remainder of the most likely candidate string to the existing characters, highlighting the appended characters. 
None
Disables the automatic completion feature for the ComboBox and TextBox controls. 
Suggest
Displays the auxiliary drop-down list associated with the edit control. This drop-down is populated with one or more suggested completion strings. 
SuggestAppend
Applies both Suggest and Append options
 
AutoCompleteSource –
AllUrl
Specifies the equivalent of HistoryList and RecentlyUsedList as the source. 
CustomSource
Specifies strings from a built-in AutoCompleteStringCollection as the source. 
FileSystem
Specifies the file system as the source. 
FileSystemDirectories
Specifies that only directory names and not file names will be automatically completed. 
HistoryList
Includes the Uniform Resource Locators (URLs) in the history list. 
ListItems
Specifies that the items of the ComboBox represent the source. 
None
Specifies that no AutoCompleteSource is currently in use. This is the default value of AutoCompleteSource
RecentlyUsedList
Includes the Uniform Resource Locators (URLs) in the list of those URLs most recently used. 
AllSystemSources
Specifies the equivalent of FileSystem and AllUrl as the source. This is the default value when AutoCompleteMode has been set to a value other than the default
 
If you need to achieve this programmatically, you can use the following code :
tsTxtBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend
tsTxtBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource
 
 How Do I Use The WebBrowser Control To Print A Web Page Without Displaying It
Use the following code to Print a Web Page without displaying it :
private void btnPrint_Click(object sender, EventArgs e)
{
     // Add an event handler that prints the document after it lods.
    wbMyBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(PrintDocument);
 
   // Set the Url property to load the document.
    wbMyBrowser.Url = new Uri(@"YourHtmlFile.htm");
}
 
        private void PrintDocument(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            // Print the document now that it is fully loaded.
            ((WebBrowser)sender).Print();
 
            // Dispose the WebBrowser now that the task is complete.
            ((WebBrowser)sender).Dispose();
        }
 
How Do I Use The WebBrowser Control to Print Web Pages
 
The WebBrowser control can be used to print the document currently displayed in the WebBrowser control or print a document without opening it.
To do this, after the document finishes loading, you can handle the DocumentCompleted event to receive a notification. The Print() method can then be used here to print the document. If you need to see a preview before printing, use the ShowPrintPreviewDialog method to display the Print Preview dialog box. After the preview gets displayed, click the Print button on the Print Preview box.
 
private void btnPrintWoOpening_Click(object sender, EventArgs e)
{
          // Add an event handler that prints the document after it loads.
     wbMyBrowser.DocumentCompleted+=new                 WebBrowserDocumentCompletedEventHandler (PrintDocument);
 
            // Set the Url property to load the document.
            //wbMyBrowser.Url = new Uri(@"YourHtmlFile.htm");
            wbMyBrowser.Navigate("www.saama.com");
 }
 
 private void PrintDocument(object sender, WebBrowserDocumentCompletedEventArgs e)
{
            // Print the document now that it is fully loaded.
            ((WebBrowser)sender).Print();
 
}
 
Note : To check for certain conditions before printing, you can handle the Navigating event. 
Note : To access the contents of the displayed page using the DOM object, use the Document, DocumentStream or DocumentText property when the DocumentCompleted event occurs.
 
Conclusion :
 
In this article, we saw a recipe approach to performing some of the most common tasks with the WebBrowser Control. I hope the article was useful and I thank you for viewing it.
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by amruta kelkar on Wednesday, January 2, 2008 2:43 AM
excellenttttt article very helpfullll
Comment posted by Som on Tuesday, May 13, 2008 6:02 AM
Good article. Very Helpful.
Comment posted by Tom on Tuesday, September 2, 2008 1:27 PM
Any chance you could contact me regarding IMAGES.  Particularly, how to capture images without referencing the <img> tag src.

Thanks!
Comment posted by solasa subhash on Tuesday, July 12, 2011 1:07 AM
thank you your code is very nice

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

FREE .NET MAGAZINES

Free DNC .NET Magazine

Tags

JQUERY COOKBOOK

jQuery CookBook