Author: Tomas Rutkauskas
Does anyone have an example of using CopyFileEx with a CopyProgressRoutine? I have
created a function that takes the same parameters as the CopyProgressRoutine, but
when I pass it using @ or Addr() I get a Variable Required error message.
Answer:
Let's assume you call CopyFileEx and want the callback to update a progress bar.
The callback cannot be an objects method but you can use the lpData parameter of
CopyFileEx to pass any kind of data to the callback, e.g. a form reference. So, if
you want to serve a progress form in the callback that would look like this
(untested !):
1 type
2 TProgressForm = class(TForm)
3 AbortButton: TButton;
4 ProgressBar: TProgressBar;
5 procedure AbortButtonClick(Sender: TObject);
6 private
7 { Private declarations }
8 public
9 { Public declarations }
10 FCancel: BOOL;
11 end;
12 {form has fsStayOnTop formstyle!}
13
14 implementation
15
16 {$R *.DFM}
17
18 procedure TProgressForm.AbortButtonClick(Sender: TObject);
19 begin
20 FCancel := True;
21 end;
22
23 {Note: could use int64 instead of COMP, but that would make this D4 specific}
24
25 function CopyCallback(TotalFileSize, TotalBytesTransferred, StreamSize,
26 StreamBytesTransferred: COMP; dwStreamNumber, dwCallbackReason: DWORD;
27 hSourceFile, hDestinationFile: THandle; progressform: TProgressForm): DWORD;
28 stdcall;
29 var
30 newpos: Integer;
31 begin
32 Result := PROCESS_CONTINUE;
33 if dwCallbackReason = CALLBACK_CHUNK_FINISHED then
34 begin
35 newpos := Round(TotalBytesTransferred / TotalFileSize * 100);
36 with progressform.Progressbar do
37 if newpos <> Position then
38 Position := newpos;
39 Application.ProcessMessages;
40 end;
41 end;
42
43 function DoFilecopy(const source, target: string): Boolean;
44 var
45 progressform: TProgressForm;
46 begin
47 progressform := TProgressform.Create;
48 try
49 progressform.Show;
50 Application.ProcessMessages;
51 Result := CopyFileEx(PChar(source), PChar(target), @CopyCallback,
52 Pointer(progressform), @progressform.FCancel, 0);
53 finally
54 progressform.Hide;
55 progressform.free;
56 end;
57 end;
|