将用户定义类型的对象放在剪贴板上并检索它

时间:2012-06-14 08:06:08

标签: c# clipboard

我正在上课。我想将类'Student'objStu'的对象存储在剪贴板上。

Class Student
{
    string stuID;
    string Name;
    string email;
}

在主要方法中我写了一个代码:

Clipboard.SetDataObject(objStu,false);

当我尝试按如下方式检索对象时:

Student anotherStu = Clipboard.GetDataObject() as Student;

它返回null。请指导我如何实现它。

1 个答案:

答案 0 :(得分:2)

将学生课程设为Serializable

[Serializable]
public class Student
{
    public string stuID { get; set; }
    public string Name { get; set; }
    public string email { get; set; }
    public void CopyToClipboard()
    {

        DataFormats.Format format =
             DataFormats.GetFormat(typeof(Student).FullName);
        //now copy to clipboard
        IDataObject dataObj = new DataObject();
        dataObj.SetData(format.Name, false, this);
        Clipboard.SetDataObject(dataObj, false);

    }

然后你尝试:

Student objStu = new Student();
objStu.Name = "test";
objStu.CopyToClipboard();
Clipboard.SetDataObject(objStu, false);
Student anotherStu = GetFromClipboard();
下面的

是GetFromClipboard方法

protected static Student GetFromClipboard()
{
    Student student = null;
    IDataObject dataObj = Clipboard.GetDataObject();
    string format = typeof(Student).FullName;

    if (dataObj.GetDataPresent(format))
    {
        student = dataObj.GetData(format) as Student;
    }
    return student;
}

检查this link以获取更多信息