Posts Tagged Image

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

Getting Images from Microsoft Office Document Imaging (MODI) with vb.net

Hello! It has been a long time since my last blog post and I am happy to be getting back to this. I have missed writing this blog more than you have missed me I guarantee it!

That being said, now that this blog has resumed there will be a few changes. The landscape has changed a bit since my last blog entry. While I will still focus primarily on vb.net code I will also be including what I am working on that is WPF and C# related as well as other .NET related topics. Why? Simply because as my skillset has expanded I wanted to share what I have learned and am learning with you as well. I hope you won’t mind!

Today’s topic revolves around getting images from Microsoft Office Document Imaging (MODI). As you recall I have done a lot of Office automation over the years and I was asked to do this for a friend. As I said, it is good to be back!

add a reference -> Com -> Microsoft Office Document Imaging

Private Sub ConvertMdi2Tif(ByVal ModiFilePath As String)
Dim miDoc As New MODI.Document
Dim myViewer As New MODI.MiDocView
Dim myImg As MODI.Image
Try
Dim Folder As New DirectoryInfo(ModiFilePath)
pbReportGenerate.Minimum = 0
pbReportGenerate.Maximum = Folder.GetFiles(“*.MDI”).Length
pbReportGenerate.Step = 1
pbReportGenerate.Value = pbReportGenerate.Minimum
For Each File As FileInfo In Folder.GetFiles(“*.MDI”)
miDoc.Create(File.FullName)
myViewer.Document = miDoc
For i As Long = 0 To miDoc.Images.Count – 1
Dim tempDoc As New MODI.Document
myImg = miDoc.Images(i)
tempDoc.Create()
tempDoc.Images.Add(myImg, Nothing)
tempDoc.SaveAs(TIFPath & “\” + GetFileNameWithoutExtension(File.FullName) & i & “.Tif”, MiFILE_FORMAT.miFILE_FORMAT_TIFF_LOSSLESS, MiCOMP_LEVEL.miCOMP_LEVEL_HIGH)
tempDoc.Close()
tempDoc = Nothing
Exit For
Next
pbReportGenerate.PerformStep()
Application.DoEvents()
Next
miDoc.Close()
miDoc = Nothing
myViewer.Document = Nothing
myViewer = Nothing
Catch ex As Exception
MsgBox(ex.Message)
End Try
GC.Collect()
End Sub

Private Sub ConvertTif2Bmp(ByVal TIFFilePath As String)
Dim Folder As New DirectoryInfo(TIFFilePath)
Dim index As Long = 0
pbReportGenerate.Minimum = 0
pbReportGenerate.Maximum = Folder.GetFiles(“*.TIF”).Length
pbReportGenerate.Step = 1
pbReportGenerate.Value = pbReportGenerate.Minimum
For Each File As FileInfo In Folder.GetFiles(“*.TIF”)
GC.WaitForPendingFinalizers()
Dim streamBinary As New FileStream(File.FullName, FileMode.Open)
Dim g As System.Drawing.Image = System.Drawing.Image.FromStream(streamBinary)
Dim imgOutput As New Bitmap(g, g.Width, g.Height)

Dim qualityEncoder As Encoder = Encoder.Quality
Dim ratio As EncoderParameter = New EncoderParameter(qualityEncoder, 40)
Dim codecParams As New EncoderParameters(1)
codecParams.Param(0) = ratio
‘bmp.Save(fileName, jpegCodecInfo, codecParams)
Dim encoder1 As ImageCodecInfo = GetEncoderInfo(“image/bmp”)
imgOutput.Save(BMPPath + “\” + GetFileNameWithoutExtension(File.FullName) + “.” & System.Drawing.Imaging.ImageFormat.Bmp.ToString, encoder1, codecParams)
streamBinary.Close()
streamBinary = Nothing
g.Dispose()
g = Nothing
imgOutput.Dispose()
imgOutput = Nothing
pbReportGenerate.PerformStep()
Application.DoEvents()
Next
GC.Collect()
End Sub


My Facebook

WordPress Tags: vb.net,Images,Microsoft,Office,Document,MODI,automation,friend,reference,MiDocView,Image,Folder,DirectoryInfo,Minimum,Maximum,GetFiles,Length,Step,Value,File,FileInfo,Create,FullName,Long,Count,SaveAs,TIFPath,GetFileNameWithoutExtension,MiFILE_FORMAT,MiCOMP_LEVEL,Close,Exit,PerformStep,Application,DoEvents,Catch,Exception,MsgBox,Message,Collect,TIFFilePath,index,WaitForPendingFinalizers,FileStream,FileMode,Open,System,FromStream,Bitmap,Width,Encoder,ratio,EncoderParameter,EncoderParameters,Param,Save,ImageCodecInfo,GetEncoderInfo,BMPPath,ImageFormat,Dispose,blog,miDoc,myViewer,myImg,pbReportGenerate,tempDoc,streamBinary,imgOutput,qualityEncoder,codecParams

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

2 Comments