Just a Bit: Copying Text to the Clipboard

A bit is the difference between true and false

So when working on this blog sometimes I spend a little too much time getting code together. I’m sure I’ll get better, faster, and care less about what it looks like over time.

Until then, I’ll use these ‘Just a Bit’ posts. The idea being that I post a tiny bit of code that I found useful recently. Sure, about 400,000,000 pages can be found elsewhere with this information, but they don’t have clever wordplay in their titles!

So, the first “Just a Bit” is using .NET to add text to the Windows clipboard.  First, put together a string using the StringBuilder class – the reason for this is that any formatting characters (‘\n’, ‘\t’, etc.) won’t necessarily translate correctly onto the clipboard correctly if you simply put them into a string.  Finally use the System.Windows.Clipboard static method SetDataObject to copy the text to the clipboard.

// build the string, with new lines between entries
StringBuilder clipStr = new StringBuilder();
foreach (string itm in TheItemCollection.Items)
{
	clipStr.Append(itm);
	clipStr.Append("\n");
}
// copy to clipboard, clear the box, and notify user
Clipboard.SetDataObject(clipStr.ToString(), true);

Enjoy that one.