C++ Builder Tutorials

Write your own dialogs

Let's built a custom dialog, that works just like the C++ Builder's dialog components.
But we don't want to develop a full blown component (with published properties and methods for creation and destroying, and more complicated stuff...) because that would be a bit overkill.

Let's suppose that you want a simple dialogbox that looks like the one above. You want to call that dialog from your code by clicking Button1 on your main form:

void __fastcall TForm1::Button1Click(TObject *Sender)
  if (UserDialog->Execute())
    Label1->Caption = "Username: " + UserDialog->UserName;
    Label1->Caption = "Error: no username was entered";

Building the example

  1. Add a new form to your project and call it UserDialog.
  2. Save the new unit as UserDlg.
  3. Set the form's Caption to 'Please enter your username:' and set its BorderStyle property to bsDialog.
  4. Add three components:
    - a TEdit; clear its Text property.
    - a TBitButton; set its property Kind to bkOK.
    - a second TBitButton; set its property Kind to bkCancel.
  5. In UserDlg.h, add two lines under public: as follows:
    public:		    // User declarations
      String UserName;
      __fastcall TUserDialog(TComponent* Owner);
      bool Execute();
  6. In UserDlg.cpp, add the following function implementation at the end of the unit:
    bool TUserDialog::Execute()
      return (ModalResult == mrOk);
  7. Through the Object Inspector, create an event handler for OnClick of Button1 and complete it as follows:
    void __fastcall TUserDialog::BitBtn1Click(TObject *Sender)
      UserName = Edit1->Text;
  8. Select Unit1.cpp and switch to Design mode.
  9. In the menu, select File / Use unit... and select UserDlg.cpp
  10. Save all and test your program.

That's all! But how does your program's magic 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.
  • If the user clicks the OK button, the dialog is automatically closed and our Execute function returns True.
  • If the Cancel button is clicked, the dialog also closes, but we receive False.
  • Also when the UserDialog is closed in another way, we get False.
  • Finally, the text of the edit-box is copied to the public variable UserName, from where other units can access it.

See also:

  Timed Dialog