I have to copy three different data to the clipboard. So I create a Tuple and copy it to the clipboard and then I copy it to clipboard
var newTuple = new Tuple<Component, Color?, bool?>(CopyComponent, headerColour_Copied, IsHeaderForegroundDark_Copied);
Clipboard.SetDataObject(newTuple);
when copying I get an exception which translated may sound like "Other data are available". I also tried to purge the clipboard but that was of no help.
Clipboard.SetDataObject(CopyComponent);
Clipboard.SetDataObject(headerColour_Copied);
Clipboard.SetDataObject(IsHeaderForegroundDark_Copied);
Please notice that if I don't make a Tuple but set each datum separately everything is fine.
So can't tuples be copied to clipboard??
I also tried to box each of the three datum into an object without but still fails
Thanks for helping
Patrick
CodePudding user response:
Generic types typically don't play very well outside the realm of . net; try sending a plain array of values instead:
Clipboard.SetDataObject(new object[] { CopyComponent, headerColour_Copied, IsHeaderForegroundDark_Copied });
Clipboard content can be consumed by any application; basic intrinsic types are a safer bet here.
CodePudding user response:
Fortunately, we can store ValueTuple
or Tuple
on the Clipboard and retrieve it as a serializable data object.
// using System.Windows;
public void TupleClipboardTest1()
{
(int, string) original = (11, "Eleven");
Clipboard.SetData(DataFormats.Serializable, original);
object retrieved = Clipboard.GetData(DataFormats.Serializable);
Debug.WriteLine(retrieved.GetType()); // System.ValueTuple`2[System.Int32,System.String]
(int, string) restored = (ValueTuple<int, string>)retrieved;
Debug.WriteLine(restored.Item1); // 11
Debug.WriteLine(restored.Item2); // Eleven
}
// using System.Windows;
public void TupleClipboardTest2()
{
Tuple<int, string> original = (11, "Eleven").ToTuple();
Clipboard.SetData(DataFormats.Serializable, original);
object retrieved = Clipboard.GetData(DataFormats.Serializable);
Debug.WriteLine(retrieved.GetType()); // System.Tuple`2[System.Int32, System.String]
Tuple<int, string> restored = (Tuple<int, string>)retrieved;
Debug.WriteLine(restored.Item1); // 11
Debug.WriteLine(restored.Item2); // Eleven
}
Of cource, its items must be serializable as well. Otherwise it causes a COMException.
// using System.Windows;
public void TupleClipboardTest3()
{
(int, System.Windows.Media.Color) original = (11, System.Windows.Media.Colors.Gray);
Clipboard.SetData(DataFormats.Serializable, original);
object retrieved = Clipboard.GetData(DataFormats.Serializable); // System.Runtime.InteropServices.COMException: 'Data on clipboard is invalid (0x800401D3 (CLIPBRD_E_BAD_DATA))'
}
Therefore, we need to convert an non-serializable item to a serializable object beforehand.