在父窗體上,改變CheckBox控制項的狀態,實現子窗體的開啟和關閉。在子窗體上,點選關閉按鈕後,父窗體CheckBox控制項變成未選取狀態。
1.方法
這裡用委託事件的方法,實現窗體的相互存取。
2.父窗體(主窗體)
父窗體上放置5個CheckBox控制項。並將他們賦值到CheckBox[]數組,以便程式碼進行循環呼叫。
CheckBox[] checkBox;public MainFormBERT() { InitializeComponent(); checkBox = new CheckBox[5]; checkBox[0] = this.checkBox1; checkBox[1] = this.checkBox2; checkBox[2] = this.checkBox3; checkBox[3] = this.checkBox4; checkBox[4] = this.checkBox5; }
為CheckBox控制項新增事件。並定義OpenOrCloseSubFormPPG(int i)方法實作開啟或關閉子窗體。此方法呼叫了子窗體的事件,以對應RecvInfo(int number)方法,設定CheckBox控制項為未選取狀態:
subFormPPGTx[i].SendToParent += new SubFormPPG.SendFun(RecvInfo);
private void checkBox1_CheckedChanged(object sender, EventArgs e) { OpenOrCloseSubFormPPG(0); }private void checkBox2_CheckedChanged(object sender, EventArgs e) { OpenOrCloseSubFormPPG(1); }private void checkBox3_CheckedChanged(object sender, EventArgs e) { OpenOrCloseSubFormPPG(2); }private void checkBox4_CheckedChanged(object sender, EventArgs e) { OpenOrCloseSubFormPPG(3); }private void checkBox5_CheckedChanged(object sender, EventArgs e) { OpenOrCloseSubFormPPG(4); } SubFormPPG[] subFormPPGTx = { null, null, null, null, null};private void OpenOrCloseSubFormPPG(int i) { try { if (checkBox[i].Checked) { string formTitle, formName; if (i < 0 || i > 4) { throw new IndexOutOfRangeException("Channel is out of range"); } else if (i == 4) { formTitle = "ParallelWrite"; formName = "subFormPPG" + formTitle; } else { formTitle = "Tx" + i; formName = "subFormPPG" + formTitle; } if (subFormPPGTx[i] == null || subFormPPGTx[i].IsDisposed) { subFormPPGTx[i] = new SubFormPPG(); subFormPPGTx[i].Text = formTitle; subFormPPGTx[i].Name = formName; subFormPPGTx[i].Tag = i; subFormPPGTx[i].SendToParent += new SubFormPPG.SendFun(RecvInfo);//调用子窗体的事件 subFormPPGTx[i].Show(this); } else { subFormPPGTx[i].WindowState = FormWindowState.Normal; subFormPPGTx[i].Activate(); } } else { //subFormPPGTx[0].Close(); subFormPPGTx[i].Dispose(); subFormPPGTx[i] = null; } } catch (IndexOutOfRangeException ex) { MessageBox.Show(ex.Message); } catch (Exception ex) { MessageBox.Show(ex.Message); } }private void RecvInfo(int number) { this.checkBox[number].Checked = false; }
3.子窗體
新增事件SendToParent,當子窗體關閉時,響應事件,將訊息傳遞給父窗體。
public delegate void SendFun(int number); public event SendFun SendToParent; private void SubFormPPG_FormClosed(object sender, FormClosedEventArgs e) { if (SendToParent != null) { SendToParent((int)this.Tag); } }
以上就是 從0自學C#05--窗體之間的相互訪問的內容,更多相關內容請關注PHP中文網(www.php.cn)!