08 Sep

Taking Screenshots with C#

This examples show how to take screenshot using C#.

Sample Usage:

            Bitmap bmp = TakingScreenshotEx1();
            bmp.Save("Screenshot1.png", ImageFormat.Png);

            bmp = TakingScreenshotEx2();
            bmp.Save("Screenshot2.png", ImageFormat.Png);

This method shows you a simple method of capturing screenshots using C# and .NET 2.0( CopyFromScreen() method. )

        private Bitmap TakingScreenshotEx1()
        {
            //Create a new bitmap.
            var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                                           Screen.PrimaryScreen.Bounds.Height,
                                           PixelFormat.Format32bppArgb);

            // Create a graphics object from the bitmap.
            var g = Graphics.FromImage(bmpScreenshot);

            // Take the screenshot from the upper left corner to the right bottom corner.
            g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                             Screen.PrimaryScreen.Bounds.Y,
                             0,
                             0,
                             Screen.PrimaryScreen.Bounds.Size,
                             CopyPixelOperation.SourceCopy);

            return bmpScreenshot;
        }

This method uses GDI in C#.NET to draw the primary screen onto a bitmap.

        private Bitmap TakingScreenshotEx2()
        {
            int screenWidth = Screen.PrimaryScreen.Bounds.Width;
            int screenHeight = Screen.PrimaryScreen.Bounds.Height;

            Bitmap bmpScreenshot = new Bitmap(screenWidth, screenHeight);
            Graphics g = Graphics.FromImage(bmpScreenshot);

            IntPtr dc1 = WinAPI.GetDC(WinAPI.GetDesktopWindow());
            IntPtr dc2 = g.GetHdc();

            //Main drawing, copies the screen to the bitmap
            //last number is the copy constant
            WinAPI.BitBlt(dc2, 0, 0, screenWidth, screenHeight, dc1, 0, 0, 13369376);

            //Clean up
            WinAPI.ReleaseDC(WinAPI.GetDesktopWindow(), dc1);
            g.ReleaseHdc(dc2);
            g.Dispose();

            return bmpScreenshot;
        }
    public class WinAPI
    {
        [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
        public static extern IntPtr GetDC(IntPtr hWnd);

        [DllImport("user32.dll", ExactSpelling = true)]
        public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);

        [DllImport("gdi32.dll", ExactSpelling = true)]
        public static extern IntPtr BitBlt(IntPtr hDestDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop);

        [DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
        public static extern IntPtr GetDesktopWindow();
    }