admin 管理员组

文章数量: 1184232

代码

#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);

本文标签: 编程 系统 控件截图