失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 【 WinForm】全屏截图 控件截图 句柄截图

【 WinForm】全屏截图 控件截图 句柄截图

时间:2024-04-21 14:17:46

相关推荐

【 WinForm】全屏截图 控件截图 句柄截图

代码

#region 全屏截图private Bitmap ScreenshotFull(){Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);Graphics g = Graphics.FromImage(bmp);g.CopyFromScreen(new Point(0, 0), new Point(0, 0), Screen.AllScreens[0].Bounds.Size);g.Dispose();return bmp;}#endregion#region 控件截图private Bitmap ScreenshotControl(Control control){Bitmap bmp = new Bitmap(control.Width, control.Height);control.DrawToBitmap(bmp, new Rectangle(0, 0, control.Width, control.Height));return bmp;}#endregion#region 句柄截图[DllImport("user32.dll")]private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rectangle rect);[DllImport("gdi32.dll")]private static extern IntPtr CreateCompatibleDC(IntPtr hdc);[DllImport("gdi32.dll")]private static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);[DllImport("gdi32.dll")]private static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);[DllImport("gdi32.dll")]private static extern int DeleteDC(IntPtr hdc);[DllImport("user32.dll")]private static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, int nFlags);[DllImport("user32.dll")]private static extern IntPtr GetWindowDC(IntPtr hwnd);public static Bitmap ScreenshotControlIntPtr(IntPtr hWnd){IntPtr hscrdc = GetWindowDC(hWnd);Rectangle windowRect = new Rectangle();GetWindowRect(hWnd, ref windowRect);int width = Math.Abs(windowRect.X - windowRect.Width);int height = Math.Abs(windowRect.Y - windowRect.Height);IntPtr hbitmap = CreateCompatibleBitmap(hscrdc, width, height);IntPtr hmemdc = CreateCompatibleDC(hscrdc);SelectObject(hmemdc, hbitmap);PrintWindow(hWnd, hmemdc, 0);Bitmap bmp = Image.FromHbitmap(hbitmap);DeleteDC(hscrdc);DeleteDC(hmemdc);return bmp;}#endregion

效果

Bitmap bitmap = ScreenshotControlIntPtr(Handle);bitmap.Save("test.png", ImageFormat.Png);

如果觉得《【 WinForm】全屏截图 控件截图 句柄截图》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。