How to create a Web Browser in C#
By FoxLearn 11/12/2024 9:56:23 AM 6.45K
This control allows you to embed web browsing capabilities directly within your form.
Open Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "AppWebBrowser" and then click OK
In the Form Designer, drag the WebBrowser, Button, Table, TextBox controls from the Toolbox onto your form, then design your form as below.
Double-click on the Go
button to create an event handler for clicking the button, and do the same for the Back
button.
In the Form1.cs
code file, you will add logic for navigating the web as shown below.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AppWebBrowser { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void txtUrl_KeyPress(object sender, KeyPressEventArgs e) { //Enter key if (e.KeyChar == (char)13) webBrowser.Navigate(txtUrl.Text); } // Go back to the previous page private void btnBack_Click(object sender, EventArgs e) { webBrowser.GoBack(); } private void btnForward_Click(object sender, EventArgs e) { webBrowser.GoForward(); } // Reload page private void btnRefresh_Click(object sender, EventArgs e) { webBrowser.Refresh(); } // Navigate to the URL entered in the text box private void btnGo_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtUrl.Text)) webBrowser.Navigate(txtUrl.Text); } } }
The btnGo_Click
event handler takes the text from txtUrl
(a TextBox
) and navigates the WebBrowser
control to that URL.
VIDEO TUTORIAL