{该文首发于博客园 滔Roy,无须授权即可转发,请自觉保留头部申明}
Delphi Clipboard[5] SetComponent、GetComponent -组件在剪贴板中的操作
1、SetComponent //将组件复制到剪贴板
procedure TClipboard.SetComponent(Component: TComponent);
var
MemStream: TMemoryStream;
begin
MemStream := TMemoryStream.Create;
try
MemStream.WriteComponent(Component);
SetBuffer(CF_COMPONENT, MemStream.Memory^, MemStream.Size);
finally
MemStream.Free;
end;
end;
2、GetComponent //从剪贴板中检索组件
function TClipboard.GetComponent(Owner, Parent: TComponent): TComponent;
var
Data: THandle;
DataPtr: Pointer;
MemStream: TMemoryStream;
Reader: TReader;
begin
Result := nil;
Open;
try
Data := GetClipboardData(CF_COMPONENT);
if Data = 0 then Exit;
DataPtr := GlobalLock(Data);
if DataPtr = nil then Exit;
try
MemStream := TMemoryStream.Create;
try
MemStream.WriteBuffer(DataPtr^, GlobalSize(Data));
MemStream.Position := 0;
Reader := TReader.Create(MemStream, 256);
try
Reader.Parent := Parent;
Result := Reader.ReadRootComponent(nil);
try
if Owner <> nil then
Owner.InsertComponent(Result);
except
Result.Free;
raise;
end;
finally
Reader.Free;
end;
finally
MemStream.Free;
end;
finally
GlobalUnlock(Data);
end;
finally
Close;
end;
end;
- 使用GetComponent检索存储在剪贴板上的组件。
- 所有者成为检索组件的所有者,父级成为其父级。Owner通常是一个表单,但两个参数都可以是nil(Delphi)或NULL(C++)。
- 在从剪贴板读取类之前,必须通过调用RegisterClass来注册它。如果试图读取未注册的类,则会出现EClassNotFound异常。
3、示例
//复制Edit
var Cpt:TComponent; begin Clipboard.SetComponent(Edit1); { 将按钮复制到剪贴板 } if Clipboard.HasFormat(CF_COMPONENT) then begin Cpt:=Clipboard.GetComponent(Self, GroupBox1); TEdit(Cpt).Text:='这是滔Roy复制的Edit1'; TEdit(Cpt).Left:=20; TEdit(Cpt).Top:=20; end; end; //复制按钮 var Cpt:TComponent; begin Clipboard.SetComponent(BitBtnTest); { 将按钮复制到剪贴板 } BitBtnTest.Caption := 'TaoRoyButton1'; { 重命名仍在表单上的按钮 } //现在从剪贴板中检索按钮并将其添加到GroupBox1 //请注意,剪贴板按钮名为BitBtnTest,而源按钮已重命名为"TaoRoyButton1" if Clipboard.HasFormat(CF_COMPONENT) then begin Cpt:=Clipboard.GetComponent(Self, GroupBox1); TBitBtn(Cpt).Left:=20; TBitBtn(Cpt).Top:=50; end; end;
注意:这里用到了 HasFormat(CF_COMPONENT) ,而CF_COMPONENT是Delphi内置的组件剪贴板格式
创建时间:2022.04.14 更新时间: