|
|||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionIn a recent project I found the need to be able to drop an image from Internet Explorer onto my form and capture the URL of the image. If you have tried using any of the text formats to get the drop data then you know this does not work. At best you will get the locally cached path of the image file. There is little or no documentation on the subject, and attempting to search for information only yields others seeking the same answers. This is why I decided to make this an article. Note that this code makes use of regular expressions. As this is not an article about regex's, which is a huge topic in itself, I provide no explanation of the expressions used. You can easily find numerous tutorials on Regular Expressions. BackgroundThe key to reading the source URL of the image is in the data type. Through much trial and error, I found that the magic words are " Using the codeSimply place the appropriate code below into your The private void myControl_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("HTML Format"))
e.Effect = DragDropEffects.Copy;
}
To actually capture the URL, place the following in the private void myControl_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));
}
We need the There are three supporting functions:
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);
}
string parseImageSrc(string html)
{
return Regex.Match(html, @"<img.*?src=[""'](.*?)[""'].*>",
RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
}
string parseBaseURL(string html)
{
return Regex.Match(html, @http://.*?/,
RegexOptions.IgnoreCase).Groups[0].Value;
}
Points of InterestCheck out the demo project to see it in action. History
|
||||||||||||||||||||||||||||||||||||||||