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

戏子无情 提交于 2019-12-14 04:25:09

问题


Can I Store more than 1 type in the Clipboard? Eg. like Text & Image. say the user pastes in a text editor, he gets the text and if he pastes in something like photoshop, he gets the image. I thought it was possible but I tried

Clipboard.Clear();
Clipboard.SetText(img.DirectLink);

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

Clipboard.SetImage(bitmapImage);

and I always get the image


回答1:


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:

  • WinForms: http://msdn.microsoft.com/en-us/library/25w5tzxb.aspx

  • WPF: http://msdn.microsoft.com/en-us/library/system.windows.clipboard.aspx


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.




回答2:


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


来源:https://stackoverflow.com/questions/3941472/c-wpf-can-i-store-more-that-1-type-in-clipboard

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