Oct 27, 2008

C# - How to take a screenshot of Internet Explorer

Asuming you have InternetExplorerClass instance, named ie, you can do the following to obtain screenshot:



                  
int screenWidth = ie.Width;
                  
int screenHeight = ie.Height;

                   #region Get IE Bitmap

                  
Bitmap b = new Bitmap(ie.Width, ie.Height);
                  
Graphics g = Graphics.FromImage(b);
                  
IntPtr hdc = g.GetHdc();

                  
bool result = PrintWindow((IntPtr)ie.HWND, hdc, 0);

                   g.ReleaseHdc();
                   g.Flush();
/>                   b.Save(@"filename.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);


You will also need to add the PrintWindow function (it is windows API function):

     [
DllImport("user32.dll")]
    
private static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt,
        
uint nFlags);

Not that hard, but not well documented. If you don't know how to get a pointer to a running Internet Explorer class, you can do the following:

1. Add reference to ShDocVw (it is in the COM tab and it should be named "Microsoft Objects Automation library" or something like this)
2. Add the following code:

        SHDocVw.
ShellWindowsClass windows = new ShellWindowsClass();

foreach (SHDocVw.InternetExplorer explorer in windows)
        {
          
if (explorer.LocationURL == string.Empty)
           {
            
// this is our guy!
             ie = explorer;
           }
        }
NOTE: please be sure to use your own if statement. This one will get an instance to the last found Internet explorer which has an empty string as Location.


Happy C# programming!

2 comments:

Denis said...

Its possible to take a screenshot only of the full document (without the browser adress bar, buttons, etc and the full document) using a method like this?

please, could you send me a example to denis.juergen@gmail.com?

thanks in advance.

Павелъ Дончевъ said...

I don't think there is a way to do this so easilly.

If I see something like this I will post again and let you know.