C++ Builder Tutorials

A timed dialog -- auto-closing dialog box

Suppose that you want a dialog-box that closes automatically, say after 15 seconds.
You want to call that dialog by clicking a button on your main form:

void __fastcall TForm1::Button1Click(TObject *Sender)
  TimedDlg.Execute("Warning", "Invalid entry in edit-box AGE.
                    Please correct.");

Here's a quick and simple solution, made with C++ Builder:

  1. Add a new form to your project and name it TimedDialog.
  2. Save the new unit as TimedDlg.
  3. Set the form's BorderStyle property to bsDialog.
  4. Add three components:
    - a TTimer. Set its property Interval to 15000 (that's 15000 milliseconds). Or set it to less -- for
      example, 5000 for 5 seconds. Set the timer's property Enabled to False.
    - a TMemo.
    - a TBitBtn. Set its property Kind to bkOK.
  5. In TimedDlg.h, add a line under public: as follows:
    public:		    // User declarations
      __fastcall TUserDialog(TComponent* Owner);
      void Execute(String Title, String Contents);
  6. In TimedDlg.cpp, add the following function implementation at the end of the unit:
    void TTimedDialog::Execute(String Title, String Contents)
      Caption = Title;          // set the caption of the form
      Memo1->Text = Contents;   // set the text of the memo
      Timer1->Enabled = True;   // start the timer
      ShowModal();              // show the form
    Timer1->Enabled = False; // stop the timer }
  7. Double click on the TTimer component and complete the event handler as follows:
    void __fastcall TTimedDialog::Timer1Timer(TObject *Sender)
    { Close(); // close the form }
  8. Select Unit1.cpp and in the menu, select File / Use unit..., next select TimedDlg.cpp.
  9. Save all and test your program.

How does it work?

  • The function Execute shows the UserDialog form in a "modal" way, that means: the window will open on top of the other window(s) and the application does not continue before UserDialog is closed.
    A timer is started.
  • If the user clicks the OK button, the form is automatically closed, because the button's Kind is bkOK.
  • If the user doesn't click the OK button before the timer fires, the form is closed "automagically".

See also:

  Custom Dialogs