获得 MDI 窗体中,子窗体中被选中的文本
假设我们编写类似word的多文档编辑器,我们需要把子窗体中选中的文本居中,居右等显示。
private void 新建NToolStripButton_Click_1(object sender, EventArgs e)
{
SubWin sw = new SubWin();
sw.MdiParent = this;
sw.Show();
}
{
SubWin sw = new SubWin();
sw.MdiParent = this;
sw.Show();
}
然后,我们利用一个方法,获得当前窗体中RichTextBox控件
/// <summary>
/// 获得RichTextBox控件
/// </summary>
/// <returns></returns>
private RichTextBox getRichTextBox()
{
Form CurrentForm = this.ActiveMdiChild;//获得当前被激活的窗体
//得到当前窗体中的 RichTextBox
foreach (Control CurrentControl in CurrentForm.Controls)
{
if ((CurrentControl as RichTextBox)!=null)
{
return (RichTextBox)CurrentControl;
}
}
return null;
}
最后,我们在toolStrip的居左,居右,居中三个按钮上使用这个方法,目的是子窗体中RichTextBox的文本,能居中,居左或居右显示。/// 获得RichTextBox控件
/// </summary>
/// <returns></returns>
private RichTextBox getRichTextBox()
{
Form CurrentForm = this.ActiveMdiChild;//获得当前被激活的窗体
//得到当前窗体中的 RichTextBox
foreach (Control CurrentControl in CurrentForm.Controls)
{
if ((CurrentControl as RichTextBox)!=null)
{
return (RichTextBox)CurrentControl;
}
}
return null;
}
private void 居左toolStripButton1_Click(object sender, EventArgs e)
{
getRichTextBox().SelectionAlignment = HorizontalAlignment.Left;
}
private void 居中toolStripButton2_Click(object sender, EventArgs e)
{
getRichTextBox().SelectionAlignment = HorizontalAlignment.Center;
}
private void 居右toolStripButton3_Click(object sender, EventArgs e)
{
getRichTextBox().SelectionAlignment = HorizontalAlignment.Right;
}
{
getRichTextBox().SelectionAlignment = HorizontalAlignment.Left;
}
private void 居中toolStripButton2_Click(object sender, EventArgs e)
{
getRichTextBox().SelectionAlignment = HorizontalAlignment.Center;
}
private void 居右toolStripButton3_Click(object sender, EventArgs e)
{
getRichTextBox().SelectionAlignment = HorizontalAlignment.Right;
}