开发者

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

开发者 https://www.devze.com 2023-01-20 06:31 出处:网络
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 thou

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();
bitmapIm开发者_Go百科age.UriSource = new Uri(img.DirectLink);
bitmapImage.EndInit();

Clipboard.SetImage(bitmapImage);

and I always get the image


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号