如果 TSpeedButton 已经关闭,如何提前退出()?

How to Exit() early if TSpeedButton is already Down?

我有两个 TSpeedButtonbtn1btn2。它们的属性被设置为在一组中一起行动并且相互排斥,这意味着当一个按钮被按下时另一个按钮会自动松开:

AllowAllUp = False
GroupIndex = 1
OnClick = onSpeedButtonsClick

我在 onSpeedButtonsClick() 中有一些代码根据点击两个按钮中的哪一个来运行一些代码。

我想要做的是,如果 btn1 当前为 Down,并且用户按下此按钮,则不会发生任何事情:

procedure frmMyForm.onSpeedButtonsClick(Sender: TObject);
begin
  { Don't do anything if the clicked button is already currently pressed down. }
  if ((Sender = btn1) and btn1.Down) or
       ((Sender = btn2) and btn2.Down) then
    Exit();

  { ... some other code here that should only run when
    the `Down` state of the buttons changes }
end;

问题是当btn1当前处于关闭状态并且用户按下btn2时,btn2Down属性设置为True before onSpeedButtonsClick() 执行,所以无论如何它 Exit() 早。

只需将按钮状态存储在表单字段中,然后像这样在事件处理程序的末尾设置它(我使用了位字段)

bState := Ord(btn1.Down) or (Ord(btn2.Down) shl 1);

正在检查:

   if (bState and 1) <> 0 then  
//it would be nicer to use constants like btn1down = 1 instead of magic numbers
      btn1 WAS down before
   if (bState and 2) <> 0 then
      btn2 WAS down before

我会使用按钮的 Tag 属性来跟踪所需的状态,例如:

procedure frmMyForm.onSpeedButtonsClick(Sender: TObject);
begin
  if TSpeedButton(Sender).Tag <> 0 then Exit;
  TSpeedButton(Sender).Tag := 1;
  if Sender = btn1 then btn2.Tag := 0
  else btn1.Tag := 0;

  // code that runs when the `Down` state changes ...
end;