使用 Sender 参数

来源:互联网 发布:11.4恒大淘宝的比赛 编辑:程序博客网 时间:2024/05/01 05:05

In an event handler, the Sender parameter indicates which component received the event and therefore called the handler. Sometimes it is useful to have several components share an event handler that behaves differently depending on which component calls it. You can do this by using the Sender parameter in an if...then...else statement. For example, the following code displays the title of the application in the caption of a dialog box only if the OnClick event was received by Button1.

在一个事件句柄,Sender参数指的是哪一个组件接受该事件并因此调用了该事件。有时当几个组件共用同一事件句柄是很有用的,事件产生不同的行为是由调用它的组件所决定。要做到这点,你只要将Sender参数与if……then……else语句结合使用就可以了。下列代码示范了当button1按钮的OnClick事件发生时将程序的标题显示在指定对话框的标题上。
procedure TMainForm.Button1Click(Sender: TObject);
begin
if Sender = Button1 then 
  AboutBox.Caption := 'About ' + Application.Title 
else
  AboutBox.Caption := ''; 
AboutBox.ShowModal;
end;