简体   繁体   中英

How to fire “Click” event of Checkbox using “Label Click” event in Delphi?

In my Delphi XE2 Project, I am having Form1 , Label1 and CheckBox1 .

My requirement is to set the CheckBox1.Font.Color := clGreen; .

Thought I have written

procedure TForm1.FormCreate(Sender: TObject);
begin
  CheckBox1.Font.Color := clGreen;
end;

yet the Font Color is default Black . So I have defined it in other way as follows:

  1. I have removed the Caption from the CheckBox1 and changed the Width to 17 .
  2. Then I have placed Label1 next to CheckBox1 like CleckBox1 Caption .
  3. After that I have written:

procedure TForm1.Label1Click(Sender: TObject);
begin
  CheckBox1.Click;
end;

to Toggle the state of CheckBox1 .

But I am getting [DCC Error] Unit1.pas(37): E2362 Cannot access protected symbol TCustomCheckBox.Click .

And another question is that whether the OnMouseDown Event of CheckBox1 can be triggered as the following image: 表格1

The Click() method merely triggers the contro's OnClick event, nothing else. It does not actually cause the control to perform click-related logic, like updating its internal state.

You can toggle the CheckBox's state like this:

CheckBox1.Checked := not CheckBox1.Checked;

Alternatively, use an accessor class to reach protected members:

type
  TCheckBoxAccess = class(TCheckBox)
  end;

TCheckBoxAccess(CheckBox1).Toggle;

You can use it like :

procedure TForm1.Label1Click(Sender: TObject);
begin
//either
CheckBox1.Checked := not CheckBox1.Checked;  // this trigger onClick event!!
// or 
// if you absolutely need it.. 
CheckBox1Click(Sender); // NOTE this will not check or uncheck CheckBox1
end;

But note you use here a TLabel Object (Sender). If you do not use Sender you can do it Without further attention.

But it's better to put the code for enable and disable other control out of the event. only one line for example doenable() .

procedure TForm1.doEnable(enable: Boolean);
begin
  Edit1.Enabled := enable; 
  Edit2.Enabled := enable;
  Edit3.Enabled :=  NOT enable;
  if enable then Label1.Font.Color := clGreen else Label1.Font.Color := clWindowText;
  ...
end;


procedure TForm1.Label1Click(Sender: TObject);
begin
  // NOTE This trigger also CheckBox1 Click event. 
  CheckBox1.Checked := not CheckBox1.Checked; 
  // NOT needed.
  //if CheckBox1.Checked then doEnable(true) else doEnable(false);
end;

procedure TForm1.CheckBox1Click(Sender: TObject);
begin
  if CheckBox1.Checked then doEnable(true) else doEnable(false);
end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM