首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> C# 入門

C# 操作剪貼簿完整教學:文字、圖片與檔案的複製貼上實作

     編輯:C# 入門

前言:剪貼簿操作的核心場景

剪貼簿是 Windows 作業系統的核心資料交換機制。無論是文字、圖片、檔案還是自訂資料格式,Ctrl+C 複製與 Ctrl+V 貼上都是最基礎的使用者操作。本文將透過一個完整的 WinForms 範例,示範如何使用 C# 實作剪貼簿的核心操作:寫入資料與讀取資料,並處理資料格式驗證與例外情況。

開發環境與專案架構

  • 作業系統:Windows 2000 Server
  • 框架:.NET Framework SDK Beta 2
  • 介面元件:兩個 TextBox(來源/目標)、兩個 Button(複製/貼上)

核心類別:Clipboard 與 IDataObject

類別/介面命名空間核心功能
ClipboardSystem.Windows.Forms靜態類別,提供 SetDataObject() 寫入、GetDataObject() 讀取
IDataObjectSystem.Windows.Forms資料傳輸介面,提供 GetDataPresent() 檢查格式、GetData() 取得資料
DataFormatsSystem.Windows.Forms預定義資料格式常數(Text, Bitmap, FileDrop 等)

功能一:複製選取文字到剪貼簿

步驟解析

  1. 檢查是否有選取內容:透過 TextBox.SelectedText 屬性判斷
  2. 寫入剪貼簿:呼叫 Clipboard.SetDataObject()

程式碼實作

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.SelectedText != "")
        Clipboard.SetDataObject(textBox1.SelectedText);
    else
        textBox2.Text = "textBox1 中沒有選取的內容";
}

功能二:從剪貼簿讀取並顯示文字

步驟解析

  1. 取得資料物件:IDataObject iData = Clipboard.GetDataObject()
  2. 驗證資料格式:iData.GetDataPresent(DataFormats.Text) 確認為文字格式
  3. 取出資料並拆箱:(string)iData.GetData(DataFormats.Text) 將 object 轉為 string

程式碼實作

private void button2_Click(object sender, EventArgs e)
{
    IDataObject iData = Clipboard.GetDataObject();
    
    if (iData.GetDataPresent(DataFormats.Text))
    {
        textBox2.Text = (string)iData.GetData(DataFormats.Text);
    }
    else
    {
        textBox2.Text = "沒有從剪貼簿接收到文字資料!";
    }
}

完整程式碼

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

public class Form1 : Form
{
    private Button button1;
    private Button button2;
    private TextBox textBox1;
    private TextBox textBox2;
    private Container components = null;

    public Form1()
    {
        InitializeComponent();
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing && components != null)
            components.Dispose();
        base.Dispose(disposing);
    }

    private void InitializeComponent()
    {
        this.button1 = new Button();
        this.button2 = new Button();
        this.textBox1 = new TextBox();
        this.textBox2 = new TextBox();
        this.SuspendLayout();

        // button1 - 複製到剪貼簿
        this.button1.Location = new Point(264, 56);
        this.button1.Size = new Size(96, 40);
        this.button1.Name = "button1";
        this.button1.Text = "複製指定資料到剪貼簿";
        this.button1.Click += new EventHandler(this.button1_Click);

        // button2 - 從剪貼簿取得資料
        this.button2.Location = new Point(264, 104);
        this.button2.Size = new Size(96, 40);
        this.button2.Name = "button2";
        this.button2.Text = "從目前剪貼簿取得資料";
        this.button2.Click += new EventHandler(this.button2_Click);

        // textBox1 - 來源文字方塊
        this.textBox1.Location = new Point(64, 64);
        this.textBox1.Name = "textBox1";
        this.textBox1.TabIndex = 2;

        // textBox2 - 目標文字方塊
        this.textBox2.Location = new Point(64, 104);
        this.textBox2.Name = "textBox2";
        this.textBox2.TabIndex = 3;

        this.ClientSize = new Size(384, 273);
        this.Controls.AddRange(new Control[] { this.textBox2, this.textBox1, this.button2, this.button1 });
        this.Name = "Form1";
        this.Text = "C# 操作剪貼簿範例";
        this.ResumeLayout(false);
    }

    [STAThread]
    static void Main()
    {
        Application.Run(new Form1());
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (textBox1.SelectedText != "")
            Clipboard.SetDataObject(textBox1.SelectedText);
        else
            textBox2.Text = "textBox1 中沒有選取的內容";
    }

    private void button2_Click(object sender, EventArgs e)
    {
        IDataObject iData = Clipboard.GetDataObject();
        if (iData.GetDataPresent(DataFormats.Text))
        {
            textBox2.Text = (string)iData.GetData(DataFormats.Text);
        }
        else
        {
            textBox2.Text = "沒有從剪貼簿接收到資料!";
        }
    }
}

進階應用:支援多種資料格式

本範例專注於文字格式,實務上可擴充支援:

  • 圖片:DataFormats.Bitmap、DataFormats.EnhancedMetafile
  • 檔案清單:DataFormats.FileDrop(拖曳檔案路徑陣列)
  • 自訂格式:使用 DataFormats.GetFormat("CustomFormat") 註冊專屬格式

讀取時同樣透過 GetDataPresent() 判斷格式後再取值,邏輯完全一致。

常見問題與最佳實務

問題解決方案
剪貼簿被其他程式佔用導致例外使用 try-catch 捕捉 ExternalException,可加入重試機制
大量資料複製效能不佳考慮實作 IDataObject 自訂資料物件,支援虛擬模式(按需提供資料)
跨應用程式資料格式不相容優先使用標準格式;自訂格式需雙方協定序列化方式

結語

掌握 Clipboard 與 IDataObject 的核心操作,即可輕鬆實作剪貼簿的讀寫功能。本文示範的文字處理邏輯,同樣適用於圖片、檔案等其他格式,只需調整格式常數與資料型別轉換即可。建議在實務專案中加入例外處理與格式驗證,確保使用者體驗穩定可靠。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved