Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

clipboard

wpf

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

like image 261
Jiew Meng Avatar asked Oct 15 '10 10:10

Jiew Meng


1 Answers

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.

like image 165
Nick Martyshchenko Avatar answered Nov 15 '22 16:11

Nick Martyshchenko