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

编程入门 行业动态 更新时间:2024-10-11 13:22:04
本文介绍了检查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#]

本文发布于:2023-11-10 14:32:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575636.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:粗体   文本   字体   Richtextbox

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!