Highlight specific text in richtextbox

前端 未结 2 792
Happy的楠姐
Happy的楠姐 2020-12-22 08:01

I have a window form that contain a listbox and some richtextboxex. listbox contains some values. When I select any value from l

相关标签:
2条回答
  • 2020-12-22 08:54

    Something like this should work (just tested this.. seems to work fine):

    int openBrace = richTextBox.Text.IndexOf("<");
    while (openBrace > -1) {
        int endBrace = richTextBox.Text.IndexOf(">", openBrace);
        if (endBrace > -1) {
            richTextBox.SelectionStart = openBrace;
            richTextBox.SelectionLength = endBrace - openBrace;
            richTextBox.SelectionColor = Color.Blue;
        }
        openBrace = richTextBox.Text.IndexOf("<", openBrace + 1);
    }
    
    0 讨论(0)
  • 2020-12-22 09:08

    One way to do that without casting to new object with functionality you want is to override ListBox DrawItem

    void listBox1_DrawItem(object sender, DrawItemEventArgs e)
    {
        var item = listBox1.Items[e.Index] as <Your_Item>;
    
        e.DrawBackground();
        if (item.fIsTemplate)
        {
            e.Graphics.DrawString(item.Text + "(Default)", new Font("Microsoft Sans Serif", 8, FontStyle.Regular), Brushes.Black, e.Bounds);
        }
        else
        {
            e.Graphics.DrawString(item.Text, new Font("Microsoft Sans Serif", 8, FontStyle.Regular), Brushes.Black, e.Bounds);
        }
        e.DrawFocusRectangle();
    }
    

    and add this in your constructor (after InitializeComponent(); call)

    listBox1.DrawMode = DrawMode.OwnerDrawFixed;
    listBox1.DrawItem += new DrawItemEventHandler(listBox1_DrawItem);
    
    0 讨论(0)
提交回复
热议问题