The Unofficial Newsletter of Delphi Users - by Robert Vivrette


Displaying "Time Remaining" in Your Applications

Matt Hamilton - mhamilton@bunge.com.au

Another little tip! Here's how to have those "3 minutes remaining" labels (like Internet Explorer's file download dialog) in your own application.

This example assumes that you have some sort of loop (perhaps a "while not EOF" or something), and a progress bar.

First, you'll need a TTimer to update the label. This is a bit more efficient than updating the label every iteration of your loop, since the time remaining doesn't change that often. Disable the timer by default, and set its update interval to a couple of seconds.

Now, before your loop starts, place the following code:

ProgressBar1.Tag := GetTickCount;
Timer1.Enabled := True;
Next, use this code in your OnTimer event:
procedure TForm1.Timer1Timer(Sender: TObject);
var
   h, m: Integer;
   s: string;
begin
   with ProgressBar1 do
      if Position <> 0 then
      begin
         m := Trunc((Int(GetTickCount) - Tag) * (Max - Position) / Position / 60000);
         h := Trunc(m / 60);
         m := m - h * 60;

         if h = 1 then
            s := '1 hour and '
         else if h > 1 then
            s := '%0:d hours and ';

         if m = 0 then
            s := s + '< 1 minute'
         else if m = 1 then
            s := s + '1 minute'
         else if m > 1 then
            s := s + '%1:d minutes';

         Label1.Caption := Format(s + ' remaining', [h, m]);
      end;
end;

Note that Label1 in this example is the "time remaining" label. Also note that I have typecast GetTickCount to Integer, so as to avoid any "comparing signed and unsigned" warnings.

Try it out! It's a bit sporadic for the first few updates, but the longer your program runs, the more accurate it becomes!