TProgressBarStepIt (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example reads bytes from a file in tenths of the size of the file. The ProgressBar displays the status of each 1/10th step as they are read into the buffer. This example requires a TButton and a TProgressBar control on the form.

Code

procedure TForm1.Button1Click(Sender: TObject);
const
  FName = 'about.txt';  // To obtain a more interesting result, use a file larger than 2048 bytes.
var
  F: File;
  MyData: array[1..2048] of byte;
  BytesRead: LongInt;
begin
  AssignFile(F, FName);
  try
    Reset(F, 1);
    ProgressBar1.Max := FileSize(F);
    if (ProgressBar1.Max > 10) then
    begin
      // Amount to move when the StepIt method called
      ProgressBar1.Step := ProgressBar1.Max div 10;
      ProgressBar1.Step := Min(ProgressBar1.Step, 2048);
    end
    else
      ProgressBar1.Step := ProgressBar1.Max;
    while (ProgressBar1.Position < ProgressBar1.Max) do
    begin
      // Read one Step size chunk of data to buffer.
      BlockRead(F, MyData, ProgressBar1.Step, BytesRead);
      // Move the ProgressBar Position using StepIt.
      ProgressBar1.StepIt; // move by Step amount
      // Do this or the reading will wrap and start over.
      ProgressBar1.Step :=
          Min(ProgressBar1.Step, ProgressBar1.Max - ProgressBar1.Position);

    end;
  finally;
    CloseFile(F);
  end;
end;

Uses