Advanced 15 min read Control #29

WebBrowser Control

WebBrowser embeds a web browser in your Windows Forms application. You can navigate to websites, display HTML content, and interact with web pages.

What is a WebBrowser?

WebBrowser control uses the Internet Explorer engine (or Edge in newer versions) to display web content. It's perfect for embedded help, web-based UI, and displaying web pages within your app.

Code Example

// Navigate to a URL
webBrowser1.Navigate("https://www.google.com");

// Navigate to a local HTML file
webBrowser1.Navigate("C:\\help\\index.html");

// Display HTML content directly
string html = "<html><body><h1>Hello from C#!</h1><p>This is embedded HTML.</p></body></html>";
webBrowser1.DocumentText = html;

// Handle navigation events
private void webBrowser1_Navigating(object sender, 
    WebBrowserNavigatingEventArgs e)
{
    // Show loading indicator
    lblStatus.Text = "Loading: " + e.Url;
}

private void webBrowser1_DocumentCompleted(object sender, 
    WebBrowserDocumentCompletedEventArgs e)
{
    // Hide loading indicator
    lblStatus.Text = "Done";
}

// Go back/forward
private void btnBack_Click(object sender, EventArgs e)
{
    if (webBrowser1.CanGoBack)
        webBrowser1.GoBack();
}

private void btnForward_Click(object sender, EventArgs e)
{
    if (webBrowser1.CanGoForward)
        webBrowser1.GoForward();
}

// Refresh
webBrowser1.Refresh();

Exercise

Task: Create a simple web browser application.

  1. Add a WebBrowser with Dock = Fill.
  2. Add a ToolStrip with: Back, Forward, Refresh, Home buttons.
  3. Add a ComboBox or TextBox for URL entry.
  4. Navigate when the user presses Enter or clicks Go.
  5. Show page title in the form title.
  6. Add a StatusStrip showing loading status.
  7. Add keyboard shortcuts (F5 for Refresh).
Key Takeaway

WebBrowser embeds web content in your app. Use it for help systems, web-based UI, and displaying external content.