利用自定义事件实现不同窗体间的通讯 -- Delphi篇

类别:Delphi 点击:0 评论:0 推荐:
    要实现子窗体与父窗体之间的通讯,有多种方法(比如:重载子窗体的构造函数,将父窗体的引用作为参数传递给子窗体)。下面我要介绍的是利用自定义事件的方法,它能够最大程度的避免模块之间的耦合,充分体现面向对象的优点。    先将效果图展示给大家:下面是实现代码: Unit2 //子窗体 type   //声明自定义事件的类型(类似于C#中的委托)  TMyEventHandle = procedure (Sender: TObject; Content: string) of object;   TForm2 = class(TForm)    ComboBox1: TComboBox;    Label1: TLabel;    procedure ComboBox1Click(Sender: TObject);  private    FOnSelectionChanged: TMyEventHandle;  public     //声明自定义事件    property OnSelectionChanged: TMyEventHandle      read FOnSelectionChanged write FOnSelectionChanged;  end; procedure TForm2.ComboBox1Click(Sender: TObject);begin   //当选择改变时,触发自定义的事件  if Assigned(FOnSelectionChanged) then    FOnSelectionChanged(Self, ComboBox1.Text);end;  Unit1 //父窗体 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);    //指定当m_frm2的自定义事件发生时的处理程序  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://com.8s8s.com/it/it4230.htm