Posts Tagged analysts

Capture an Image of the Desktop, Specific Screen or Portion of a Screen with C#

So today is my birthday. It has been a wild ride this last 46 years. Lets hope that things continue to get better.

So this is my entire class for capturing screens and desktop appearance to an image file or to print them. I use this class quite often in my error management, saving or emailing the output should errors occur so I can get a good idea of what was going on at the time an error occurs. Why? Because often end users or business analysts, though they are trying their best, sometimes can’t describe in detail how to reproduce what occurred. I suggest using this in conjunction with a logging class as well so that you can replicate the steps needed. The image file is also very handy in reconstructing what a user was or was not doing which, as a coder, can literally save your ass on occasion. So here it is. It is well commented and pretty straight forward.

using System.Windows.Forms;
using System;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;

public class clsScreenCapture
{
    private System.Drawing.Printing.PrintDocument Pd = new System.Drawing.Printing.PrintDocument();
    private PictureBox PicForm = new PictureBox();

    /// Creates an Image object containing a screen shot of the entire desktop
    public Image CaptureScreen()
    {
        return CaptureWindow(User32.GetDesktopWindow());
    } //CaptureScreen
    /// Creates an Image object containing a screen shot of a specific window
    public Image CaptureWindow(IntPtr handle)
    {
        int SRCCOPY = 0xCC0020;
        // get te hDC of the target window
        IntPtr hdcSrc = User32.GetWindowDC(handle);
        // get the size
        User32.RECT windowRect = new User32.RECT();
        User32.GetWindowRect(handle, ref windowRect);
        int width = windowRect.right – windowRect.left;
        int height = windowRect.bottom – windowRect.top;
        // create a device context we can copy to
        IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
        // create a bitmap we can copy it to,
        // using GetDeviceCaps to get the width/height
        IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc, width, height);
        // select the bitmap object
        IntPtr hOld = GDI32.SelectObject(hdcDest, hBitmap);
        // bitblt over
        GDI32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, SRCCOPY);
        // restore selection
        GDI32.SelectObject(hdcDest, hOld);
        // clean up
        GDI32.DeleteDC(hdcDest);
        User32.ReleaseDC(handle, hdcSrc);

        // get a .NET image object for it
        Image img = Image.FromHbitmap(hBitmap);
        // free up the Bitmap object
        GDI32.DeleteObject(hBitmap);

        return img;
    } //CaptureWindow
    /// Captures a screen shot of a specific window, and saves it to a file
    public void CaptureWindowToFile(IntPtr handle, string filename, ImageFormat format)
    {
        Image img = CaptureWindow(handle);
        img.Save(filename, format);
    } //CaptureWindowToFile
    /// Captures a screen shot of a specific window, and saves it to a file
    public void CaptureWindowToPrinter(Form mfForm, ImageFormat format)
    {
        // Dim img As Image = CaptureScreen()

        Image img = CaptureWindow(mfForm.Handle);
        try
        {
            PicForm.Image = img;
            if (MessageBox.Show(“Press Yes to Print or No to Copy to your Clipboard (‘No’ will allow pasting into an email or Word document etc).”, “Print or Copy to Clipboard?”, MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                Pd.Print();
            }
            else
            {
                Clipboard.SetDataObject(img, true);
            }
        }
        catch (Exception ex)
        {
            string a = “vfdgsfg”;
        }
    } //CaptureWindowToPrinter
    private void pd_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {
        //—————————————————————
        // this procedure handles events raised by the printer object pd
        //—————————————————————
        e.Graphics.DrawImageUnscaled(PicForm.Image, 0, 0); //send image to printer – upper left position

        e.HasMorePages = false; //this is the last page to print

    }

    /// Captures a screen shot of the entire desktop, and saves it to a file
    public void CaptureScreenToFile(string filename, ImageFormat format)
    {
        Image img = CaptureScreen();
        img.Save(filename, format);
    } //CaptureScreenToFile
    public Bitmap CaptureDeskTopRectangle(Rectangle CapRect, int CapRectWidth, int CapRectHeight)
    {
        /// Returns BitMap of the region of the desktop, similar to CaptureWindow, but can be used to
        /// create a snapshot of the desktop when no handle is present, by passing in a rectangle
        /// Grabs snapshot of entire desktop, then crops it using the passed in rectangle’s coordinates
        clsScreenCapture SC = new clsScreenCapture();
        Bitmap bmpImage = new Bitmap(SC.CaptureScreen());
        Bitmap bmpCrop = new Bitmap(CapRectWidth, CapRectHeight, bmpImage.PixelFormat);
        Rectangle recCrop = new Rectangle(CapRect.X, CapRect.Y, CapRectWidth, CapRectHeight);
        Graphics gphCrop = Graphics.FromImage(bmpCrop);
        Rectangle recDest = new Rectangle(0, 0, CapRectWidth, CapRectHeight);
        gphCrop.DrawImage(bmpImage, recDest, recCrop.X, recCrop.Y, recCrop.Width, recCrop.Height, GraphicsUnit.Pixel);
        return bmpCrop;
    }
    /// Helper class containing Gdi32 API functions
    private class GDI32
    {
        public int SRCCOPY = 0xCC0020;
        // BitBlt dwRop parameter
        [System.Runtime.InteropServices.DllImport(“gdi32.dll”, EntryPoint=”BitBlt”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
        public static extern Int32 BitBlt(IntPtr hDestDC, Int32 x, Int32 y, Int32 nWidth, Int32 nHeight, IntPtr hSrcDC, Int32 xSrc, Int32 ySrc, Int32 dwRop);

        [System.Runtime.InteropServices.DllImport(“gdi32.dll”, EntryPoint=”CreateCompatibleBitmap”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
        public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, Int32 nWidth, Int32 nHeight);

        [System.Runtime.InteropServices.DllImport(“gdi32.dll”, EntryPoint=”CreateCompatibleDC”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
        public static extern IntPtr CreateCompatibleDC(IntPtr hdc);

        [System.Runtime.InteropServices.DllImport(“gdi32.dll”, EntryPoint=”DeleteDC”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
        public static extern Int32 DeleteDC(IntPtr hdc);

        [System.Runtime.InteropServices.DllImport(“gdi32.dll”, EntryPoint=”DeleteObject”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
        public static extern Int32 DeleteObject(IntPtr hObject);

        [System.Runtime.InteropServices.DllImport(“gdi32.dll”, EntryPoint=”SelectObject”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
        public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hObject);
    } //GDI32
    /// Helper class containing User32 API functions
    public class User32
    {
        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int left;
            public int top;
            public int right;
            public int bottom;
        } //RECT

        [System.Runtime.InteropServices.DllImport(“user32.dll”, EntryPoint=”GetDesktopWindow”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
        public static extern IntPtr GetDesktopWindow();

        [System.Runtime.InteropServices.DllImport(“user32.dll”, EntryPoint=”GetWindowDC”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
        public static extern IntPtr GetWindowDC(IntPtr hwnd);

        [System.Runtime.InteropServices.DllImport(“user32.dll”, EntryPoint=”ReleaseDC”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
        public static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);

        [System.Runtime.InteropServices.DllImport(“user32.dll”, EntryPoint=”GetWindowRect”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
        public static extern Int32 GetWindowRect(IntPtr hwnd, ref RECT lpRect);

    } //User32

    public clsScreenCapture()
    {
        SubscribeToEvents();
    }

// event handler wireups:
    private bool EventsSubscribed = false;
    private void SubscribeToEvents()
    {
        if (EventsSubscribed)
            return;
        else
            EventsSubscribed = true;

        Pd.PrintPage += pd_PrintPage;
    }

}


Join me on Facebook

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a comment