在父表單上,改變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--表單之間的相互訪問的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!