目次

TextBoxに対してコピーの操作をコードから実行する - C#

コードを用いて、TextBoxで選択された文章をクリップボードにコピーする方法を紹介します。

UI

下図の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.Copy();
    }
  }
}

解説

TextBoxのCopyメソッドを呼び出すことで選択範囲の文字をコピーできます。

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


下図の文章を入力します。


テキストボックス上でドラッグし、文章の一部を選択します。選択後[button1]を押します。


メモ帳を開き[編集]メニューの[貼り付け]を選択します。先にテキストボックスで選択しコピーした部分の文字列がメモ帳に貼り付けられます。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2012-06-25
iPentec all rights reserverd.