Delphi中(Sender:TObject)
<pre id="best-content-2283507653" accuse="aContent" class="best-text mb-10" style="margin: 10px 0px; padding: 0px; font-family: "PingFang SC", "Lantinghei SC", "Microsoft YaHei", arial, 宋体, sans-serif, tahoma; white-space: pre-wrap; word-wrap: break-word; font-size: 16px; line-height: 29px; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); min-height: 55px;">1.Sender的定义:
每一个事件处理里面至少都有一个Sender参数。比如:
procedure TForm1.Button1Click(Sender:TObject);
begin
...
end;
Sender的含义就是代表调用TForm1.Button1Click这个过程的控件. 由于Sender是TObject,所以任何object都可以赋给Sender.
当你点击BUTTON1时,会产生一个Button1Click事件,系统会把Button1传递给Button1Click过程作为参数,也就是所说的Sender.
2.Sender的用法:
<1>.由于Sender代表了调用所在过程的控件,那么你就可以直接把它拿来当那个控件用,不过如果要用属性的话,最好写成(Sender as 控件名).控件属性:=... 例如:
procedure TForm1.Edit1Click(Sender: TObject);
begin
with Sender as TEdit do
begin
text:=’hello’;
end;
end;
<2>.如果在两个事件中处理同样的事情,那么可以利用Sender来省去重写同样的过程。例如:
Procedure TForm1.Button1Click(Sender:TObject);
begin
do same sth.....;
if Sender=Button1 then
do sth....;
if Sender=Button2 then
do other sth....;
end;
procedure TForm1.Button2Click(Sender:TOBJect);
begin
Button1Click(Button2);
end;</pre>