父子窗口傳遞數據主要經過屬性和委託完成。 c#
對話框主要分爲模態和非模態兩種對話框。本文參考http://bbs.csdn.net/topics/360140208一文實現這個功能。 框架
父窗口 函數
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private MyDialog m_dlg; private void toolStripButton1_Click(object sender, EventArgs e) { MyDialog dlg = new MyDialog(richTextBox1.Text); if (dlg.ShowDialog() == DialogResult.OK) { richTextBox1.Text = dlg.TextBoxValue; } } private void toolStripButton2_Click(object sender, EventArgs e) { if (m_dlg == null) { m_dlg = new MyDialog(richTextBox1.Text); m_dlg.TextBoxChanged += new EventHandler( (sender1, e1) => { richTextBox1.Text = m_dlg.TextBoxValue; } ); m_dlg.FormClosed += new FormClosedEventHandler( (sender2, e2) => { m_dlg = null; } ); m_dlg.Show(this); } else { m_dlg.Activate(); } } } }
子窗口 this
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class MyDialog : Form { public event EventHandler TextBoxChanged; public string TextBoxValue { get { return textBox1.Text; } set { textBox1.Text = value; } } public MyDialog() : this("") { } public MyDialog(string Param) { InitializeComponent(); TextBoxValue = Param; } private void textBox1_TextChanged(object sender, EventArgs e) { if (TextBoxChanged != null) TextBoxChanged(this, e); } private void button1_Click(object sender, EventArgs e) { Close(); } } }
模態傳值的方法是:傳入時能夠使用構造函數,傳出的時候首先判斷是否用戶是經過肯定關閉的,若是是,那麼用屬性傳出。這個作法也是框架庫的作法,好比打開文件對話框。
非模態的狀況略微複雜:由於咱們須要主窗體能和子窗體實時交互,爲了同步主窗體和子窗體的數據,咱們用了事件。有人問了,爲何咱們不能讓子窗體直接操做主窗體,這是由於考慮到對話框能夠被重用,若是讓它直接操做主窗口那麼就限制死了這個子窗口只能被某個特定的主窗口調用。爲了解除子窗體對調用者的耦合,咱們使用事件。若是子窗體已經被顯示,主窗體再次調用子窗體,那麼一般咱們但願激活子窗體而不是再顯示一個。 spa
參考資料 .net
http://bbs.csdn.net/topics/360140208