Click here to Skip to main content
15,894,017 members
Articles / Programming Languages / C#

Drop images from IE

Rate me:
Please Sign up or sign in to vote.
4.50/5 (19 votes)
9 Jun 20072 min read 28.7K   347   30  
Capturing the URL of an image dropped on your form from IE
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Text.RegularExpressions;

namespace DropImageUrlFromIE_Src
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void Form1_DragEnter(object sender, DragEventArgs e)
    {
      if (e.Data.GetDataPresent("HTML Format"))
        e.Effect = DragDropEffects.Copy;
    }

    string parseBaseURL(string html)
    {
      return Regex.Match(html, @"http://.*?/", RegexOptions.IgnoreCase).Groups[0].Value;
    }

    string parseImageSrc(string html)
    {
      return Regex.Match(html, @"<img.*?src=[""'](.*?)[""'].*>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
    }

    string getHtmlFragment(string clipboardHtml)
    {
      int fragStartPos = int.Parse(Regex.Match(clipboardHtml, @"^StartFragment:(\d+)", RegexOptions.Multiline).Groups[1].Value);
      int fragEndPos = int.Parse(Regex.Match(clipboardHtml, @"^EndFragment:(\d+)", RegexOptions.Multiline).Groups[1].Value);

      return clipboardHtml.Substring(fragStartPos, fragEndPos - fragStartPos);
    }

    private void Form1_DragDrop(object sender, DragEventArgs e)
    {
      string clipboardHtml = (string)e.Data.GetData("HTML Format");
      string htmlFragment = getHtmlFragment(clipboardHtml);
      string imageSrc = parseImageSrc(htmlFragment);
      string baseURL = parseBaseURL(clipboardHtml);

      if (imageSrc.ToUpper().IndexOf("HTTP://") == 0)
        MessageBox.Show(imageSrc);
      else
        MessageBox.Show(baseURL + imageSrc.Substring(1));
    }
  }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions