Componentes - ligando componentes a ponteiros |
Top Previous Next |
|
Linking Components using Pointers
{ This tip will come in handy if you have a lot of controls on your form which all do pretty much the same thing, but when each of them affects a different component. For example, let's say you have a "View" menu, with several items, each of which do nothing but ShowModal a different form. Ordinarily you'd have a different OnClick for each menu item, with a line like this: }
Form2.ShowModal;
{ However, there's a "cleaner" way! You can "link" each menu item to the form it views using pointers and the "Tag" property. In the OnCreate of the form, use lines like this: } ViewForm2Item.Tag := LongInt(@Form2); ViewForm3Item.Tag := LongInt(@Form3);
// . . . and so on for each item. Then, generate an OnClick for one of the items, and make it look like this:
procedure TMainWnd.ViewForm2ItemClick(Sender: TObject); begin TForm(Pointer(TMenuItem(Sender).Tag)^).ShowModal; end; { If you look closely at this line, you'll see that we've cast the "Tag" of the menu item to a pointer, and referenced the memory it points to as a form. Then we've shown this form modally. You can then point each of the menu items to this single event handler.
This technique works with any components - as they can all be referenced as pointers, and they all have Tag properties. It's handy for linking two controls for which no formal linking method (like "DataSource" or "FocusControl" etc) exists. } |