Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a custom clipboard format in a WinForms app

Tags:

c#

.net

clipboard

Take a look at this image:

img2

The screenshot is generated by copying one of the contacts in your skype list. The data contains raw bytes containing information that skype apparently finds useful (in this case, the contact name, along with the size of the name).

I would like to accomplish this myself.

Here's the code I used in an attempt to copy to clipboard

byte[] bytes = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
Clipboard.SetData("My Data", bytes);

Which does copy to the clipboard. However, I get a DataObject entry along with some extra data added to it, rather than just raw bytes:

img2

The top half is what I see. The bottom half is when I take a screenshot of the screen. Notice that it is just raw bitmap data.

Can this be done in .NET?

like image 475
MxLDevs Avatar asked Apr 01 '15 16:04

MxLDevs


1 Answers

The extra bytes are serialization headers. See this note from the MSDN documentation on the Clipboard class (emphasis mine):

An object must be serializable for it to be put on the Clipboard. If you pass a non-serializable object to a Clipboard method, the method will fail without throwing an exception. See System.Runtime.Serialization for more information on serialization. If your target application requires a very specific data format, the headers added to the data in the serialization process may prevent the application from recognizing your data. To preserve your data format, add your data as a Byte array to a MemoryStream and pass the MemoryStream to the SetData method.

So the solution is to do this:

byte[] bytes = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
MemoryStream stream = new MemoryStream(bytes);
Clipboard.SetData("My Data", stream);
like image 103
dlf Avatar answered Oct 31 '22 18:10

dlf