/// <summary> /// 截取指定句柄窗口的图像, 也可也截屏 /// <para>当然 当前封装是依赖传入参数获取窗口大小,也可以使用API自动获取</para> /// <para>该方法可以直接生成缩略图, 通过 widthDest 和 heightDest 置顶缩略图宽高</para> /// </summary> /// <param name="handle"></param> /// <param name="widthSrc"></param> /// <param name="heightSrc"></param> /// <param name="widthDest"></param> /// <param name="heightDest"></param> /// <returns></returns> public static Bitmap CaptureWindow(IntPtr handle, int widthSrc, int heightSrc, int widthDest, int heightDest) { try { // get the hDC of the target window IntPtr hdcSrc = User32.GetWindowDC(handle); // create a device context we can copy to IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc); // create a bitmap we can copy it to, // using GetDeviceCaps to get the width/height IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc, widthDest, heightDest); // select the bitmap object IntPtr hOld = GDI32.SelectObject(hdcDest, hBitmap); // 设置高质量的缩放模式 GDI32.SetStretchBltMode(hdcDest, GDI32.STRETCH_HALFTONE); // 如果 缩放模式设置为 GDI32.STRETCH_HALFTONE, 则必须调用下面的方法 GDI32.POINTAPI point; GDI32.SetBrushOrgEx(hdcDest, 0, 0, out point); // bitblt over GDI32.StretchBlt(hdcDest, 0, 0, widthDest, heightDest, hdcSrc, 0, 0, widthSrc, heightSrc, GDI32.SRCCOPY); // restore selection GDI32.SelectObject(hdcDest, hOld); // clean up GDI32.DeleteDC(hdcDest); User32.ReleaseDC(handle, hdcSrc); // get a .NET image object for it Bitmap img = Image.FromHbitmap(hBitmap); // free up the Bitmap object GDI32.DeleteObject(hBitmap); return(img); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(null); }