简体   繁体   English

如何在WinForms应用程序中创建自定义剪贴板格式

[英]How to create a custom clipboard format in a WinForms app

Take a look at this image: 看看这张图片:

IMG2

The screenshot is generated by copying one of the contacts in your skype list. 通过复制skype列表中的一个联系人生成屏幕截图。 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). 数据包含原始字节,其中包含skype显然有用的信息(在这种情况下,联系人名称以及名称的大小)。

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: 但是,我得到一个DataObject条目以及一些额外的数据,而不仅仅是原始字节:

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? 这可以在.NET中完成吗?

The extra bytes are serialization headers. 额外的字节是序列化标头。 See this note from the MSDN documentation on the Clipboard class (emphasis mine): 请参阅Clipboard类的MSDN文档中的这个注释 (强调我的):

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. 如果将非可序列化对象传递给Clipboard方法,则该方法将失败而不会引发异常。 See System.Runtime.Serialization for more information on serialization. 有关序列化的更多信息,请参见System.Runtime.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 . 要保留数据格式,请将数据作为Byte数组添加到MemoryStream,并将MemoryStream传递给SetData方法

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM