溫馨提示×

C#中如何實現WebBrowser控件的網頁縮放功能

c#
小樊
261
2024-08-12 05:11:37
欄目: 編程語言

可以通過WebBrowser控件的Document對象的Window對象的execScript方法來實現網頁的縮放功能。具體步驟如下:

  1. 將WebBrowser控件的Document對象賦值給一個HTMLDocument對象。

  2. 使用HTMLDocument對象的parentWindow屬性獲取Window對象。

  3. 使用Window對象的execScript方法執行JavaScript代碼來改變網頁的縮放比例。

以下是一個簡單的示例代碼:

private void btnZoomIn_Click(object sender, EventArgs e)
{
    if (webBrowser1.Document != null)
    {
        HTMLDocument doc = webBrowser1.Document.DomDocument as HTMLDocument;
        if (doc != null)
        {
            IHTMLWindow2 window = (IHTMLWindow2)doc.parentWindow;
            if (window != null)
            {
                window.execScript("document.body.style.zoom = '150%'", "JavaScript");
            }
        }
    }
}

private void btnZoomOut_Click(object sender, EventArgs e)
{
    if (webBrowser1.Document != null)
    {
        HTMLDocument doc = webBrowser1.Document.DomDocument as HTMLDocument;
        if (doc != null)
        {
            IHTMLWindow2 window = (IHTMLWindow2)doc.parentWindow;
            if (window != null)
            {
                window.execScript("document.body.style.zoom = '100%'", "JavaScript");
            }
        }
    }
}

在上面的示例代碼中,btnZoomIn_Click和btnZoomOut_Click方法分別實現了網頁的放大和縮小功能。當用戶點擊放大按鈕時,執行JavaScript代碼使網頁的縮放比例變為150%;當用戶點擊縮小按鈕時,執行JavaScript代碼使網頁的縮放比例變為100%。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女