https://
public partial class BrowserForm : Form
{
public BrowserForm() { InitializeComponent(); }
private void Navigate(string address)
{
if (string.IsNullOrWhiteSpace(address)) return;
if (address == "about:blank") return;
if (!address.StartsWith("https://") && !address.StartsWith("https://"))
address = "https://" + address;
try
{
Cursor.Current = Cursors.WaitCursor;
webBrowser1.Navigate(new Uri(address));
}
catch (UriFormatException) { /* 忽略無效網址 */ }
finally { Cursor.Current = Cursors.Default; }
}
private void Form1_Load(object sender, EventArgs e)
{
// 工具列圖示綁定
toolStrip1.ImageList = imageList1;
btnBack.ImageIndex = 0; btnForward.ImageIndex = 1;
btnRefresh.ImageIndex = 2; btnHome.ImageIndex = 3;
}
private void txtUrl_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Navigate(txtUrl.Text);
if (!txtUrl.Items.Contains(txtUrl.Text)) txtUrl.Items.Add(txtUrl.Text);
}
}
private void btnBack_Click(object sender, EventArgs e) => webBrowser1.GoBack();
private void btnForward_Click(object sender, EventArgs e) => webBrowser1.GoForward();
private void btnRefresh_Click(object sender, EventArgs e)
{
if (webBrowser1.Url?.ToString() != "about:blank") webBrowser1.Refresh();
}
private void btnHome_Click(object sender, EventArgs e) => webBrowser1.GoHome();
private void txtUrl_SelectedIndexChanged(object sender, EventArgs e) => Navigate(txtUrl.Text);
private void mnuOpen_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string html = File.ReadAllText(openFileDialog1.FileName, Encoding.GetEncoding("gb2312"));
webBrowser1.DocumentText = html;
}
}
private void mnuExit_Click(object sender, EventArgs e) => Close();
private void BrowserForm_Resize(object sender, EventArgs e)
{
webBrowser1.Width = ClientSize.Width - 25;
webBrowser1.Height = ClientSize.Height - 130;
txtUrl.Width = ClientSize.Width - 55;
}
private void btnSearch_Click(object sender, EventArgs e) => webBrowser1.GoSearch();
}
Navigate, GoBack, GoForward, Refresh, GoHome, GoSearch, DocumentText 等高層 API。new Uri(address) 攔截格式錯誤。Encoding.GetEncoding("gb2312") (或 UTF-8) 避免亂碼。Resize 事件中依客戶區大小調整控制項尺寸。CoreWebView2.Navigate(), GoBack(), ExecuteScriptAsync()。Microsoft.Web.WebView2,需目標機器安裝 WebView2 Runtime (或隨應用程式部署 Fixed Version)。本範例適合教學、簡易內部工具、舊版相容專案;新專案**強烈建議直接採用 WebView2**。