使用 Windows Forms WebBrowser 控制項,搭配工具列按鈕、位址列與狀態列。
private void Navigate(string url) {
if (string.IsNullOrEmpty(url)) return;
if (!url.StartsWith("https://")) url = "https://" + url;
try {
Cursor.Current = Cursors.WaitCursor;
webBrowser1.Navigate(new Uri(url));
} catch (UriFormatException) { return; }
finally { Cursor.Current = Cursors.Default; }
}
// 導航按鈕
private void btnBack_Click(object s, EventArgs e) => webBrowser1.GoBack();
private void btnForward_Click(object s, EventArgs e) => webBrowser1.GoForward();
private void btnRefresh_Click(object s, EventArgs e) => webBrowser1.Refresh();
private void btnHome_Click(object s, EventArgs e) => webBrowser1.GoHome();
// 位址列 Enter 導航
private void cmbUrl_KeyDown(object s, KeyEventArgs e) {
if (e.KeyCode == Keys.Enter) {
Navigate(cmbUrl.Text);
if (!cmbUrl.Items.Contains(cmbUrl.Text)) cmbUrl.Items.Add(cmbUrl.Text);
}
}
// 視窗大小調整
private void Form1_Resize(object s, EventArgs e) {
webBrowser1.Width = this.Width - 25;
webBrowser1.Height = this.Height - 130;
cmbUrl.Width = this.Width - 55;
}
private void mnuOpen_Click(object s, EventArgs e) {
if (openFileDialog1.ShowDialog() == DialogResult.OK) {
webBrowser1.DocumentText = File.ReadAllText(openFileDialog1.FileName, Encoding.GetEncoding("gb2312"));
}
}
本範例實作基本瀏覽、導航、重新整理、首頁、歷史記錄與開啟本地檔案功能,適合初學者參考。