Copying Formatted HTML to the Clipboard (It's not as easy as you would think...)
For a VS2003 work project I needed to copy formatted data to the clipboard. RTF was overkill, so I thought I'd just use HTML...
Easy right? Just Clipboard.SetDataObject("<html><body>This is html</body></html>")?
Or maybe;
Dim DataObject As New DataObject
DataObject.SetData(DataFormats.Html, True, "<html><body>This is html</body></html>")
Clipboard.SetDataObject(DataObject , True)
?
Not even.
First of all kudo's to Stuart Radcliffe's post Copying HTML Link to the Clipboard which helped me get over this hump.
There I was, going crazy. I could copy and paste text easy, but my HTML was pasting as blank/empty. I was doing everything right as far as I could tell. My HTML was well formatted (and very simple), I knew how to post the data to the clipboard, etc. But it just wasn't working...
So I thought I'd look at what another app was doing when it copied HTML (and how that looked when I grabbed it back). Let's copy THIS from WLW.
Via the very cool ClipSpy Code Project Stuart also mentions, here's the raw HTML content in the clipboard (with some style stuff removed for readability so the values don't match any more...).
Version:1.0
StartHTML:000000237
EndHTML:000001414
StartFragment:000001344
EndFragment:000001348
StartSelection:000001344
EndSelection:000001348
<HTML><HEAD><LINK
href="C:\Program Files\Windows Live Writer\template\defaultstyle.css"
type=text/css rel=stylesheet></HEAD>
<BODY><DIV class=post><DIV class=body><DIV class=postBody >
<P><!--StartFragment-->THIS<!--EndFragment--></P>
</DIV></DIV></DIV></BODY></HTML>
Wow, that's a lot of stuff for one word...
The magic is in the Header elements and the Start/End Fragment comments.
Yes, your HTML will need the Start/End header elements, with the correct values, if you want your posted HTML to paste as formatted HTML. That's where the JuJu is...
That's where Stuart's post comes in. Besides confirming that I'm not crazy (much) and do indeed need all that header stuff, he's also done much of the initial dirty work in generating the correctly formatted HTML for posting to the clipboard (i.e. calculating the Start's and End's, etc).
His code is working code and may require some tweaking to work for you, but it's a great start. (If you didn't have to tweak the code, where would the fun come from? ;)
At the end of the day, with help from his post, I had formatted HTML coping to the clipboard and pasting out as expected...
No comments:
Post a Comment