To implement communication between a subform and a parent form, there are several methods (such as overloading the child form's constructor, passing the parent form's reference as an argument to the subform). I would like to introduce the use of custom events method, it can minimize the coupling between the modules, fully embodies the advantages of object-oriented.
First, we will show you:
[[The picture]]
Here is the implementation code:
Unit2//Subform
Type
Declaring the type of the custom event (similar to a delegate in C #)
Tmyeventhandle = procedure (sender:tobject; content:string) of object;
TForm2 = Class (Tform)
Combobox1:tcombobox;
Label1:tlabel;
Procedure Combobox1click (Sender:tobject);
Private
Fonselectionchanged:tmyeventhandle;
Public
Declaring custom events
Property Onselectionchanged:tmyeventhandle
Read fonselectionchanged write fonselectionchanged;
End
Procedure Tform2.combobox1click (Sender:tobject);
Begin
Trigger a custom event when the selection is changed
If Assigned (fonselectionchanged) Then
Fonselectionchanged (self, combobox1.text);
End
UNIT1//Parent form
Type
TForm1 = Class (Tform)
Btnopenform2:tbutton;
Edit1:tedit;
Label1:tlabel;
Procedure Btnopenform2click (Sender:tobject);
Private
M_frm2:tform2;
Procedure frm2_selectionchanged (Sender:tobject; content:string);
Public
Constructor Create (aowner:tcomponent); Override
destructor Destroy; Override
End
Constructor Tform1.create (aowner:tcomponent);
Begin
Inherited Create (Aowner);
M_frm2: = Tform2.create (self);
Specifies the handler when a custom event for M_frm2 occurs
M_frm2. OnSelectionChanged: = frm2_selectionchanged;
End
destructor Tform1.destroy;
Begin
M_frm2. Free;
Inherited Destroy;
End
Procedure tform1.frm2_selectionchanged (Sender:tobject; content:string);
Begin
Edit1.text: = Content;
End
Procedure Tform1.btnopenform2click (Sender:tobject);
Begin
M_frm2. ShowModal;
End
Http://m.ithao123.cn/content-7386687.html
Custom event implementation communication between different forms Delphi Chapter