Delphi Tutorials »

Timed Dialogs - AutoCloseDlg


If you want a TimedDialog box that is closed automatically after a certain delay, here's the source for an "AutoCloseDlg" unit. You can call this dialog from your Delphi source code just like you'd call any other dialog, for example:

AutoCloseDlg.Execute('Warning', 
  'Unexpected value in edit-box AGE. Please correct.', 5000); 

Here's the code:

  1. Add a new form to your project and name it frmTimedDialog.
  2. Save the unit of this form as TimedDialog.
  3. Set the form's BorderStyle property to bsDialog.
  4. Add three components:
    - a TTimer; set its property Enabled to False;
    - a TMemo;
    - a TBitButton; set its property Kind to bkOK.
  5. In the PUBLIC section of unit TimedDlg, declare a procedure with the name Execute (the part in red):
    unit TimedDialog;
    interface
    uses
      Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
      StdCtrls, Buttons;
    type
      TfrmTimedDialog = class(TForm)
      btnOK: TBitBtn;
      private
      { Private declarations }
      public
      { Public declarations }
        procedure Execute(Title, Contents: string;
    Delay: integer); // added by you
      end;
    var
      frmTimedDlg: TfrmTimedDlg;
  6. In the implementation section of your new unit, add the following code:
  7. procedure TfrmTimedDlg.Execute(Title, Contents: string;
    Delay: integer);
    begin
      Caption := Title;
      Memo1.Text := Contents;
    
      Timer1.Delay := Delay;
      ShowModal;
    end;
  8. Double click on the TTimer component. Delphi will write an "OnTimer" event handler in your code.
  9. Complete this "OnTimer" procedure as follows:
    procedure TfrmTimedDialog.Timer1Timer;
    begin
      Timer1.Enabled := False; // stop the timer
      ModalResult := mrOK;     // close the form
    end;

The function Execute shows the dialog form in a "modal" way, that means: the window opens on top of the other window(s) and your application doesn't continue before this dialog form is closed.
If the user clicks the OK button, the dialog form is closed. But the form will be closed automatically if the user doesn't click the OK button within "Delay" seconds.

Note: don't forget to add the unit TimedDialog to the uses directive in each unit that uses TimedDialog.Execute, like this:

   uses ..., ..., TimedDialog;

TOP  DelphiLand Club Membership  DC Library  Forum  Forum Archives  Crash Course Delphi  Tips  Source Code  Downloads  Links

© Copyright DelphiLand 1999-2016