-2

Say that I have three switches, namely SW_A, SW_B, and SW_ALL.

When SW_A is clicked (from off to on), TMemo prints 'SW_A is on', and the same works for SW_B.

However, when SW_ALL is clicked(from off to on), TMemo prints 'SW_ALL is on', and SW_A and SW_B should both be turned on no matter what their current states were without printing 'SW_A is on' and 'SW_B is on.'

My problem is that whenever SW_All is clicked, other switches also prints their states out. Does anyone know how to solve the problem? Thanks!!

procedure TForm1.SW_ALLSwitch(Sender: TObject);
begin
  if SW_All.IsChecked then
  begin
    Memo1.Lines.Add('SW_All is on');

    SW_Alarm_A.IsChecked := True;
    SW_Alarm_B.IsChecked := True;

  end
  else
  begin
    Memo1.Lines.Add('SW_All is off');

    SW_Alarm_A.IsChecked := False;
    SW_Alarm_B.IsChecked := False;

  end;

end;


procedure TForm1.SW_ASwitch(Sender: TObject);
begin
  if SW_A.IsChecked = False then
    Memo1.Lines.Add('SW_A is off')
  else
    Memo1.Lines.Add('SW_A is on');
end;
Alvin Lin
  • 199
  • 2
  • 5
  • 13
  • What you did not say is what kind of control `SW_A` is, and what events the two handlers are attached to. Please can you make these points clear. – David Heffernan Dec 08 '14 at 11:50

1 Answers1

2

It is unclear if there is a problem only when "SW_ALL is clicked(from off to on)", or if there is a problem "whenever SW_ALL is clicked". The following is a solution for "whenever SW_ALL is clicked".

The switch component presumably has an OnSwitch event. When you switch SW_ALL and programmatically change the state of the other switches, the OnSwitch events of SW_A and SW_B fires just as they do when clicked on.

To temporarily prevent SW_A and SW_B from reacting to switch events you can assign nil to the OnSwitch events, change the switch state and the reassign the OnSwitch event. For example

procedure TForm1.SW_ALLSwitch(Sender: TObject);
var
  TempOnSwA, TempOnSwB: TNotifyEvent;
begin
  TempOnSwA := SW_Alarm_A.OnSwitch;
  SW_Alarm_A.OnSwitch := nil;
  TempOnSwB := SW_Alarm_B.OnSwitch;
  SW_Alarm_B.OnSwitch := nil;

  if SW_All.IsChecked then
  begin
    Memo1.Lines.Add('SW_All is on');

    SW_Alarm_A.IsChecked := True;
    SW_Alarm_B.IsChecked := True;

  end
  else
  begin
    Memo1.Lines.Add('SW_All is off');

    SW_Alarm_A.IsChecked := False;
    SW_Alarm_B.IsChecked := False;

  end;

  SW_Alarm_A.OnSwitch := TempOnSwA;
  SW_Alarm_B.OnSwitch := TempOnSwB;
end;
Tom Brunberg
  • 20,312
  • 8
  • 37
  • 54