delphi事件参数sender的用法例程

http://www.hackpig.cn/post/320.html

 

注意,如果你想为上面每个按钮做一个onclick是一种错误的思想,正确的做法是全选这5个按钮,然后做它们的onclick事件。
写如代码: Edit1.Text:=Edit1.Text+ TButton(Sender).Caption;


事件处理函数Sender:TObject参数,代表着“激发这个事件函数的控件”。我们可以把这个参数转为具体的类型,来访问控件实例。该参数往往和控件的Tag属性配合使用,对于简单事件函数的调用,如果我们确定参数中没用到Sender,可以用nil来充当Sender参数。

下面是源代码:
-------------------------------------------------------------------------------------

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    Button5: TButton;
    Edit1: TEdit;
    procedure Button1Click(Sender: TObject);
  p rivate
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  Edit1.Text:=Edit1.Text+ TButton(Sender).Caption;
end;

end.

界面代码:
--------------------------------------------------------

object Form1: TForm1
  Left = 275
  Top = 274
  Width = 340
  Height = 264
  Caption = 'Sender演示  猪悟能'
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 13
  object Button1: TButton
    Left = 42
    Top = 23
    Width = 75
    Height = 25
    Caption = '1'
    TabOrder = 0
    OnClick = Button1Click
  end
  object Button2: TButton
    Left = 42
    Top = 56
    Width = 75
    Height = 25
    Caption = '2'
    TabOrder = 1
    OnClick = Button1Click
  end
  object Button3: TButton
    Left = 42
    Top = 90
    Width = 75
    Height = 25
    Caption = '3'
    TabOrder = 2
    OnClick = Button1Click
  end
  object Button4: TButton
    Left = 42
    Top = 124
    Width = 75
    Height = 25
    Caption = '4'
    TabOrder = 3
    OnClick = Button1Click
  end
  object Button5: TButton
    Left = 42
    Top = 157
    Width = 75
    Height = 25
    Caption = '5'
    TabOrder = 4
    OnClick = Button1Click
  end
  object Edit1: TEdit
    Left = 131
    Top = 24
    Width = 121
    Height = 21
    TabOrder = 5
  end
end

源代码下载:http://www.rayfile.com/files/63599be3-23f0-11df-bedc-0015c55db73d/

 第二个例子:
加个pageControl控件,计划用5个按钮去控制5个页标签。

首先把按钮的tag标签设好,为0-4
然后在按钮的onclick事件中加入代码:PageControl1.ActivePageIndex:=TComponent(Sender).Tag;

 

源代码下载:http://www.rayfile.com/files/71db0ac0-23f2-11df-be1d-0015c55db73d/

原文地址:https://www.cnblogs.com/chulia20002001/p/1921707.html