在Pascal中,有没有一种方法可以为多个按钮使用一个过程?

7
我正在寻找一种方法,可以为多个按钮使用一个过程。这是为了一个类似于测验的东西,您必须按Button 1回答问题1,但是复制并粘贴36个按钮的整个代码,并为36个按钮更改变量对任何人来说都不是有趣的事情。
因此,我认为可能会出现以下情况:
procedure TForm1.Button[x]Click(Sender: TObject);
begin
  DoTask[x];
end;

X是变量。 这种方式是否可行,或者还有其他方法可以获得相同的结果?

从tbutton(sender).name中检索“x”,而不是使用其他方法?只需向后扫描数字即可。 - Marco van de Voort
1个回答

7
最简单的方法是:
  1. Number the buttons using the Tag property in the Object Inspector (or in code when they're created) in order to easily tell them apart. (Or assign the value you want to be passed to your procedure/function when that button is clicked.)

  2. Create one event handler, and assign it to all of the buttons you want to be handled by the same code.

  3. The Sender parameter the event receives will be the button that was clicked, which you can then cast as a TButton.

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

非常感谢您的帮助。但是,我对Pascal相当不熟悉,甚至可以说是没有经验,所以...如果您愿意,能否详细说明第二步?就像我不知道如何使用事件处理程序,更不用说从头开始创建一个基本的事件处理程序了。 - Pascalerino
双击IDE中的任何一个按钮,这将创建例程的外壳(例如,“Button1Click”)。使用对象检查器上该按钮的事件选项卡将其重命名为更通用的内容(例如“ButtonsClick”)。按住Ctrl并单击要共享相同事件的窗体上所有按钮,切换到对象检查器事件选项卡,并将该通用的“ButtonsClick”事件选择为所有按钮的OnClick处理程序。(或者仅使用对象检查器将其分别分配给每个按钮。) - Ken White
好的,谢谢,这样就清楚多了!但是我还有一个问题,如何将Tbutton.tag赋值给一个变量?QuestionNumber:= TButton.Tag; 显然行不通。 - Pascalerino
这段代码“QuestionNumber := (Sender as TButton).Tag”是可用的,同样,“TButton(Sender).Tag”也是可行的(只要你确定“Sender”是一个“TButton”)。 - Ken White

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