'How to search a word in a RichTextBox having specific format?
I have a RichTextBox where the user will copy-paste from MS Word an MCQ quiz question.
The correct choice would either be highlighted or with bold
text (e.g. in the image it is highlighted).
So, I need to check which option is correct by searching for that specific format (the correct choice doesn't always sit on a fixed place so it could be any one from the 4 options).
What I tried:
- the
Find()
method (doesn't help since it deals with text not the format) - get the format of each word, but I don't really have a clue where should I try more harder.
Solution 1:[1]
Just a suggestion, based on the specifics you're describing here.
When you paste text, the RTB's SelectionFont
property can tell you whether the Font uses FontStyle.Bold
.
If the text is highlighted (the selection's background color is not the same as the Control's background color), the SelectionBackColor
property can return this value.
Note that the style of a whole line is evaluated. If the style is applied to a partial section of text in a line, you'll have to change the code accordingly.
You could also use the Lines[]
property; I usually avoid that property, though in this context it wouldn't affect the performance in any way). Change the code as you prefer.
In the example, the code is reading each line of text, creates a selection and asks the Control to clarify whether the text in the selection uses a Bold FontStyle and what is its Background Color.
The result is printed to the Output Window, but you could use, e.g., a Dictionary<int, [Enum]>
(where the enumerator could be Regular
, Bold
, Highlighted
, BoldHighlighted
etc.) and the Key is the line number.
Or List<class>
or whatever you see fit to store this information.
Assume the RichTextBox Control is named rtbLines
:
int currentLine = 0;
int textLength = rtbLines.TextLength;
int selStart = rtbLines.SelectionStart;
while (true) {
int lineFirstChar = rtbLines.GetFirstCharIndexFromLine(currentLine);
if (lineFirstChar < 0) break;
int nextLineFirstChar = rtbLines.GetFirstCharIndexFromLine(currentLine + 1);
int selLength = nextLineFirstChar >= 0
? nextLineFirstChar - lineFirstChar - 2 // Last char of the current line
: textLength - lineFirstChar; // Last line
if (selLength > 0) {
rtbLines.SelectionStart = lineFirstChar;
rtbLines.SelectionLength = selLength;
bool fontBold = rtbLines.SelectionFont.Style.HasFlag(FontStyle.Bold);
bool highLighted = rtbLines.SelectionBackColor != rtbLines.BackColor;
Console.WriteLine($"Line: {currentLine} IsBold: {fontBold} IsHighlighted: {highLighted}");
}
currentLine++;
}
rtbLines.SelectionStart = selStart;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |