1
votes

For a project I am currently working on I'm required to use the clipboard to a certain extent.

What I need:

Save text and some additional application specific data to the clipboard. The text is supposed to be usable with CTRL + V within other applications while the application data should usually be omitted as it is mostly used for referencing stuff (like quotes and so on)

What I tried:

Copying custom object to clipboard and overwriting the ToString-Method, which was a little naive to think it would work

[Serializable]
public class TestData {
    public string txt;
    public string additionalStuffs;

    public override string ToString() {
        return txt;
    }
}
Clipboard.SetData( "TestData", new TestData() { txt = "This is a text", additionalStuffs = "Stuffs" } );

I would now need the txt to be pastable into other applications as a string while the other data is ignored unless posted in my application. For the sake of being readable and easy to use for the user.

Can any of you explain how I need to approach this problem? Is there even a way to do that?

1
I think it's impossible. You can put either text or an object to the clipboard.Alexander Petrov
@AlexanderPetrov I just found a solution after a little more trial and error. The trick is to apply multiply data-types to a DataObject and then writing all of this to the clipboard. This way every application can look for its prefered "string type" and display the value you supplied.dravorle

1 Answers

2
votes

Okay, a little more trial and error using the documentation and I actually found a solution.

For everyone having the same problem: the trick is using a DataObject like the following:

[Serializable]
public class TestData {
   public string Whatever;
}

IDataObject dataObject = new DataObject();
dataObject.SetData( "System.String", "Test" );
dataObject.SetData( "Text", "Test" );
dataObject.SetData( "UnicodeText", "Test" );
dataObject.SetData( "OEMText", "Test" );

dataObject.SetData( "TestData", new TestData() { Whatever = "NONONONONO", } );

Clipboard.SetDataObject( dataObject );

Using this construct you can set a Text using multiple "DataTypes" so whatever the application you want to paste to requires you have a value supplied. This way only the text shows up when pasting but hidden inside is also the additional data.

Sorry for putting this question up without researching to the end. Have a great day!