首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Visual C# 剪貼簿程式設計實戰:讀取與儲存剪貼簿資料完整範例(三)

     編輯:關於C語言

完整程式碼:偵測類型並儲存/顯示


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

public class Form1 : Form {
  private RichTextBox richTextBox1;
  private Button button1;
  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.richTextBox1 = new RichTextBox();
    this.button1 = new Button();
    this.SuspendLayout();
    this.richTextBox1.Location = new Point(40, 16);
    this.richTextBox1.Name = "richTextBox1";
    this.richTextBox1.Size = new Size(336, 264);
    this.richTextBox1.TabIndex = 0;
    this.richTextBox1.Text = "";
    this.button1.Location = new Point(128, 304);
    this.button1.Name = "button1";
    this.button1.Size = new Size(128, 24);
    this.button1.TabIndex = 1;
    this.button1.Text = "取得剪貼簿資料";
    this.button1.Click += new EventHandler(this.button1_Click);
    this.AutoScaleBaseSize = new Size(6, 14);
    this.ClientSize = new Size(408, 357);
    this.Controls.Add(this.button1);
    this.Controls.Add(this.richTextBox1);
    this.Name = "Form1";
    this.Text = "用 Visual C# 儲存剪貼簿資料!";
    this.ResumeLayout(false);
  }

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

  private void button1_Click(object sender, EventArgs e) {
    IDataObject data = Clipboard.GetDataObject();

    // 位圖 → 存檔
    if (data.GetDataPresent(DataFormats.Bitmap)) {
      Bitmap bmp = (Bitmap)data.GetData(DataFormats.Bitmap);
      bmp.Save(@"c:\my.bmp");
      MessageBox.Show("剪貼簿為位圖,已儲存至 MY.BMP!");
    }
    // 文字 → 顯示於 RichTextBox
    else if (data.GetDataPresent(DataFormats.Text)) {
      string txt = (string)data.GetData(DataFormats.Text);
      richTextBox1.Text = txt;
    }
    else {
      MessageBox.Show("剪貼簿為其他資料類型!");
    }
  }
}

關鍵技術點總結

  1. IDataObject 介面: Clipboard.GetDataObject() 回傳實作此介面的物件,統一存取不同格式資料。
  2. GetDataPresent: 偵測指定格式(DataFormats.Bitmap、Text、Html 等 21 種預定義格式)。
  3. GetData + 裝箱/拆箱: GetData 回傳 object,需強制轉型為實值型別(Bitmap、string),此為參考型別轉實值型別的拆箱操作。
  4. Bitmap.Save: 直接將位圖存為檔案。
  5. RichTextBox: 適合顯示純文字或 RTF 格式內容。

應用延伸

掌握剪貼簿讀取/儲存後,可輕鬆開發:螢幕擷圖工具、格式轉換器、剪貼簿歷史管理器、自動排版貼上工具等實用小程式。

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