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)
Label1->Caption = "Username: " + UserDialog->UserName;
Label1->Caption = "Error: no username was entered";
Building the example
- Add a new form to your project and call it UserDialog.
- Save the new unit as UserDlg.
- Set the form's Caption to 'Please enter your username:'
and set its BorderStyle property to bsDialog.
- 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.
- In UserDlg.h, add two lines under public: as follows:
public: // User declarations
__fastcall TUserDialog(TComponent* Owner);
- In UserDlg.cpp, add the following function implementation at the end of the unit:
return (ModalResult == mrOk);
- Through the Object Inspector, create an event handler for OnClick of Button1 and complete it
void __fastcall TUserDialog::BitBtn1Click(TObject *Sender)
UserName = Edit1->Text;
- Select Unit1.cpp and switch to Design mode.
- In the menu, select File / Use unit... and select UserDlg.cpp
- 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
- 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.