拷贝文件显示进度条

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    btn1: TButton;
    ProgressBar1: TProgressBar;
    procedure btn1Click(Sender: TObject);
  private
    { Private declarations }
  public
    procedure CopyFileProgressBar(getPath,setPath:string);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.CopyFileProgressBar(getPath,setPath:string);

var

  getStream,setStream: TFileStream;

  num, n: Integer;

  buf: PByte;

  BufSize,block: Integer;

begin

  if not FileExists(getPath) then

  begin

   // ShowMessage('源文件不存在');

   // Exit;

  end;

  getStream := TFileStream.Create(getPath, fmOpenRead or fmShareExclusive);

  setStream := TFileStream.Create(setPath, fmCreate);

  num := getStream.Size;

  setStream.Size := num;

  getStream.Position := 0;

  setStream.Position := 0;

  BufSize := num;

  block := BufSize div 100;

  GetMem(buf, BufSize);

  form1.ProgressBar1.Max := 100;

  form1.ProgressBar1.Min := 0;

  form1.ProgressBar1.Position := 0;

  while num <> 0 do

  begin

    Application.ProcessMessages;

    n := block;

    if n > num then n := num;

    getStream.ReadBuffer(buf^, n);

    setStream.WriteBuffer(buf^, n);

    form1.ProgressBar1.Position := Trunc((1 - num / BufSize) * 100);

    Dec(num, n);

    sleep(100); //为了演示 进度条的进度变化效果 可以打开sleep(100)
  end;

  FreeMem(buf, BufSize);

  getStream.Free;

  setStream.Free;

  //ShowMessage('复制完毕');

  form1.ProgressBar1.Position := 0;

end;

procedure TForm1.btn1Click(Sender: TObject);
begin
  CopyFileProgressBar('Java编程思想.pdf','xx.pdf');
end;

end.

你可能感兴趣的:(拷贝文件显示进度条)