4

I am having a strange problem. I am trying to retrieve the images already loaded in webbrowser control. The following code works fine in a WinForms application:

IHTMLControlRange imgRange = (IHTMLControlRange)((HTMLBody)__ie.NativeDocument.BODY).createControlRange();

            foreach (IHTMLImgElement img in __ie.NativeDocument.Images)
            {
                imgRange.add((IHTMLControlElement)img);
                imgRange.execCommand("Copy", false, null);

                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                using (Bitmap bmp = (Bitmap)Clipboard.GetDataObject().GetData(DataFormats.Bitmap))
                {
                        bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
                        var image = System.Drawing.Image.FromStream(stream);
                }
            }

But the same code if I use in WPF application gives error on

using (Bitmap bmp = (Bitmap)Clipboard.GetDataObject().......

The error is as follows:

"Unable to cast object of type 'System.Windows.Interop.InteropBitmap' to type 'System.Drawing.Bitmap'."

How do I solve this?

Please can anyone provide any guidance.

Thank you in advance.

Rick Sladkey
  • 33,988
  • 6
  • 71
  • 95
Milan Solanki
  • 1,207
  • 4
  • 25
  • 48

1 Answers1

8

The issue you are running into is that there are two different Clipboard classes, one for WinForms, and one for WPF. The WinForms one returns bitmaps that are suitable for use with WinForms, i.e. System.Drawing.Bitmap, which in the code you are using copies it to a System.Drawing.Image.

Those types of bitmaps are not useful with WPF so the fact that you can't convert what the WPF version of the Clipboard class is giving you to a type that is useful with WinForms is expected and not really your problem.

Your problem is that for WPF you need a type of bitmap that you can use with WPF: a BitmapSource. That is something you can use with WPF controls like Image. So, back to your question:

  • if you are using WPF4 you can use Clipboard.GetImage which returns a BitmapSource, exactly what you need
  • if you are using anything else, you can use Thomas Levesque's technique described here

In summary:

  • For WinForms: WinForms clipboard => WinForms bitmaps
  • For WPF: WPF clipboard => WPF bitmaps
Rick Sladkey
  • 33,988
  • 6
  • 71
  • 95