C#及wpf WebBrowser截圖

最靠譜的截圖源碼,直接拿去用,返回的ImageSource可以直接設置給Image控件

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Media;

namespace Base
{
    class WebScreenshot
    {
        [DllImport("user32.dll")]
        private static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, uint nFlags);

        /// <summary>
        /// 對一個WebBrowser進行截圖
        /// </summary>
        /// <param name="targetBrowser">我這裏用的是Forms的WebBrowser,如果是wpf的,請自己改成Controls並調整參數</param>
        /// <returns></returns>
        public static ImageSource BrowserSnapShot(System.Windows.Forms.WebBrowser targetBrowser)
        {
            // 獲取寬高
            int screenWidth = (int)targetBrowser.Width;
            int screenHeight = (int)targetBrowser.Height;

            IntPtr myIntptr = targetBrowser.Handle;
            int hwndInt = myIntptr.ToInt32();
            IntPtr hwnd = myIntptr;
            //創建圖形
            System.Drawing.Bitmap bm = new System.Drawing.Bitmap(screenWidth, screenHeight, System.Drawing.Imaging.PixelFormat.Format16bppRgb555);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bm);
            IntPtr hdc = g.GetHdc();

            //調用api 把hwnd的內容用圖形繪製到hdc 如果你有代碼潔癖 可以不使用api 使用g.CopyFromScreen,請自行研究
            bool result = PrintWindow(hwnd, hdc, 0);
            g.ReleaseHdc(hdc);
            g.Flush();


            if (result == true) //成功 轉換並返回ImageSource
            {
                ImageSourceConverter imageSourceConverter = new ImageSourceConverter();
                MemoryStream stream = new MemoryStream();
                bm.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                return (ImageSource)imageSourceConverter.ConvertFrom(stream);
            }
            return null;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章