我有一個 RichTextBox,用戶將從 MS Word 復制粘貼一個 MCQ 測驗問題。
正確的選擇將被突出顯示或使用粗體文本(例如在影像中突出顯示)。
因此,我需要通過搜索該特定格式來檢查哪個選項是正確的(正確的選擇并不總是位于固定的位置,因此它可能是 4 個選項中的任何一個)。

我嘗試了什么:
- 該
Find()方法(沒有幫助,因為它處理文本而不是格式) - 獲取每個單詞的格式,但我真的不知道應該在哪里更加努力。
uj5u.com熱心網友回復:
只是一個建議,基于您在此處描述的具體情況。
當您粘貼文本時,RTB 的SelectionFont屬性可以告訴您字體是否使用FontStyle.Bold.
如果文本被突出顯示(選擇的背景顏色與控制元件的背景顏色不同),該SelectionBackColor屬性可以回傳此值。
請注意,評估整行的樣式。如果樣式應用于一行中的部分文本,則必須相應地更改代碼。
您也可以使用該Lines[]物業;我通常會避免使用該屬性,盡管在這種情況下它不會以任何方式影響性能)。根據需要更改代碼。
在示例中,代碼正在讀取每一行文本,創建一個選擇并要求控制元件澄清選擇中的文本是否使用粗體字體樣式以及它的背景顏色是什么。
結果將列印到輸出視窗,但您可以使用例如 a Dictionary<int, [Enum]>(其中列舉數可以是Regular、Bold、Highlighted等BoldHighlighted)并且 Key 是行號。
或者List<class>任何你認為適合存盤這些資訊的東西。
假設 RichTextBox 控制元件名為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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/475060.html
