在窗体上放置一个 TPanel; 在 TPanel 上放一个 TImage; 另外需要三个按钮.
本例效果图:
![26153048_MUBx.gif](http://static.oschina.net/uploads/img/201409/26153048_MUBx.gif)
第一版代码:
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:\temp\test.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:\temp\test.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 常量表示图片, 其他格式怎么表示? 有多少格式可以用于剪切板?