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

时间:2020-12-01 12:54:20

要实现子窗体与父窗体之间的通讯,有多种方法(比如:重载子窗体的构造函数,将父窗体的引用作为参数传递给子窗体)。下面我要介绍的是利用自定义事件的方法,它能够最大程度的避免模块之间的耦合,充分体现面向对象的优点。
  先将效果图展示给大家:
  

[[The No.1 Picture.]]

  下面是实现代码:
  
  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://m.ithao123.cn/content-7386687.html