C#でクリップボードにあるクラスのオブジェクトを貼り付けて、取得する方法について見てみよう。
今回は以下のようなサンプルプログラムをWindowsFormで作成した。

プログラムは以下のようになる。
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ClilpBoardLesson
{
public partial class Form1 : Form
{
/// <summary>
/// Serializableを付けないといけないようだ
/// </summary>
[Serializable]
private class Person
{
public String Name { get; set; }
public String Address { get; set; }
public int Age { get; set; }
}
public Form1()
{
InitializeComponent();
}
/// <summary>
/// コピー
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCopy_Click(object sender, EventArgs e)
{
Person person = new Person()
{
Name = txtName.Text,
Address = txtAddress.Text,
Age = (int)numAge.Value
};
Clipboard.SetDataObject(person, true);
}
/// <summary>
/// ペースト
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnPaste_Click(object sender, EventArgs e)
{
IDataObject dataObject = Clipboard.GetDataObject();
if(dataObject != null && dataObject.GetDataPresent(typeof(Person)) )
{
Person person = dataObject.GetData(typeof(Person)) as Person;
txtName.Text = person.Name;
txtAddress.Text = person.Address;
numAge.Value = person.Age;
}
}
}
}
まずこのプログラムを複数立ち上げておく。そして入力項目欄に適当な値を入力し、Copyボタンを押すと18-24行目で定義したPersonクラスのオブジェクトが作成され、システムクリップボードに格納される。[①]

次に、別の画面でPasteボタンを押すと[②]、最初に入力した画面の内容が入力される。[③]

当初、PersonクラスにはSerializableを付けていなかったのだが、そうすると58行目のIDataObject#GetData()の呼び出しではnullが返ってきてしまった。どうやらクラスのオブジェクトをクリップボード間で受け渡すときはSerializableを付けないといけないようだ。