Handle copy component from one form to another in Delphi

773 views Asked by At

Writing my own Delphi VCL component inherited from TComponent with a bunch of properties, that must be unique to component's owner form. When I copy component from one form to another (with simple Ctrl+C, Ctrl-V) all properties are copied too. Any ideas on where (or how) I can handle copying or pasting the component on form and clear copied values (or set them to default)? For now I ended up with the idea of keeping component's owner form name (or other unique property) in the special component property and compare it with actual owner name in component's Loaded method. Maybe there is a more elegant or simpler way?

1

There are 1 answers

0
zrocker On BEST ANSWER

Found a solution myself. This is a kind of hack, but nonetheless it works.

First of all, when we copy the component, Delphi only copies the published properties - they are written in dfm file. It is more correct to say that Delphi will copy the implementation of the component in dfm format. You can easily verify this by copying the component and pasting it into Notepad. So now we can use the clipboard to analyze it in the newly pasted instance of our component and decide whether to clear the properties or not (or do something else).

A small example of such a check - a procedure that analyzes the values ​​in the clipboard for compliance with the current component:

function CheckClipboard:boolean;
begin
 try
  if (pos('object', Clipboard.AsText) <> 0)
    and (pos('object', Clipboard.AsText) < pos('TComponent', Clipboard.AsText))
    and (pos('TComponent', Clipboard.AsText) < pos(#13#10, Clipboard.AsText))
    and (pos(#13#10, Clipboard.AsText) < pos('end', Clipboard.AsText))
    and (TForm(Owner).Showing) then //This is for the function to not execute when the owner form is created or opened
       Result:=true
  else
    Result := false;
 except
  on E : Exception do
  begin
   MessageDlg('Clipboard error: '+E.Message, mtError, mbOKCancel, 0);
   Result := false;
  end;
 end;
end;

It returns true when the clipboard contains such a component, and false if not. I use it in Loaded method of my component.