本文實例總結了C#子窗體與父窗體通信方法。分享給大家供大家參考。具體如下:
【第一種方法:】
第一步:
創建接口IForm,父窗體繼承這個接口
public interface IForm{ void RefreshForm();}
第二步:
父窗體實現接口中的方法,在實現接口的方法中寫入刷新代碼
Form2 f = new Form2();f.Owner = this;f.ShowDialog();
第三步:
在子窗體中調用,刷新的方法
【第二種方法:】
1.父窗體中定義刷新的方法RefreshForm()
2.在點擊的事件Show出子窗體的時候,代碼如下:
Form form=new Form();form.Show(this);
3.在子窗體的點擊事件中,代碼如下:
【第三種方法:】
通過事件解決方法:
子窗體中定義:
public delegate void sendmessage(string message); public event sendmessage SendTo ;
主窗體:
ChildForm frm = new ChildForm(); frm.SendTo += new ChildForm.sendmessage(SendArgs); frm.ShowDialog(this);private void SendArgs(string Message)//主窗體接收消息 {MessageBox.Show( "主窗體已收到消息: " + Message);}
子窗體測試:
【第四種方法:】
通過引用:
下例演示怎樣通過引用類型實現你的功能:
子窗體中定義:
新構造函數:
public ChildForm(MainForm parent) { InitializeComponent();this.ParentFrom = parent;//引用 }
主窗體中某Click:
ChildForm frm = new ChildForm(this); frm.ShowDialog(this);
子窗體測試:
void ...Click(....) { this.Text = "測試引用 "; if (this.ParentFrom != null) this.ParentFrom.Text += "- " + this.Text;//....... }
希望本文所述對大家的C#程序設計有所幫助。
新聞熱點
疑難解答