C#/WPF: Can I Store more that 1 type in Clipboard?

狂风中的少年 提交于 2019-12-04 03:40:56

Yes, it is possible. The main problem is, methods you are using clear clipboard before putting data (that's why in particular they named "Set..." instead of "Add...").

Clipboard.SetText (WinForms) / Clipboard.SetText (WPF) description from MSDN:

(WinForms): Clears the Clipboard and then adds text data in the Text or UnicodeText format, depending on the operating system.

But a solution is relatively easy:

To place data on the Clipboard in multiple formats, use the DataObject class or an IDataObject implementation. Place data on the Clipboard in multiple formats to maximize the possibility that a target application, whose format requirements you might not know, can successfully retrieve the data.

Check MSDN for details:


UPDATE:

Added links to WPF variants.

To clarify @Björn comment:

The MSDN page for System.Windows.Clipboard.SetText() does not state that the clipboard is cleared, even though that seems to be the case

Both methods (WPF/WinForms) internally calls to OleSetClipboard so behaviour is similar (you can check http://referencesource.microsoft.com/#q=Clipboard.SetText).

I also checked both variants (WinForms/WPF) in console app and found they do the same.

As Nick says in the accepted answer: You have to use a DataObject (or IDataObject) to use multiple formats (otherwise each Set-call will clear the clipboard first).
Here is a code sample:

BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.UriSource = new Uri(img.DirectLink);
bitmapImage.EndInit();

DataObject d = new DataObject();
d.SetImage(bitmapImage);
d.SetText(img.DirectLink);
Clipboard.SetDataObject(d);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!