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
2 type
3 TProgressForm = class(TForm)
4 AbortButton: TButton;
5 ProgressBar: TProgressBar;
6 procedure AbortButtonClick(Sender: TObject);
7 private
8 { Private declarations }
9 public
10 { Public declarations }
11 FCancel: BOOL;
12 end;
13 {form has fsStayOnTop formstyle!}
14
15 implementation
16
17 {$R *.DFM}
18
19 procedure TProgressForm.AbortButtonClick(Sender: TObject);
20 begin
21 FCancel := True;
22 end;
23
24 {Note: could use int64 instead of COMP, but that would make this D4 specific}
25
26 function CopyCallback(TotalFileSize, TotalBytesTransferred, StreamSize,
27 StreamBytesTransferred: COMP; dwStreamNumber, dwCallbackReason: DWORD;
28 hSourceFile, hDestinationFile: THandle; progressform: TProgressForm): DWORD;
29 stdcall;
30 var
31 newpos: Integer;
32 begin
33 Result := PROCESS_CONTINUE;
34 if dwCallbackReason = CALLBACK_CHUNK_FINISHED then
35 begin
36 newpos := Round(TotalBytesTransferred / TotalFileSize * 100);
37 with progressform.Progressbar do
38 if newpos <> Position then
39 Position := newpos;
40 Application.ProcessMessages;
41 end;
42 end;
43
44 function DoFilecopy(const source, target: string): Boolean;
45 var
46 progressform: TProgressForm;
47 begin
48 progressform := TProgressform.Create;
49 try
50 progressform.Show;
51 Application.ProcessMessages;
52 Result := CopyFileEx(PChar(source), PChar(target), @CopyCallback,
53 Pointer(progressform), @progressform.FCancel, 0);
54 finally
55 progressform.Hide;
56 progressform.free;
57 end;
58 end;
|