Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win


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.   =\
Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

636 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