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

C# 检查richtextbox上的选定文本是否全部为粗体,c#,.net,winforms,richtextbox,C#,.net,Winforms,Richtextbox,如何检查richtextbox上的选定文本是否全部为粗体。例如: asdasdasdasd← 这不全是粗体的 我都是粗体的← 这都是大胆的 这是我编写的代码,它可以检查是否全部加粗,但速度很慢,因为它使用Selection.Start到Selection.Length并检查是否加粗。 bool allbold = true; int start = richTextBox1.SelectionStart; int end = richTextBox1.SelectionLength; for (

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

asdasdasdasd← 这不全是粗体的
我都是粗体的← 这都是大胆的

这是我编写的代码,它可以检查是否全部加粗,但速度很慢,因为它使用
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();
    }
}
bool allbold=true;
int start=richTextBox1.SelectionStart;
int end=richTextBox1.SelectionLength;
for(int i=1;i

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

您可以检查
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  \b i\b0 s a \b t\b0 est.}";
然后通过以下方式检查不同的选择:

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

对于初学者,您可以通过添加
break
一旦找到不粗体的内容。您可以选中
richTextBox1.SelectionFont.bold
,如果所有选定的文本都是粗体,则返回true。有什么问题?不确定它是否有效;你在雷扎测试过吗?实际需要的是混合权重的第三个值。@TaW,是的,如果
SelectionFont
不为空,则
SelectionFont.Bold
在所有选定文本均为粗体时返回true<代码>选择字体
为空,当所选内容包含不同字体时。@t新问题是不同的,您可能遗漏了新问题的某些部分。看来这个新问题需要重新讨论。在这个问题中,OP需要检查整个选择是否为粗体,在新的问题中OP需要检测3种状态:整体为粗体,混合内容,不包含粗体。这个问题的答案不能用于新的问题。嗨@Reza Aghaei Thx为答案。但我今天早上才意识到,我正在检查所选的文本是否都有字符,但这些字符并不都是粗体的。既然这篇文章得到了回答,我就提出了另一个问题。如果你想帮忙,这里有个问题。
[