The Label
control doesn't natively support multiple colors, but the RichTextBox
control does! And you can set it's properties to look like a label.
For example, to make it look like a label:
private void Form1_Load(object sender, EventArgs e)
{
// Make the RichTextBox look and behave like a Label control
richTextBox1.BorderStyle = BorderStyle.None;
richTextBox1.BackColor = System.Drawing.SystemColors.Control;
richTextBox1.ReadOnly = true;
richTextBox1.Text = "Hipopotamus";
// I added a small, blank Label control to the form which I use to capture the Focus
// from this control, so the user can't see the caret or select/highlight/edit text
richTextBox1.GotFocus += (s, ea) => { lblHidden.Focus(); };
}
Then a method to highlight a search term by setting selection start and length and changing selected colors:
private void HighlightSearchText(string searchText, RichTextBox control)
{
// Make all text black first
control.SelectionStart = 0;
control.SelectionLength = control.Text.Length;
control.SelectionColor = System.Drawing.SystemColors.ControlText;
// Return if search text isn't found
var selStart = control.Text.IndexOf(searchText);
if (selStart < 0 || searchText.Length == 0) return;
// Otherwise, highlight the search text
control.SelectionStart = selStart;
control.SelectionLength = searchText.Length;
control.SelectionColor = Color.Red;
}
For a test and to show usage, I added a txtSearch
textbox control to the form and call the method above in the TextChanged
event. Run the form, and type into the textbox to see the results:
private void txtSearch_TextChanged(object sender, EventArgs e)
{
HighlightSearchText(txtSearch.Text, richTextBox1);
}