ColdZer0
ColdZer0

Reputation: 233

how to know how many times button has been clicked?

I want to do something after the button is clicked the 2nd time and the 3rd time and so on.

Upvotes: 1

Views: 2169

Answers (2)

Michael Vincent
Michael Vincent

Reputation: 1660

I know you've already accepted an answer, but, FWIW, this is how I would do it.

If the button clicked count does not need to be used outside of the OnClick() handler, you could keep the counter local to the handler by using a typed constant like this:

procedure TForm1.Button1.click(Sender: TObject);
{$J+}
const
  counter: integer = 0;
{$J-}
begin
  inc(counter);

  if (counter < 2) then exit;
end;

Notes:

1) the {$J+} allows assignment to typed constants.

2) the use of typed constants like this has been deprecated for many years (even though they are useful for stuff like this - keeping the declaration and use of a "variable" close to each other is a good thing in my book and using a form level variable for this seems wrong as it kind of breaks encapsulation).

Upvotes: -1

Ken White
Ken White

Reputation: 125708

Declare a form-level variable, and increment it each time the button is clicked.

type
  TForm1 = class(TForm)
    // component/control variables
  private
    FClickCount: Integer;
  end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  FClickCount := FClickCount + 1;  // or Inc(FClickCount);
end;

Upvotes: 8

Related Questions