//Snippet: CaptureScreen.cs
//Author: Palle Kristensen
//Shared: 08-oct-2005
//Keywords:BITMAP,BITBLT,GDI32,GRAPHICS,RELEASEHDC,FROMHWND,GETHDC
//
//Captures the primary desktop screen.
//
//-------------------------------------------------------------
public class ScreenCapture
{
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
private static extern bool BitBlt(
IntPtr hdcDest, // handle to destination DC
int nXDest, // x-coord of destination upper-left corner
int nYDest, // y-coord of destination upper-left corner
int nWidth, // width of destination rectangle
int nHeight, // height of destination rectangle
IntPtr hdcSrc, // handle to source DC
int nXSrc, // x-coordinate of source upper-left corner
int nYSrc, // y-coordinate of source upper-left corner
System.Int32 dwRop // raster operation code
);
public static Bitmap PerformCapture()
{
Bitmap bm;
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();
return bm;
}
}
|