Junaid Rehman
Junaid Rehman

Reputation: 159

Copy an image from cache of web browser control present in VB.NET

I know that an image can be downloaded from a website opened in web browser control, but that actually works by getting the image URL and download that. There is a website that doesn't allow the direct link, so the image fails to download, so the only method I can think of is copying the images from the cache of the web browser control.

Upvotes: 0

Views: 3351

Answers (1)

volody
volody

Reputation: 7199

You can use online c# to vb.net converters like telerik or developerfusion to get code in vb.net in the future.

  1. Add reference to Microsoft.mshtml to your project
  2. Add next code into the webBrowser DocumentCompleted event handler

Sample code:

Private Sub webBrowser1_DocumentCompleted(sender As Object, _
   e As WebBrowserDocumentCompletedEventArgs) _
   Handles WebBrowser1.DocumentCompleted

   Dim doc As IHTMLDocument2 = _
      DirectCast(webBrowser1.Document.DomDocument, IHTMLDocument2)

   Dim imgRange As IHTMLControlRange = _
      DirectCast(DirectCast(doc.body, _
      HTMLBody).createControlRange(), IHTMLControlRange)

   For Each img As IHTMLImgElement In doc.images
    imgRange.add(DirectCast(img, IHTMLControlElement))

    imgRange.execCommand("Copy", False, Nothing)

    Using bmp As Bitmap = DirectCast( _
        Clipboard.GetDataObject().GetData(DataFormats.Bitmap), Bitmap)
        bmp.Save("C:\" + img.nameProp)
    End Using
   Next

End Sub

Upvotes: 1

Related Questions