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

Posted on 2011-09-16
Medium Priority
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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 11

Assisted Solution

Visio_Guy earned 800 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 86

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.   =\
CHALLENGE LAB: Troubleshooting Connectivity Issues

Goal: Fix the connectivity issue in the lab's AWS environment so that you can SSH into the provided EC2 instance.  

LVL 86

Accepted Solution

Mike Tomlinson earned 1200 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 86

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 86

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: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

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

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…

800 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