检查Richtextbox上的选定文本是否全部为粗体或混合字体[C#] [英] Check if selected text on richtextbox is not all bold or mixed [C#]

查看:64
本文介绍了检查Richtextbox上的选定文本是否全部为粗体或混合字体[C#]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to check if selected text on richtextbox that

它的字符不是全部加粗.

its chars is not all bold.

例如:

notbold 粗体 notbold←这是混合的.
我不是全黑的←这不是全黑的

notboldboldnotbold ← this is mixed.
Im not all bold ← this is not all bold

这是我编写的代码,它检查richtextbox上选定的文本是否包含一些加粗的文本.
之所以缓慢,是因为它使用Selection.Start to Selection.Length逐个检查字符,并检查如果大胆.如果我使用 richTextBox1.SelectionFont.Bold ,它将返回false,因为它不是全部为粗体,这也意味着如果其与粗体而不是粗体混合.

This is the code I have made, it checks selected text on richtextbox whether the text contains some bolded text or not.
its slow because its checking the char one by one using Selection.Start to Selection.Length and check if bold. If I use richTextBox1.SelectionFont.Bold it will return false because its not all bold, that means also if its mixed with bold and not bold.

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();
    }
}

检查长字符串时,可以看到检查时文本变粗体.除此之外,还有什么有效的方法吗?

When checking long string, I can see the text is getting bolded when checking. Is there any efficient way than this?

推荐答案

在RTF文本中, \ b 表示文本的粗体部分的开头.因此,您可以先检查 richTextBox1.SelectionFont.Bold 是否为true,然后表示文本为粗体,否则,如果选定的rtf包含 \ b ,则表示内容是混合的,否则所选文本中没有粗体文​​本:

In an RTF text, \b indicates start of a bold part of text. So you can first check if richTextBox1.SelectionFont.Bold is true, then it means the text is all bold, otherwise, if the selected rtf contains \b it means the content is mixes, otherwise there is no bold text in selected text:

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 :

To test the solution, it's enough to initialize the RichtextBox with such value:

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}";

这篇关于检查Richtextbox上的选定文本是否全部为粗体或混合字体[C#]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆