How to create your own clipboard format in a WinForms application

Take a look at this image:

img2

A screenshot is taken by copying one of the contacts in your skype list. The data contains raw bytes containing information that seems to be useful (in this case, the name of the contact, as well as the size of the name).

I would like to do it myself.

Here is the code that I used in an attempt to copy to the clipboard

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

Copy to clipboard. However, I get a DataObject record along with additional data added to it, and not just raw bytes:

img2

The upper half is what I see. The bottom half is when I take a screenshot. Note that this is just bitmap data.

Can this be done in .NET?

+6
source share
1 answer

Additional bytes are serialization headers. See the note from the MSDN documentation in the Clipboard class (highlighting):

The object must be serializable so that it is placed on the clipboard. If you pass a non-serialization object to the Clipboard method, the method will fail without exception. See System.Runtime.Serialization for more information on serialization. If your target application requires a very specific data format, headers added to the data during the serialization process may prevent the application from recognizing your data. To save the data format, add your data as a byte array to a MemoryStream and pass in a MemoryStream for the SetData strong> method.

So, the solution should do this:

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

Source: https://habr.com/ru/post/984571/


All Articles