namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Paint(object sender, PaintEventArgs e) { } public Bitmap GetDesktopImage() { SIZE size; IntPtr hBitmap; IntPtr hDC = PlatformInvokeUSER32.GetDC(listBox1.Handle); IntPtr hMemDC = PlatformInvokeGDI32.CreateCompatibleDC(hDC); size.cx = listBox1.Width; size.cy = listBox1.Height; hBitmap = PlatformInvokeGDI32.CreateCompatibleBitmap(hDC, size.cx, size.cy); if (hBitmap != IntPtr.Zero) { IntPtr hOld = (IntPtr)PlatformInvokeGDI32.SelectObject(hMemDC, hBitmap); PlatformInvokeGDI32.BitBlt(hMemDC, 0, 0, size.cx, size.cy, hDC, 0, 0, PlatformInvokeGDI32.SRCCOPY); PlatformInvokeGDI32.SelectObject(hMemDC, hOld); PlatformInvokeGDI32.DeleteDC(hMemDC); PlatformInvokeUSER32.ReleaseDC(listBox1.Handle, hDC); Bitmap bmp = System.Drawing.Image.FromHbitmap(hBitmap); PlatformInvokeGDI32.DeleteObject(hBitmap); GC.Collect(); return bmp; } return null; } private void button1_Click(object sender, EventArgs e) { pictureBox1.Image = GetDesktopImage(); } } [StructLayout(LayoutKind.Sequential)] public struct SIZE { public int cx; public int cy; } public class PlatformInvokeGDI32 { public const int SRCCOPY = 13369376; [DllImport("gdi32.dll", EntryPoint = "DeleteDC")] public static extern IntPtr DeleteDC(IntPtr hDC); [DllImport("gdi32.dll", EntryPoint = "DeleteObject")] public static extern IntPtr DeleteObject(IntPtr hDC); [DllImport("gdi32.dll", EntryPoint = "BitBlt")] public static extern bool BitBlt(IntPtr hdcDest, int xDest, int yDest, int wDest, int hDest, IntPtr hdcSource, int xSrc, int ySrc, int rasterOp); [DllImport("gdi32.dll", EntryPoint = "CreateCompatibleBitmap")] public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC,int nWidth,int hHeight); [DllImport("gdi32.dll", EntryPoint = "CreateCompatibleDC")] public static extern IntPtr CreateCompatibleDC(IntPtr hDC); [DllImport("gdi32.dll", EntryPoint = "SelectObject")] public static extern IntPtr SelectObject(IntPtr hDC,IntPtr bmp); } public class PlatformInvokeUSER32 { public const int SM_CXSCREEN = 0; public const int SM_CYSCREEN = 1; [DllImport("user32.dll", EntryPoint = "GetDesktopWindow")] public static extern IntPtr GetDesktopWindow(); [DllImport("user32.dll", EntryPoint = "GetDC")] public static extern IntPtr GetDC(IntPtr ptr); [DllImport("user32.dll", EntryPoint = "GetSystemMetrics")] public static extern int GetSystemMetrics(int abc); [DllImport("user32.dll", EntryPoint = "GetWindowDC")] public static extern IntPtr GetWindowDC(Int32 ptr); [DllImport("user32.dll", EntryPoint = "ReleaseDC")] public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDc); } } |