Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change CheckBox state without calling OnClick Event

I'm wondering so when I change state of CheckBox

CheckBox->Checked=false;

It calls CheckBoxOnClick Event , how to avoid it ?

like image 502
cnd Avatar asked Feb 15 '10 06:02

cnd


4 Answers

In newer Delphi versions you can use class helpers to add this functionality:

CheckBox.SetCheckedWithoutClick(False);

by using the following class helper for a VCL TCheckBox:

TCheckBoxHelper = class helper for TCheckBox
    procedure SetCheckedWithoutClick(AChecked: Boolean);
end;

procedure TCheckBoxHelper.SetCheckedWithoutClick(AChecked: Boolean);
begin
    ClicksDisabled := True;
    try
        Checked := AChecked;
    finally
        ClicksDisabled := False;
    end;
end;

Just for completeness: A FMX TCheckBox will behave similar (triggering OnChange). You can workaround this by using the following class helper:

TCheckBoxHelper = class helper for TCheckBox
    procedure SetCheckedWithoutClick(AChecked: Boolean);
end;

procedure TCheckBoxHelper.SetCheckedWithoutClick(AChecked: Boolean);
var
    BckEvent: TNotifyEvent;
begin
    BckEvent := OnChange;
    OnChange := nil;
    try
        IsChecked := AChecked;
    finally
        OnChange := BckEvent;
    end;
end;

Disclaimer: Thanks, dummzeuch for the original idea. Be aware of the usual hints regarding class helpers.

like image 96
yonojoy Avatar answered Nov 20 '22 13:11

yonojoy


You could surround the onClick event code with something like

if myFlag then
  begin
    ...event code...
  end;

If you don't want it to be executed, set myFlag to false and after the checkbox state's change set it back to true.

like image 37
Holgerwa Avatar answered Nov 20 '22 13:11

Holgerwa


Another option is to change the protected ClicksDisable property using an interposer class like this:

type
  THackCheckBox = class(TCustomCheckBox)
  end;

procedure TCheckBox_SetCheckedNoOnClick(_Chk: TCustomCheckBox; _Checked: boolean);
var
  Chk: THackCheckBox;
begin
  Chk := THackCheckBox(_Chk);
  Chk.ClicksDisabled := true;
  try
    Chk.Checked := _Checked;
  finally
    Chk.ClicksDisabled := false;
  end;
end;
like image 10
dummzeuch Avatar answered Nov 20 '22 14:11

dummzeuch


I hope there's a button solution but you could store the current event in a TNotifyEvent var, then set Checkbox.OnChecked to nil and afterwards restore it.

like image 7
Remko Avatar answered Nov 20 '22 13:11

Remko