Is there a way to use ONE procedure for several buttons in Pascal?

I am looking for a way to use one procedure for several buttons. This is for a quiz, how you should press button 1 for question 1, but copying and pasting all the code into 36 buttons and changing the variables to 36 buttons is not very funny for anyone.

So, I thought it was possible:

procedure TForm1.Button[x]Click(Sender: TObject); begin DoTask[x]; end; 

X is a variable.

Is something like this possible or are there other ways to get the same result?

+6
source share
1 answer

The easiest way to do this:

  • Highlight buttons using the Tag property in the Object Inspector (or in the code when they are created) to easily separate them. (Or assign the value you want to pass to your procedure / function when this button is pressed.)

  • Create one event handler and assign it to all the buttons that you want to process with the same code.

  • The Sender parameter received by the event will be a pressed button, which you can then use as TButton .

     procedure TForm1.ButtonsClick(Sender: TObject); var TheButton: TButton; begin TheButton := Sender as TButton; DoTask(TheButton.Tag); end; 
+6
source

Source: https://habr.com/ru/post/980539/


All Articles