在Delphi中获取发送方组件的数组索引 [英] Get array index of sender component in Delphi

查看:143
本文介绍了在Delphi中获取发送方组件的数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有一个数组(可以说是20个组件),这些数组是我从代码中以编程方式创建的,并且向所有组件添加相同的onClick过程时,是否可以通过以下方法获取组件的数组索引:该过程的Sender变量?

When I have an array of, lets say, 20 components, that I create programmatically from the code, and I add the same onClick procedure to all of them, is there a way that I can get the component's array index via the Sender variable of the procedure?

我知道我可以通过(Sender as TComponentType)访问其他属性。属性,但这就是我可以想到的所有与Sender一起完成的工作。

I know I can access to other properties by (Sender as TComponentType).Property, but that's mostly all I can think of doing with the Sender variable.

示例:

var Button: array [0..9] of TButton;

for i := 0 to 9 do
  begin
    Button[i]:=TButton.Create(Self);
    Button[i].OnClick:=ButtonClick;
  end;


procedure ButtonClick(Sender: TObject);
begin
  // Here I'd like to get the "i" of the sender Button[i]
end


推荐答案

为了清晰起见,将不同的答案发布为社区Wiki(对我而言没有投票),因为没有人愿意发布他们出于某些奇怪的原因

您可以从TButton创建自定义后代,并向其中添加自己的字段:

You can make a custom descendant from TButton and add your own field to it:

type
  TMyButton = class(TButton)
  public
    Tag2: Integer;
  end;

for i := 0 to 9 do
begin
  Button[i] := TMyButton.Create(Self);
  Button[i].OnClick := ButtonClick;
  Button[i].Tag2 := i;
end;

procedure ButtonClick(Sender: TObject);
var
  i: Integer;
begin
  // get the "i" of the sender Button from Tag
  i := TMyButton(Sender).Tag2;
end;

这篇关于在Delphi中获取发送方组件的数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆