Is there any way to store HTML fragments in the Windows clipboard containing <img...>
elements that reference temporary image files and to make sure that no temporary image files are left in the TEMP directory?
Here is some sample code for illustrating the problem that I am encountering:
Pressing a button in my test application executes the following code:
string tempFileName = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()) + ".png";
CreateImage(tempFileName);
string html = string.Format("<p>[This is <b>HTML</b> with a picture:<img src=\"file://{0}\">]</p>", tempFileName);
WriteHtmlToClipboard(html);
MessageBox.Show("Wrote HTML to clipboard");
CreateImage()
renders and saves an image file on the fly, like this:
private static void CreateImage(string tempFileName)
{
Bitmap b = new Bitmap(50, 50);
using (Graphics g = Graphics.FromImage(b))
{
g.DrawEllipse(Pens.Red, new RectangleF(2, 2, b.Width - 4, b.Height - 4));
Bitmap b2 = new Bitmap(b);
b2.Save(tempFileName, ImageFormat.Png);
}
}
WriteHtmlToClipboard()
writes the HTML fragment to the clipboard:
private static void WriteHtmlToClipboard(string html)
{
const string prefix = "<html>head><title>HTML clipboard</title></head><body>";
const string suffix = "</body>";
const string header = "Version:0.9\r\n" +
"StartHTML:AAAAAA\r\n" +
"EndHTML:BBBBBB\r\n" +
"StartFragment:CCCCCC\r\n" +
"EndFragment:DDDDDD\r\n";
string result = header + prefix + html + suffix;
result = result.Replace("AAAAAA", header.Length.ToString("D6"))
.Replace("BBBBBB", result.Length.ToString("D6"))
.Replace("CCCCCC", (header + prefix).Length.ToString("D6"))
.Replace("DDDDDD", (header + prefix + html).Length.ToString("D6"));
Clipboard.SetText(result, TextDataFormat.Html);
}
I now have two alternatives regarding the handling of the temporary image file:
Delete the image file when the application is terminated. Problem: When I paste the HTML text from the clipboard into another application, the images are lost. Most users expect that the clipboard's content is preserved even if you close an application.
Leave the image file in the TEMP directory even after the application terminates. Problem: Who removes the image file when the clipboard's content is replaced by something else?
Of course, I could implement a helper application that runs whenever Windows boots and cleans up any temporary image file, but I would prefer a more elegant solution.