クリップボードからデータを取得する

ClipboardクラスのGet~関数群を利用します。
下の例はFormにTextBoxとButtonを貼り付けて
Buttonが押されたらTextBoxにクリップボードのテキストを設定しています。

動作確認をする場合は
メモ帳などのエディタを開いて文字列を入力、クリップボードにコピーしたあとに
Buttonを押してみてください。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // クリップボードからテキストを取得し、TextBoxに設定
            // テキストが格納されていない場合はstring.Empty "" が返ります
            textBox1.Text = Clipboard.GetText();

            // クリップボードにテキストが格納されているとは限らないので
            // データの種別を判断する例はこちら
            IDataObject data = Clipboard.GetDataObject();
            if (data != null)
            {
                string text = (string)data.GetData(DataFormats.Text);
                textBox1.Text = text;
            }
        }
    }
}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)