5
mybox.Checked := true;

Setting TRadioButton to checked (by code) causes OnClick event handler to be called.

How can I recognize if user is making the state change by GUI interaction

Lars Truijens
  • 42,837
  • 6
  • 126
  • 143
Tom
  • 6,725
  • 24
  • 95
  • 159

4 Answers4

11

You can nil the OnClick event handler while changing a radiobutton state programmatically:

procedure TForm1.Button6Click(Sender: TObject);
var
  Save: TNotifyEvent;

begin
  Save:= RadioButton2.OnClick;
  RadioButton2.OnClick:= nil;
  RadioButton2.Checked:= not RadioButton2.Checked;
  RadioButton2.OnClick:= Save;
end;
kludg
  • 27,213
  • 5
  • 67
  • 118
  • 2
    Ideally you should wrap this in a try..finally if there was any more complex logic between `OnClick := nil` and `OnClick := Save;` – Gerry Coll May 18 '10 at 22:20
4
 mybox.Tag := 666; 
 mybox.Checked :=true; 
 mybox.Tag := 0;

procedure myboxOnclick(Sender : TObject);
begin
if Tag = 0 then
//Do your thing
end;
Mihaela
  • 2,482
  • 3
  • 21
  • 27
  • I favor this approach but usually use an flag in the private section of the form class, something along the lines of "ChangingStuffRomCode:Boolean". The idea's that there usually are multiple radio buttons (and other controls that behave like this) and it's simpler to do set a single flag when initializing the form. – Cosmin Prund May 19 '10 at 09:58
3

If you have an action connected to the radiobutton, you can set the checked property of the action instead. This will also prevent the OnClick event to be fired.

Uwe Raabe
  • 45,288
  • 3
  • 82
  • 130
  • But if you're using actions, you're probably using the action's OnExecute event, not the control's OnClick event. Does OnExecute get fired when you change the action's Checked property? – Rob Kennedy May 18 '10 at 14:29
  • 1
    @Rob Kennedy: No, it does not - Action.OnExecute and Button.OnClick is the same event here. An action temporally sets the radiobutton's protected 'ClicksDisabled' property to True to prevent radiobutton's 'OnClick' event to fire while changing 'Checked' property. – kludg May 18 '10 at 14:53
0

TRadioButton (like TCheckBox) provides a protected property ClicksDisabled that can help you.

I use class helpers to add the needed functionality:

RadioButton1.SetCheckedWithoutClick(False);

with the following class helper for a VCL TRadioButton:

TRadioButtonHelper = class helper for TRadioButton
    procedure SetCheckedWithoutClick(AChecked: Boolean);
end;

procedure TRadioButtonHelper.SetCheckedWithoutClick(AChecked: Boolean);
begin
    ClicksDisabled := True;
    try
        Checked := AChecked;
    finally
        ClicksDisabled := False;
    end;
end;
yonojoy
  • 5,486
  • 1
  • 31
  • 60