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.
The issue you are running into is that there are two different
Clipboardclasses, one for WinForms, and one forWPF. 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 aSystem.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
Clipboardclass 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 likeImage. So, back to your question:Clipboard.GetImagewhich returns aBitmapSource, exactly what you needIn summary: