📄 faq55.htm
字号:
<HTML>
<HEAD>
<TITLE>Get information from TObject* Sender in an event</TITLE>
<META NAME="Author" CONTENT="Harold Howe">
</HEAD>
<BODY BGCOLOR="WHITE">
<CENTER>
<TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH="640">
<TR>
<TD>
<H3>
Get information from TObject* Sender in an event</H3>
<BR>
<P>
The event handlers in BCB pass a <TT>TObject</TT> pointer
called <TT>Sender</TT> to the handler function. This pointer tells the handler
function what VCL control generated the event. However, since the pointer is a
<TT>TObject</TT> pointer, you cannot treat it as if it were a button or a menu item.
To obtain useful information from the <TT>Sender</TT> argument, you will often times need
to cast the pointer. The code below uses the new <TT>dynamic_cast</TT> C++
type safe cast to convert Sender to a concrete VCL object.
</P>
<pre>
<b>void</b> <b>__fastcall</b> TForm1<b>:</b><b>:</b>Button2Click<b>(</b>TObject <b>*</b>Sender<b>)</b>
<b>{</b>
TButton <b>*</b>btn <b>=</b> <b>dynamic_cast</b>< TButton <b>*</b> <b>></b><b>(</b>Sender<b>)</b><b>;</b>
<b>if</b><b>(</b><b>!</b>btn<b>)</b>
<b>return</b><b>;</b>
btn<b>-></b>Caption <b>=</b> <font color="blue">"New Caption"</font><b>;</b>
<b>}</b>
</pre>
<P>
<TT>dynamic_cast</TT> returns <TT>NULL</TT> if the <TT>Sender</TT> object is not
a valid instance of the class. In the code above, <TT>dynamic_cast</TT> returns
<TT>NULL</TT> if <TT>Sender</TT> is not really a button. The <TT>if</TT> test checks to
see if the cast operation failed.
</P>
<B>Note:</B>
<P>
Sometimes, you can live without the cast if you only need to identify who triggered
the event. The code below clarifies what I mean.
</P>
<pre>
<b>void</b> <b>__fastcall</b> TForm1<b>:</b><b>:</b>Button2Click<b>(</b>TObject <b>*</b>Sender<b>)</b>
<b>{</b>
<font color="navy">// Test Sender to see if its the same pointer as Button1.</font>
<font color="navy">// If they are the same, change the Caption of Button1</font>
<b>if</b><b>(</b>Button1 <b>==</b> Sender<b>)</b>
Button1<b>-></b>Caption <b>=</b> <font color="blue">"New Caption"</font><b>;</b>
<b>}</b>
</pre>
</TD> </TR>
</TABLE>
</CENTER>
</BODY>
</HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -