Search code examples
delphivcl

Delphi: hook ToggleSwitch manual State change to avoid a Click call


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?


Solution

  • 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;