准備工作:
在窗體上放置一個 TPanel; 在 TPanel 上放一個 TImage; 另外需要三個按鈕.
本例效果圖:
第一版代碼:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Panel1: TPanel;
Image1: TImage;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses Clipbrd;
procedure TForm1.Button1Click(Sender: TObject);
begin
Image1.Left := 0;
Image1.Top := 0;
Panel1.AutoSize := True;
Image1.AutoSize := True;
Image1.Picture.LoadFromFile('c:temptest.bmp');
TButton(Sender).Caption := '導入';
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Clipboard.Assign(Image1.Picture); {把 Image1 中的圖片放入剪切板}
{現在在圖像軟件中都可以粘貼了, 可以用 Windows 畫圖板試試}
TButton(Sender).Caption := '復制';
end;
procedure TForm1.Button3Click(Sender: TObject);
var
bit: TBitmap; {准備用一個 TBitmap 從剪切板中結束圖片}
x,y: Integer;
begin
bit := TBitmap.Create;
bit.Assign(Clipboard); {從剪切板獲取}
x := Panel1.Width + Panel1.Left * 2; {x,y 是准備在窗體上的粘貼位置}
y := Panel1.Top;
Canvas.Draw(x, y, bit); {粘貼就是畫出來呗}
bit.Free;
TButton(Sender).Caption := '粘貼';
end;
end.
不過現在程序還有漏洞: 假如剪切板中沒有東西, 粘貼什麼? 如果剪切板中不是圖片, 怎麼粘貼?
其實我們只用 TClipboard.HasFormat 函數判斷一下剪切板中是不是圖片就行了.
第二版代碼:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Panel1: TPanel;
Image1: TImage;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses Clipbrd;
procedure TForm1.Button1Click(Sender: TObject);
begin
Image1.Left := 0;
Image1.Top := 0;
Panel1.AutoSize := True;
Image1.AutoSize := True;
Image1.Picture.LoadFromFile('c:temptest.bmp');
TButton(Sender).Caption := '導入';
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
{如果 Image1 還沒有圖片, 就別復制了, 退出吧}
if Image1.Picture = nil then Exit;
Clipboard.Assign(Image1.Picture);
TButton(Sender).Caption := '復制';
end;
procedure TForm1.Button3Click(Sender: TObject);
var
bit: TBitmap;
x,y: Integer;
begin
{如果當前剪切板中的東西不是圖片, 就退出}
if not Clipboard.HasFormat(CF_BITMAP) then Exit;
bit := TBitmap.Create;
bit.Assign(Clipboard);
x := Panel1.Width + Panel1.Left * 2;
y := Panel1.Top;
Canvas.Draw(x, y, bit);
bit.Free;
TButton(Sender).Caption := '粘貼';
end;
end.
現在有出了新的問題: CF_BITMAP 常量表示圖片, 其他格式怎麼表示? 有多少格式可以用於剪切板?