You are here: Home » Builder » [ En ] » Message box with check box

Message box with check box

21 January |

  Here is an easy way to make a custom message box with a check box bellow the buttons. No need for MessageBox hooks or any other “magics”, just plain VCL:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
TModalResult CheckMessageDialog(AnsiString Message, AnsiString Caption,
  AnsiString CheckBoxCaption, bool *Checked,
  TMsgDlgType DlgType, TMsgDlgButtons Buttons)
{
   TForm *Dialog=CreateMessageDialog(Message, DlgType, Buttons);
   if (!Caption.IsEmpty()) Dialog->Caption = Caption;

   int LeftEdge=Dialog->ClientWidth;
   int TopEdge =Dialog->ClientHeight;
   if (Dialog->ControlCount>0) {
     for (int i = 1; i < Dialog->ControlCount; i++) {
       TControl *Ctrl=Dialog->Controls[i];
       if (Ctrl->Left < LeftEdge) LeftEdge=Ctrl->Left;
       if (Ctrl->Top  < TopEdge)  TopEdge =Ctrl->Top;
     }
   } else {
     LeftEdge=10;
     TopEdge=10;
   }

   TCheckBox * CheckBox = new TCheckBox(Dialog);
   CheckBox->Parent  = Dialog;
   CheckBox->Caption = CheckBoxCaption;
   CheckBox->Checked = *Checked;
   CheckBox->Left    = LeftEdge;
   CheckBox->Top     = Dialog->ClientHeight;
   CheckBox->Width   = Dialog->Canvas->TextWidth(CheckBox->Caption)+30;

   Dialog->ClientHeight = Dialog->ClientHeight + CheckBox->Height + TopEdge;

   if (CheckBox->Width + LeftEdge*2 > Dialog->ClientWidth)
     Dialog->ClientWidth = CheckBox->Width + LeftEdge*2;

   TModalResult Result = Dialog->ShowModal();
   *Checked = CheckBox->Checked;

   delete Dialog;
   Dialog=NULL;
   
   return Result;
}

Using it is simple :

1
2
3
4
5
6
bool checkv=true;  //checkbox  value
TModalResult res= CheckMessageDialog("Are you sure you want to do whatever you were supposed to do?",
                "The caption","Don't show this message again",&checkv,mtConfirmation,
                TMsgDlgButtons() << mbYes << mbNo  << mbIgnore);

ShowMessage("Check box " + AnsiString(checkv ? "checked":"not cheked") + "\n dialog result:" + AnsiString(res));
You like this post? Be the first of my friends to give me a beer! click here. Thanks!
Filed under

Builder, [ En ]

| Tags:

1 Comments.

  1. 1
    delete Dialog;

    Hi do we not need to delete the Checkbox before the above line?

    1
    2
    delete CheckBox;
    delete Dialog;

    Cheers Stu