private static Bitmap GetWindow(IntPtr hWnd) { IntPtr hscrdc = WindowApi.GetWindowDC(hWnd); Control control = Control.FromHandle(hWnd); IntPtr hbitmap = WindowApi.CreateCompatibleBitmap(hscrdc, control.Width, control.Height); IntPtr hmemdc = WindowApi.CreateCompatibleDC(hscrdc); WindowApi.SelectObject(hmemdc, hbitmap); WindowApi.PrintWindow(hWnd, hmemdc, 0); Bitmap bmp = Bitmap.FromHbitmap(hbitmap); WindowApi.DeleteDC(hscrdc); //删除用过的对象 WindowApi.DeleteDC(hmemdc); //删除用过的对象 return(bmp); }
/// <summary> /// 控件(窗口)的截图,控件被其他窗口(而非本窗口内控件)遮挡时也可以正确截图,使用BitBlt方法 /// </summary> /// <param name="control">需要被截图的控件</param> /// <returns>该控件的截图,控件被遮挡时也可以正确截图</returns> public static Bitmap captureControl(Control control) { //调用API截屏 IntPtr hSrce = WindowApi.GetWindowDC(control.Handle); IntPtr hDest = WindowApi.CreateCompatibleDC(hSrce); IntPtr hBmp = WindowApi.CreateCompatibleBitmap(hSrce, control.Width, control.Height); IntPtr hOldBmp = WindowApi.SelectObject(hDest, hBmp); if (WindowApi.BitBlt(hDest, 0, 0, control.Width, control.Height, hSrce, 0, 0, CopyPixelOperation.SourceCopy | CopyPixelOperation.CaptureBlt)) { Bitmap bmp = Image.FromHbitmap(hBmp); WindowApi.SelectObject(hDest, hOldBmp); WindowApi.DeleteObject(hBmp); WindowApi.DeleteDC(hDest); WindowApi.ReleaseDC(control.Handle, hSrce); // bmp.Save(@"a.png"); // bmp.Dispose(); return(bmp); } return(null); }