My hacky method to get HTML into Word programmatically had a slight flaw in that it splatted anything the user had placed on the clipboard. I consider it to be bad manners to mess with the clipboard because it’s the user’s clipboard, not my application’s. Many years ago I was forced to use Lotus Notes, which used the clipboard whenever I replied to an email, so I can’t really write code that does something that has annoyed me in the past.
So I had to figure out how to fix it. The below did the trick, although I haven’t tested it with all clipboard formats so it may not work with all of them. And if you’re wondering why this is in VB.NET and the previous example was in C#, I was forced to convert all the code to VB.NET, much to my chagrin.
' store current contents of clipboard Dim currentData As IDataObject = Clipboard.GetDataObject() Dim formats As String() = currentData.GetFormats() Dim currentClipboard As Dictionary(Of String, Object) = New Dictionary(Of String, Object) For Each Format As String In formats currentClipboard.Add(Format, currentData.GetData(Format)) Next ' do stuff... ' put back old clipboard contents Dim newData As DataObject = New DataObject() For Each savedFormat As KeyValuePair(Of String, Object) In currentClipboard newData.SetData(savedFormat.Key, savedFormat.Value) Next Clipboard.SetDataObject(newData)