如果有多个richtextbox,如何在richtextbox中加粗文字?

时间:2018-01-03 08:34:47

标签: c#

这是我的代码,只有一个richtextbox。但是,我不知道如何处理多个richtextbox

private void BoldToolStripMenuItem_Click(object sender, EventArgs e)
{
    richTextBox1.SelectionFont = new font(currentFont.FontFamily, FontStyle.Bold);
}

3 个答案:

答案 0 :(得分:2)

表单的ActiveControl属性可以帮您节省开支。触发工具条按钮的Click事件时,ActiveControl仍然保持对刚失去焦点的控件的引用。您的工具条按钮的Click实现将起作用:

private void toolStripButton1_Click(object sender, EventArgs e)
{
    // check if the active control (held by the Form) was a RichTextbox
    var rtb = this.ActiveControl as RichTextBox;
    if (rtb != null)
    {
        // if it is, do the right thing
        rtb.SelectionFont = new Font(rtb.Font, FontStyle.Bold);
    }
}

这可能是这样的:

enter image description here

答案 1 :(得分:0)

与此answer类似,你可以做类似的事情

 private void BoldTextBoxes()
 {
     Action<Control.ControlCollection> func = null;

     func = (controls) =>
         {
             foreach (Control control in controls)
                 if (control is RichTextBox)
                     (control as RichTextBox).SelectionFont = new font(currentFont.FontFamily, FontStyle.Bold);
                 else
                     func(control.Controls);
         };

     func(Controls);
 }

答案 2 :(得分:-1)

非常简单:

    private void BoldToolStripMenuItem_Click(object sender, EventArgs e)
    {

    richTextBox1.SelectionFont = new font(currentFont.FontFamily, FontStyle.Bold);
    richTextBox2.SelectionFont = new font(currentFont.FontFamily, FontStyle.Bold);
    richTextBox3.SelectionFont = new font(currentFont.FontFamily, FontStyle.Bold);
    // Continue
    }