Jasmeet
Jasmeet

Reputation: 1460

How to make custom object stored in the Clipboard paste-able into Notepad (or any other text editor)?

I am working with Cut copy Paste functionality of my class objects. I am able to keep the data on Clipboard and get it back for this purpose.

Now what I am trying is to get the same data on some other text editor through ctrl+V or paste operation provided by that text editor.

The code for setting the data on clipboard is :

  /// <summary>
  /// Set elements on the clipboard.
  /// </summary>
  /// <param name="object">object to be stored on the clipboard.</param>
  private static void SetElementsOnClipboard(CustomData object)
  {
     Tuple<string, Type> serializedElement = null;
     var data = new System.Windows.DataObject();
     serializedElement = new Tuple<string, Type>(SerialiseData(object), object.GetType());
     data.SetData("SomeKey", serializedElement);

     System.Windows.Clipboard.SetDataObject(data);
  }

Here the method SerialiseData(CustomData object) returns a string object that I want to paste in other text editor.

I would appreciate any help.

Upvotes: 1

Views: 1726

Answers (1)

Nyerguds
Nyerguds

Reputation: 5639

You can set data on the clipboard in multiple formats simultaneously. Put in a SetText with a string representation of your object in addition to your SetData, so text-only applications have something to paste from it too.

Note that unless you need to receive that data in a specific format under a specific clipboard ID, you shouldn't need to serialize that object yourself; as long you set the [Serializable] attribute at the top of your class, and you make sure the data inside is made up of serializable types, the system can take care of all that by itself. In fact even the clipboard ID can just be substituted by the object type, and SetData does that automatically if you don't specifically add the string ID.

/// <summary>
/// Set object on the clipboard, together with its string representation.
/// </summary>
/// <param name="myObject">object to be stored on the clipboard.</param>
public static void PutOnClipboardWithTextVersion<T>(T myObject) where T : class
{
    DataObject data = new DataObject();
    data.SetData(myObject); // identical to data.SetData(typeof(T), myObject);
    data.SetText(myObject.ToString());
    // The second arg makes the data stay available after the program closes.
    Clipboard.SetDataObject(data, true);
}

You'll have to write the .ToString() implementation yourself, of course.

Note: DataObject and Clipboard aren't in System.Windows; they're in System.Windows.Forms. And, I'm fairly sure you can't use object as variable name.

Note on the automatic serialization: this is the way to retrieve the object:

DataObject clipData = (DataObject)Clipboard.GetDataObject();
CustomData clipPaste = null;
if (clipData.GetDataPresent(typeof(CustomData)))
    clipPaste = clipData.GetData(typeof(CustomData)) as CustomData;

Upvotes: 3

Related Questions