C
C#3y ago
HimmDawg

Replacing font table in RichTextBox (WinForms)

I'm working on a .NET Framework 4.8 app that uses WinForms and in there, RichTextBox is used. The app has a list of supported fonts, so we made an algorithm that sorts out unknown fonts when you type or paste text with fonts that are not on the list. If an unknown font ist detected every character having an unknown font will be set to a default font from that list. Now, somebody copied a text from a pdf and pasted it into a richtext box. The fonts in the table are Times New Roman, TimesNewRoman, TimesNewRoman,Bold. So the algorithm (correctly) detects TimesNewRoman, TimesNewRoman,Bold as unknown and tries to replace those. But in reality, it didn't do anything because the text didn't contain characters with one of those two fonts, thus leaving the two unknown fonts in the fonttable. I collected the fonts actually contained in the text with
IEnumerable<string> actualFonts = new List<string>();

for (int i = 0; i < riText.TextLength; i++)
{
riText.Select(i, 1);
actualFonts.Add(riText.SelectionFont.FontFamily.Name);
}
IEnumerable<string> actualFonts = new List<string>();

for (int i = 0; i < riText.TextLength; i++)
{
riText.Select(i, 1);
actualFonts.Add(riText.SelectionFont.FontFamily.Name);
}
...and in there, I got 3x Microsoft Sans Serif (different font sizes) and 2x Times New Roman (different font sizes). I'm a bit lost here. Manually replacing the fonttable doesn't work. What can I do?
1 Reply
HimmDawg
HimmDawgOP3y ago
So just for future references: I found a hack to solve this problem. I just made a new RichTextBox in the code-behind and appended the old text character by character. I also transferred the font of each character into the new RichtextBox. The resulting rtf was exactly what i needed, so I took that and assigned it to the RichTextBox on the form

Did you find this page helpful?