检查 richtextbox 上的选定文本是否全部为粗体或混合 [C#]

Check if selected text on richtextbox is not all bold or mixed [C#]

如何检查 richtextbox 上的选定文本是否

its chars is not all bold.

例如:

notboldboldnotbold ← 这个是混合的。
我不是全粗体 ← 这不是全粗体

这是我编写的代码,它检查 richtextbox 上的选定文本是否包含一些粗体文本。
它很慢,因为它使用 Selection.Start 一个一个地检查字符到 Selection.Length 并检查是否为粗体。如果我使用 richTextBox1.SelectionFont.Bold 它将 return false 因为它不是所有粗体,这也意味着如果它混合了粗体而不是粗体。

bool notallbold = true;
int start = richTextBox1.SelectionStart;
int end = richTextBox1.SelectionLength;
for (int i = 1; i < end; i++)
{
    richTextBox1.SelectionStart = start+i;
    richTextBox1.SelectionLength = 1;
    if (richTextBox1.SelectionFont.Bold)
    {
        notallbold = false;
        richTextBox1.SelectionStart = 0;
        richTextBox1.SelectionLength = 0;
        richTextBox1.SelectionStart = start;
        richTextBox1.SelectionLength = end;
        richTextBox1.Focus();
    }
}

检查长字符串时,我可以看到文本在检查时变粗了。 还有比这更有效的方法吗?

在 RTF 文本中,\b 表示文本粗体部分的开始。所以你可以先检查richTextBox1.SelectionFont.Bold是否为true,则表示文本全部为粗体,否则,如果所选rtf包含\b,则表示内容是混合的,否则所选中没有粗体文​​本文字:

private void button1_Click(object sender, EventArgs e)
{
    if (richTextBox1.SelectionFont == null)
        return;
    if (richTextBox1.SelectionFont.Bold)
        MessageBox.Show("All text is Bold");
    else if (richTextBox1.SelectedRtf.Replace(@"\", "").IndexOf(@"\b") > -1)
        MessageBox.Show("Mixed Content");
    else
        MessageBox.Show("Text doesn't contain Bold");
}

为了测试解决方案,用这样的值初始化 RichtextBox 就足够了:

this.richTextBox1.SelectedRtf = @"{\rtf1\fbidis\ansi\ansicpg1256\deff0\deflang1065" +
    @"{\fonttbl{\f0\fnil\fcharset0 Calibri;}}\uc1\pard\ltrpar" +
    @"\lang9\b\f0\fs22 T\b0 his is a \b test}";