コードを用いてTextBoxにクリップボードのテキストをペーストする方法を紹介します。
下図のUIを作成します。TextBoxとButtonを配置します。TextBoxのMultilineプロパティを"True"に設定します。
下記のコードを記述します。button1のClickイベントハンドラを実装します。
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 TextBoxOperationFromCode
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Paste();
//または
/*
IDataObject data = Clipboard.GetDataObject();
if (data.GetDataPresent(DataFormats.Text) == true){
//クリップボードにテキストが入っている
textBox1.Paste();
}
*/
}
}
}
TextBoxのPasteメソッドを呼び出すことでテキストボックスにクリップボードのテキストを貼り付けできます。
クリップボード内にテキストボックスに張り付けられるテキストデータがあるか判定するには下記のコードを用います。
IDataObject data = Clipboard.GetDataObject();
if (data.GetDataPresent(DataFormats.Text) == true){
//クリップボードにテキストが入っている
}
プロジェクトを実行します。下図のウィンドウが表示されます。
メモ帳を開き文字を入力します。入力した文字を選択し[コピー]メニューを選択し文字列を栗っぽボードにコピーします。
フォームで[button1]をクリックします。メモ帳でコピーした文字列がテキストボックスに貼り付けられました。