Making Specific Text Boldefaced in a Textbox

Making specific Text Boldefaced in a TextBox

use a RichTextBox, below a method that i have wrote for this problem - hope it helps ;-)

/// <summary>
/// This method highlights the assigned text with the specified color.
/// </summary>
/// <param name="textToMark">The text to be marked.</param>
/// <param name="color">The new Backgroundcolor.</param>
/// <param name="richTextBox">The RichTextBox.</param>
/// <param name="startIndex">The zero-based starting caracter position.</param>
public static void ChangeTextcolor(string textToMark, Color color, RichTextBox richTextBox, int startIndex)
{
if (startIndex < 0 || startIndex > textToMark.Length-1) startIndex = 0;

System.Drawing.Font newFont = new Font("Verdana", 10f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 178, false);
try
{
foreach (string line in richTextBox.Lines)
{
if (line.Contains(textToMark))
{
richTextBox.Select(startIndex, line.Length);
richTextBox.SelectionBackColor = color;
}
startIndex += line.Length +1;
}
}
catch
{ }
}

Set specific text to bold in WPF RichTextBox

After several tests, I figured out a simple solution.

CaretPosition = CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward);

This set caret in the right orientation, preventing the BOLD setting from continuing within the Run object.

if(textPointerEnd.GetNextInsertionPosition(LogicalDirection.Forward) == null)
new Run("", textPointerEnd);

This would add a Run object to the end of a new Bold object that was located at the end of the Paragraph object.

Change font style to richtextbox

You need to set Bold in FontWeight-property:

sp.FontWeight = FontWeights.Bold;

Same in WinForms:

sp.Font = new Font(sp.Font.Name, sp.Font.Size, FontStyle.Bold); 


Related Topics



Leave a reply



Submit