在父窗体上,改变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)!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号