首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 實作簡易 Web 瀏覽器

     編輯:關於C語言

核心元件

使用 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;
}

開啟本地 HTML 檔案

private void mnuOpen_Click(object s, EventArgs e) {
    if (openFileDialog1.ShowDialog() == DialogResult.OK) {
        webBrowser1.DocumentText = File.ReadAllText(openFileDialog1.FileName, Encoding.GetEncoding("gb2312"));
    }
}

說明

本範例實作基本瀏覽、導航、重新整理、首頁、歷史記錄與開啟本地檔案功能,適合初學者參考。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved