在富文本框中格式化文本,该文本位于2个选定字符之间

时间:2017-02-17 09:45:15

标签: c# string winforms richtextbox

我需要格式化文本,因为它是在富文本框中输入的。所以例如..

文本文本(文本文本文本)文本文本文本。

括号中的文字在输入时更改为指定的字体和颜色,当括号关闭时,以下任何文字都会返回到'使用'富文本框默认字体/颜色。

到目前为止我所拥有的......

private void FormatMiddleText (string start, string end, Font font, Color color)    
{
    this.richTextBox1.SelectionColor = color;
    this.richTextBox1.SelectionFont = font;
}

...用法

FontFamily fontFamily = new FontFamily("Arial");
Font font = new Font(
   fontFamily,
   16,
   FontStyle.Bold,
   GraphicsUnit.Pixel);


FormatMiddleText("(",")", Color.Red,  font)

无法解决如何RichTextBox选择开始和结束字符串之间的文本。

2 个答案:

答案 0 :(得分:1)

您需要的是跟踪所选文本。开始和结束。所以这必须进入你的FormatMiddleText方法,因为它应该是索引int将是更好的类型:

private void FormatMiddleText(int start, int end, Font font, Color color)
{
    richTextBox1.SelectionStart = start;
    richTextBox1.SelectionLength = end;

    this.richTextBox1.SelectionColor = color;
    this.richTextBox1.SelectionFont = font;
    // reset the selection start so you can keep typing at the right hand side
    richTextBox1.SelectionStart = richTextBox1.Text.Length;
}

现在您需要跟踪输入内容。您需要一个startIndex并计算文本的格式化程度。另外一个标志是很好的知道你是否应用你的“酷”格式或无聊的默认格式

int startIndex = 0;
int charCount = 0;
bool startFormatting = false;

现在,您可以使用TextChanged事件来处理用户在文本中键入的格式:

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
    if (richTextBox1.Text.Last() == '(')
    {
        // remember the start index
        startIndex = richTextBox1.Text.Length-1; // -1 will take the "(" also to be formatted
        startFormatting = true; // now you can start formatting with the cool font
    }

    if (richTextBox1.Text.Last() == ')')
    {
        MessageBox.Show("found end ");
        startIndex = richTextBox1.Text.Length;
        startFormatting = false;   // now you can proceed to format with boring default font             
    }

    charCount++;

    if (startFormatting)
    {
        FormatMiddleText(startIndex, charCount, font, Color.Red);
    }
    else
    {
        FormatMiddleText(startIndex, charCount, DefaultFont, Color.Black);
    }
}

我还没有找到一种方法来重置字体并保持默认写入而不进行常量格式化。因为设置richTextBox1.Font = DefaultFont;会重置括号之间的格式。所以我选择保持格式化。如果您找到方法,请告诉我

答案 1 :(得分:0)

这应该可以解决问题。

    private void rtb_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.D0 && e.Shift)
        {
            this.richTextBox1.SelectionColor = Color.Black;
        }
    }

    private void rtb_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == '(')
        {
            this.richTextBox1.SelectionColor = Color.Red;
        }
    }

您可以使用SelectionFont代替SelectionColor来提供更复杂的字体属性。此外,您可以用任何开始和结束字符替换括号以获得相同的效果。希望这有帮助!