//-------------------------------------------------------------------- // CaptureScreen.cs © 2002 by Charles Petzold, www.charlespetzold.com //-------------------------------------------------------------------- using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; class CaptureScreen: Form { // Define external Win32 function. [DllImport("gdi32.dll")] public static extern bool BitBlt(IntPtr hdcDst, int xDst, int yDst, int cx, int cy, IntPtr hdcSrc, int xSrc, int ySrc, uint ulRop); // Sole field Bitmap bm; public static void Main() { Application.Run(new CaptureScreen()); } public CaptureScreen() { Text = "CaptureScreen Demo (click client area)"; ResizeRedraw = true; } protected override void OnClick(EventArgs ea) { // Get a Graphics object associated with the screen. Graphics grfxScreen = Graphics.FromHwnd(IntPtr.Zero); // Create a bitmap the size of the screen. bm = new Bitmap((int) grfxScreen.VisibleClipBounds.Width, (int) grfxScreen.VisibleClipBounds.Height, grfxScreen); // Create a Graphics object associated with the bitmap. Graphics grfxBitmap = Graphics.FromImage(bm); // Get hdc's associated with the Graphics objects. IntPtr hdcScreen = grfxScreen.GetHdc(); IntPtr hdcBitmap = grfxBitmap.GetHdc(); // Do the bitblt from the screen to the bitmap. BitBlt(hdcBitmap, 0, 0, bm.Width, bm.Height, hdcScreen, 0, 0, 0x00CC0020); // Release the device contexts. grfxBitmap.ReleaseHdc(hdcBitmap); grfxScreen.ReleaseHdc(hdcScreen); // Manually dispose of the Graphics objects. grfxBitmap.Dispose(); grfxScreen.Dispose(); Invalidate(); } protected override void OnPaint(PaintEventArgs pea) { Graphics grfx = pea.Graphics; // If the bitmap exists, display it shrunk to size of client. if (bm != null) grfx.DrawImage(bm, ClientRectangle); } }