Label 控件本身不支持多种颜色,但RichTextBox 控件支持!您可以将其属性设置为看起来像一个标签。
例如,让它看起来像一个标签:
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(); };
}
然后是通过设置选择开始和长度并更改所选颜色来突出显示搜索词的方法:
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;
}
为了测试和显示用法,我在表单中添加了一个txtSearch 文本框控件,并在TextChanged 事件中调用上述方法。运行表单,然后在文本框中输入以查看结果:
private void txtSearch_TextChanged(object sender, EventArgs e)
{
HighlightSearchText(txtSearch.Text, richTextBox1);
}