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

.NET 使用 WebBrowser 控件獲取網頁截圖(WinForms 方案)

     編輯:ASP.NET 基礎

適用場景

WinForms / WPF 桌面應用中需生成網頁縮略圖或全頁截圖。注意:ASP.NET 服務端不支持 WebBrowser 控件(無 UI 消息泵、權限受限),請勿用於 Web 項目。

完整 WinForms 代碼

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private WebBrowser _webBrowser;

        public Form1()
        {
            InitializeComponent();
        }

        public void GetThumbNail(string url)
        {
            _webBrowser = new WebBrowser();
            _webBrowser.ScrollBarsEnabled = false;
            _webBrowser.Navigate(url);
            _webBrowser.DocumentCompleted += Completed;

            // 等待加載完成(同步等待,UI 線程需 DoEvents 防假死)
            while (_webBrowser.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
        }

        private void Completed(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            // 設置控件大小為文檔實際大小,截取完整頁面
            _webBrowser.Width = _webBrowser.Document.Body.ScrollRectangle.Width;
            _webBrowser.Height = _webBrowser.Document.Body.ScrollRectangle.Height;

            using (Bitmap bmp = new Bitmap(_webBrowser.Width, _webBrowser.Height))
            {
                _webBrowser.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
                bmp.Save("Capture.png", System.Drawing.Imaging.ImageFormat.Png);
                pictureBox1.ImageLocation = "Capture.png"; // 界面顯示
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            GetThumbNail(textBox1.Text);
        }
    }
}

關鍵點

  • Application.DoEvents() 保持消息泵運行,確保 DocumentCompleted 觸發。
  • DrawToBitmap 將控件繪製到位圖,支持超出可視區域的完整頁面。
  • 異步改進:可使用 TaskCompletionSource 封裝為 async/await 模式,避免阻塞 UI 線程。

服務端替代方案

ASP.NET Core / .NET 6+ 服務端截圖推薦使用 Puppeteer Sharp(無頭 Chrome)或 Playwright,支持現代 CSS/JS、無 UI 依賴、可容器化部署。

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