Click here to Skip to main content
15,881,204 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
How to save data in clipboard (all of it), and then set the clipboard to it after the clipboard have changed?
Posted
Comments
Harsh Athalye 10-Dec-14 6:13am    
How about Clipboard.SetText()?
john1990_1 10-Dec-14 13:35pm    
i want to set and get objects not strings
setdata and getdata dont work

Saving an 'object into the Clipboard, and reading it, is not difficult: the one requirement is that the 'object must be serializable. But, remember that the Clipboard is meant to be used by the user, at any time, "inside" or "outside" of your Application. To try and restrict its use is a serious mistake.

Example (in a WinForm) of saving an 'object to the Clipboard, and reading it back; example:
C#
// in the same NameSpace with the test code below:
[Serializable]
public class TestClass
{
    public int count { set; get; }
    public string aString { set; get; }
}

private string TestClassDataFormat = "TestClassList";

private List<testclass> ListOfTestClass;

private void TestClipboardWrite()
{
    ListOfTestClass = new List<testclass>
    {
        new TestClass {aString = "instance 1", count = 300},
        new TestClass {aString = "instance 2", count = 400 }
    };

    // create a DataObject
    DataObject testDataObject = new DataObject(TestClassDataFormat, ListOfTestClass);
    
    // write to the Clipboard
    Clipboard.SetDataObject(testDataObject);
}

private void TestClipboardRead()
{
    IDataObject clipData = Clipboard.GetDataObject();

    if (clipData != null)
    {
        if (clipData.GetDataPresent(TestClassDataFormat))
        {
            ListOfTestClass = (List<testclass>)clipData.GetData(TestClassDataFormat);
        
            // put a break-point here, and examine results
        }
    }
}</testclass></testclass></testclass>
Comment: note that here a generic List of 'TestClass was written/read to/from the Clipboard: this was successful because the "atomic" elements of the Object, the instances of 'TestClass were all Serializable. So, it was not necessary to create a separate Class marked Serializable that held the List of 'TestClass.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900