开发者

Is it possible to access a TButton using tag?

开发者 https://www.devze.com 2023-01-31 15:24 出处:网络
I hope to access a T开发者_运维百科Button using tag. IS it possible? for example, I hope set the caption of a TButton (button1 has tag 3) as \'aaa\',

I hope to access a T开发者_运维百科Button using tag. IS it possible?

for example, I hope set the caption of a TButton (button1 has tag 3) as 'aaa', I know I can use

button1.caption:='aaa';

but I hope to use tag '3' to access the tbutton and set the string value 'aaa'.

Welcome any comment

Thanks

interdev


procedure TForm1.ChnCaptionByTag(SearchTag: integer; NewCpt: string);
var
  i: Integer;
begin
  for i := 0 to ComponentCount - 1 do
    if Components[i] is TButton then
    begin
      if TButton(Components[i]).Tag = SearchTag then
         TButton(Components[i]).Caption := NewCpt;
    end;
end;


There is no direct way to do

 ButtonByTag(3).Caption := 'aaa';

You can search through a form's components looking for something with a tag of 3:

 var C: TComponent;

 for C in Self.Components do
    if C is TCustomButton then
      if C.Tag = 3 then
        (C as TCustomButton).Caption := 'aaa'

But note that you could have plenty of components with the same tag, it's not guaranteed unique.


I think this should work:

procedure TForm1.SetCaption(iTag: Integer; mCaption: String);
var
  i: Integer;
begin
  for i:= 0 to controlcount-1 do
    if controls[i] is TButton then
      if TButton(controls[i]).Tag = iTag then
        TButton(controls[i]).Caption := mCaption;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  SetCaption(3,'aaa');
end;


Well, right now the Tag property is the same size as a Pointer, so you could, but you need to describe a bit more of what it is you'd like to do.

I'm not positive that this is going to continue to be the case moving into 64-bit Delphi, but I think that's the case too.

Edit: Yes, TComponent.Tag should be a NativeInt in future versions. References: Barry Kelly, Alexandru Ciobanu


procedure TForm1.ChangeCaptionByTag(const SearchTag: integer; const NewCaption: string);
var i: Integer;
begin
  for i in Components do
    if Components[i] is TButton then
      if (Components[i] as TButton).Tag = SearchTag then
        begin
          (Components[i] as TButton).Caption := NewCaption;
          Break;
        end;
end;
0

精彩评论

暂无评论...
验证码 换一张
取 消