1

Delphi Rio 10.3.2

With the TToggleSwitch component, when you manually change the State property, i.e

ToggleSwitch1.State := tssOff 

the OnClick event is called. How can I prevent this?

hikari
  • 3,393
  • 1
  • 33
  • 72

1 Answers1

4

You have a few choices:

  • set the OnClick property to nil before setting the State, then restore the event handler afterwards.

    ToggleSwitch1.OnClick := nil;
    try
      ToggleSwitch1.State := ...;
    finally
      ToggleSwitch1.OnClick := ToggleSwitch1Click;
    end;
    
  • set a flag before setting the State, then clear the flag afterwards, and have the OnClick event handler check the flag before doing anything.

    ToggleSwitch1.Tag := 1;
    try
      ToggleSwitch1.State := ...;
    finally
      ToggleSwitch1.Tag := 0;
    end;
    
    procedure TMyForm.ToggleSwitch1Click(Sender: TObject);
    begin
      if ToggleSwitch1.Tag <> 0 then Exit;
      ...
    end;
    
  • use an accessor class to reach the protected FClicksDisabled member so you can temporarily set it to True while changing the State:

    type
      TToggleSwitchAccess = class(TToggleSwitch)
      end;
    
    TToggleSwitchAccess(ToggleSwitch1).FClicksDisabled := True;
    try
      ToggleSwitch1.State := ...;
    finally
      TToggleSwitchAccess(ToggleSwitch1).FClicksDisabled := False;
    end;
    
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • FWIW, controls like `TCheckBox` or `TRadioButton` behave the same - they fire `OnClick` when changing the value of `Checked` property. They both inherit from `TButtonControl` which has protected property [`ClicksDisabled`](http://docwiki.embarcadero.com/Libraries/Rio/en/Vcl.StdCtrls.TButtonControl.ClicksDisabled) to mute `OnClick`, but its description is slightly misleading. Similarly, `TToggleSwitch` has undocumented protected property `FClicksDisabled`. – Peter Wolf Aug 14 '19 at 00:30
  • @PeterWolf Good point. And [it is documented](http://docwiki.embarcadero.com/Libraries/en/Vcl.WinXCtrls.TCustomToggleSwitch.FClicksDisabled) actually, just not very well. But it does say "*This field is used internally during the toggle switch state changes*", at least. – Remy Lebeau Aug 14 '19 at 01:45
  • D'oh! Of course it's documented. I was searching properties instead of fields ... But there's even more fun with events. `TEdit` [will fire OnChange event](https://stackoverflow.com/questions/2014541/delphi-how-to-set-text-in-tedit-tmaskedit-without-invoking-the-onchange-event) when setting `Text` from code. `TComboBox`, on the other hand, [doesn't fire OnChange](https://stackoverflow.com/questions/37586597/altering-itemindex-of-tcombobox-does-not-trigger-its-onchange-event) nor `OnSelect` when changing its `Text` or `ItemIndex` and this is even documented behaviour. – Peter Wolf Aug 14 '19 at 10:00