出現bug的原因是我點擊Main form中一個按鈕,彈出一個form窗口A,然后A關閉的時候,返回Main。然后發現操作的次數多了就會出現上述bug,剛開始以為是創建句柄出錯,寫了下面一段代碼:
/*窗體在InitializeComponent()的時候如果創建不成功,嘗試在Form的子類中重寫CreateHandle,如果創建不成功,通過RecreateHandle,一般都會成功的 */ protected override void CreateHandle() { if (!IsHandleCreated) { try { base.CreateHandle(); } catch { } finally { if (!IsHandleCreated) { base.RecreateHandle(); } } } }
不過后來發現還是不管用,就以為是需要dispose操作,所以又加了一段代碼:
using (AForm A = new AForm()) { A.ShowDialog(this.Parent.Parent); }
但是,后來經過測試,發現還是不行,最后,我覺得可能是從A返回Main的時候,是在Main的父窗口中new的Main,因此又換了種形式。
先在A中,定義一個事件委托,用於進入Main的load方法,更新Main中的數據,代碼如下:
public event EventHandler LoadHandler; // 用於調用父窗體load事件委托
public void btnSave_Click(object sender, EventArgs e) { SaveData(); this.Close(); MessageBox.Show("數據保存成功!"); this.Dispose(); if (LoadHandler != null) { LoadHandler(sender, e); } }
然后在AForm的click事件中添加如下代碼:
private void lbl_edit1_Click(object sender, EventArgs e) { using (AForm A = new AForm()) { A.LoadHandler += this.AForm_Load; A.ShowDialog(this.Parent.Parent); } }
經過這三處代碼的修改,發現此bug解決了!!!