Search code examples
delphidelphi-2010dynamically-generated

Add events to dynamically created objects - Webcopy - TMS Software


I'm trying to add events to a dynamically created component named webcopy from TMS Software. The code works ok for static component added to form but if I want to create a dynamic one I'm unable to execute different events.

Here is the code that works ok except the part event webcopy.OnFileDone:

public
  { Public declarations }

  procedure delete_file_after_upload(Sender:TObject; idx:integer);
end;

procedure Tform2.delete_file_after_upload(Sender:TObject; idx:integer);
begin
showmessage('FILENAME"'+upload_filename+'" SUCCESSFULLY UPLOADED TO FTP');
deletefile(upload_filename);
end;

procedure upload_file_to_ftp(filename,ftp_host,ftp_port,ftp_user,ftp_password,ftp_directory:string);
var webcopy:Twebcopy;
begin
   try
      webcopy:=Twebcopy.Create(NIL);
      Webcopy.Items.Clear;

      with WebCopy.Items.Add do
      begin
         {upload_filename = global variable so i can delete it after succesfully uploading it to ftp}
         upload_filename:=filename;

         protocol := wpFtpUpload;

         URL:=filename; // local file that is input
         FTPHost := ftp_host;
         FtpPort := strtoint(ftp_port);
         FTPUserID := ftp_user;
         FTPPassword := ftp_password;
         TargetDir := ftp_directory;   // path to use on FTP server

         {after the uploading process is done I want to delete the file from pc}
         webcopy.OnFileDone:= Form2.delete_file_after_upload;
    end;

   finally
      WebCopy.Execute;
      freeandnil(webcopy);
   end;
end;

Solution

  • The handler must have appropriate signature.

    The type for the event handler is defined as

    TWebCopyFileDone = procedure(Sender:TObject; idx:integer) of object;
    

    Thus, your handler procedure must be a method of some class (this is what of object means), and accept two parameters, TObject and Integer.

    For example:

    procedure TForm2.delete_file_after_upload(Sender:TObject; idx:integer);
    begin
      ...
    

    You'll also have to add declaration of the method to public section of TForm2.