在Delphi中执行自动取消选中按钮的操作

3

当按下 TSpeedButton 时,我希望执行一个操作,当“未按下”相同的按钮时,我希望执行另一个操作。我知道没有 onunpress 事件,但是否有任何简单的方法让我在按下不同的按钮时执行操作?

procedure ActionName.ActionNameExecute(Sender: TObject);
begin
  PreviousActionName.execute(Sender);
  //
end;

看起来太笨重了。

2个回答

5

虽然没有“未压缩”的属性,但您可以查询Down属性。

这个例子需要进行一些不太干净的转换,但它适用于操作和OnClick事件。

procedure Form1.ActionExecute(Sender: TObject);
var
  sb : TSpeedButton;
begin
  if Sender is TSpeedButton then
    sb := TSpeedButton(Sender)
  else if (Sender is TAction) and (TAction(Sender).ActionComponent is TSpeedButton) then
    sb := TSpeedButton(TAction(Sender).ActionComponent)
  else 
    sb := nil;

  if sb=nil then
    DoNormalAction(Sender)
  else if sb.Down then
    DoDownAction(sb)
  else 
    DoUpAction(sb);
end;

5
根据您所描述的情况,我猜测您使用了GroupIndex <>0的SpeedButton,但同一组中没有其他按钮,或者至少不像单选按钮(AllowAllUp True)那样工作。
当按下按钮时,您只有一个onClick事件,但要执行的操作取决于按钮的状态是否具有GroupIndex。
因此,在onClick事件处理程序中,您必须测试Down是否为False,因为Down在触发onClick处理程序之前更新。
例如:
procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
  with Sender as TSpeedButton do
  begin
    if Down then
      showmessage('pressing')
    else
      showmessage('unpressing');
  end;
end;

@Francois,在这种情况下,Sender是一个动作,所以当TSpeedButton作为Sender时会引发异常。 - Toon Krijthe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接