How to drop and/or image or image file onto form

Posted on 2011-09-16
Last Modified: 2013-12-17
I have a .Net 4 Windows Forms project created with Visual Studio 2010 using c#.

I have a form which I would like to be able to drag and drop an image onto to be displayed and saved to a file.  This will allow the user to drag an image (of any normal type jpg, gif, etc) from a web site and drop it onto the .Net form where it will be saved to file and displayed.  The user should alsobe able to browse to a file in Windows Explorer and drag an image file onto the form for similar results.

I would be happy for the user to have to drop the image onto a PictureBox or similar control.
Question by:canuckconsulting
LVL 11

Assisted Solution

Visio_Guy earned 200 total points
ID: 36548448
There's a nice article over on CodeProject. It's pretty old, but nicely written, and I believe it still applies to WinForms.

A Simple Drag And Drop How To Example
LVL 40
ID: 36549918
You cannot do that.

In your application, you can control the Drop.

But the Drag must be initiated in the application that provides the object. Think of the security issues otherwise.

Since you cannot drag images from most application, there is no way to drop them into yours.
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 36550394
He wants to drag from a web site to his form:

    "This will allow the user to drag an image (of any normal type jpg, gif, etc) from a web site and drop it onto the .Net form"

The answer is, yes you can...but with stipulations.

Most other browsers support this out of the box but you have to parse the return value to get the URL and then actually download the image (it's really not that hard).

But Internet Explorer, the most common browser, will give you headaches on systems with Vista or higher because of UAC and the "Proctected Mode" in IE.  You have to turn off UAC or disable Protected Mode to be able to drag an image from a web page.   =\
Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

LVL 85

Accepted Solution

Mike Tomlinson earned 300 total points
ID: 36550645
Here's an example...note in the screencast that I Right Click IE and select "Run as Administrator".  This is what necessary using RockMelt (browser based on Google Chrome):

Here's the code:
*The parsing code portion was written by Vaelek. I converted it from here:
Imports System.IO
Imports System.Net
Imports System.Text.RegularExpressions
Public Class Form1

    Private URL_DataFormat As String = "HTML format"

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        PictureBox1.AllowDrop = True
    End Sub

    Private Sub PictureBox1_DragEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles PictureBox1.DragEnter
        If e.Data.GetDataPresent(URL_DataFormat) Then
            e.Effect = DragDropEffects.Copy
        End If
    End Sub

    Private Sub PictureBox1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles PictureBox1.DragDrop
        Dim clipboardHtml As String = e.Data.GetData("HTML Format").ToString
        Dim htmlFragment As String = getHtmlFragment(clipboardHtml)
        Dim imageSrc As String = parseImageSrc(htmlFragment)
        Dim baseURL As String = parseBaseURL(clipboardHtml)
        Dim ImageURL As String = ""
        If imageSrc.ToUpper().StartsWith("HTTP://") Then
            ImageURL = imageSrc
            ImageURL = baseURL + imageSrc.Substring(1)
        End If

        Dim bgw As New System.ComponentModel.BackgroundWorker
        AddHandler bgw.DoWork, AddressOf bgw_DoWork
        AddHandler bgw.RunWorkerCompleted, AddressOf bgw_RunWorkerCompleted
        Me.Text = "Downloading Image..."
    End Sub

    Public Function getHtmlFragment(ByVal clipboardHtml As String) As String
        Dim fragStartPos As Integer = Integer.Parse(Regex.Match(clipboardHtml, "StartFragment:(\d+)", RegexOptions.Multiline).Groups(1).Value)
        Dim fragEndPos As Integer = Integer.Parse(Regex.Match(clipboardHtml, "^EndFragment:(\d+)", RegexOptions.Multiline).Groups(1).Value)
        Return clipboardHtml.Substring(fragStartPos, fragEndPos - fragStartPos)
    End Function

    Public Function parseImageSrc(ByVal html As String) As String
        Return Regex.Match(html, "<img.*?src=[""'](.*?)[""'].*>", RegexOptions.IgnoreCase Or RegexOptions.Singleline).Groups(1).Value
    End Function

    Public Function parseBaseURL(ByVal html As String) As String
        Return Regex.Match(html, "http://.*?/", RegexOptions.IgnoreCase).Groups(0).Value
    End Function

    Private Sub bgw_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
        Dim url As String = e.Argument
        Dim img As Image = GetWebImage(url)
        img.Tag = url
        e.Result = img
    End Sub

    Private Function GetWebImage(ByVal URL As String) As Image
            Dim wReq As WebRequest = WebRequest.Create(URL)
            If Not IsNothing(wReq) Then
                Dim wRes As WebResponse = wReq.GetResponse
                If Not IsNothing(wRes) Then
                    Dim wStrm As Stream = wRes.GetResponseStream
                    If Not IsNothing(wStrm) Then
                        Return Image.FromStream(wStrm)
                    End If
                End If
            End If
        Catch ex As Exception
        End Try
        Return Nothing
    End Function

    Private Sub bgw_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs)
        Dim img As Image = e.Result
        If Not IsNothing(img) Then
            Me.Text = img.Tag.ToString
            PictureBox1.Image = img

            ' if you want to save it:
            ' img.Save(System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "SomeFile.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg)
            Me.Text = "Oops!"
            MessageBox.Show("Failed to get image...")
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Me.Text = "Form1"
        PictureBox1.Image = Nothing
    End Sub

End Class

Open in new window

LVL 40
ID: 36550649
He also wants to drag from the browser:

   "should alsobe able to browse to a file in Windows Explorer and drag an image file onto the form for similar results."

I think the expressiond web site and file are not used in the right context :-)


There is an option to save the picture in a file in most browsers, usually on the context menu when you right click on an image. Do you really need an application to save the file for the user?

LVL 85

Expert Comment

by:Mike Tomlinson
ID: 36550655
*The "what" below should read "not" !

    "This is what necessary using RockMelt (browser based on Google Chrome)"
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 36550665
Right...I believe he wants to both be able to drag and drop a local image from Windows Explorer and an image from a web page.

There are many examples on the net showing how to accomplish the local drag and drop from Windows Explorer.

Author Closing Comment

ID: 36945262
Thank you and I'm sorry for not following up on this earlier!  Yes, I wanted to do both things (drag a file from Windows Explorer and drag an image from a web browser).  These two answer have me on the right path!

The reason I want this is the images will be resized and thumbnails created from the resized image.  Both these images will then be submitted to a DB.

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

791 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question