检查richtextbox上的选定文本是否全部为粗体

如何检查richtextbox上的选定文本是否全部为粗体。 例如:

asdasd asd asd←这并不全是大胆的
我都大胆 ←这是大胆的

这是我所做的代码,它可以检查它是否全部为粗体但是它的速度很慢,因为它使用Selection.Start逐个检查char并Selection.Start Selection.Length并检查是否为粗体。

 bool allbold = 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) { allbold = false; richTextBox1.SelectionStart = 0; richTextBox1.SelectionLength = 0; richTextBox1.SelectionStart = start; richTextBox1.SelectionLength = end; richTextBox1.Focus(); } } 

有没有比这更有效的方法?

您可以检查richTextBox1.SelectionFont.Bold 。 如果所有选定文本都是粗体,则返回true。


要进行测试,只需使用以下值初始化RichTextBox

 richTextBox1.SelectedRtf = @"{\rtf1\fbidis\ansi\ansicpg1256\deff0" + @"\deflang1065{\fonttbl{\f0\fnil\fcharset0 Calibri;}}\uc1\pard\ltrpar" + @"\lang9\b\f0\fs72 T\fs22 his\b0 \bi\b0 sa \bt\b0 est.}"; 

然后以这种方式检查不同的选择

 if (richTextBox1.SelectionFont != null) MessageBox.Show(string.Format("{0}", richTextBox1.SelectionFont.Bold));