Good morning, I need to have the lines defined with the words "moved" stand out in green and the rest in red in the listbox. Here is my font painting method.

Private void DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e) { Brush mybrush = Brushes.Green; Brush mybrush2 = Brushes.Red; e.Graphics.DrawString(listbox1.items[e.Index].ToString(),e.Font, mybrush , e.Bounds, StringFormat.GenericDefault); } 

At the moment, everything is repainted in green, but it is necessary that only certain lines are colored. How can I do that? And yes, I use WinFoms.

    2 answers 2

    Put the DrawMode property of ListBox equal to OwnerDrawFixed and code, something like

      private void listBox1_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); string text = ((ListBox)sender).Items[e.Index].ToString(); Color color = Color.White; if (text == "перемещен") color = Color.Green; e.Graphics.FillRectangle(new SolidBrush(color), e.Bounds); e.Graphics.DrawString(text, e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault); e.DrawFocusRectangle(); } 

    hang on dravitem

    It turned out so

    • Well, respectively, Color.Red, if necessary. Just cut my eyes, put white. - xSx
    • There is another question, but if in the line of this type the entry "file.xx is moved", what would this line with the content of the word "moved" be colored? - Jeron
    • Everything solved the problem itself. - Jeron

    If I'm not mistaken, then you need to set the DrawMode ( MSDN ) property of ListBox equal to OwnerDrawVariable . Then create a handler for the DrawItem event and in this handler paint:

     private void lstBox_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e) { // Перерисовываем фон всех элементов ListBox. e.DrawBackground(); // Создаем объект Brush. Brush myBrush = Brushes.Black; // Определяем номер текущего элемента switch (e.Index) { case 0: myBrush = Brushes.Red; break; case 1: myBrush = Brushes.Green; break; case 2: myBrush = Brushes.Blue; break; default: myBrush = Brushes.Yellow; break; } //Если необходимо, закрашиваем фон //активного элемента в новый цвет //e.Graphics.FillRectangle(myBrush, e.Bounds); // Перерисовываем текст текущего элемента e.Graphics.DrawString( ((ListBox)sender).Items[e.Index].ToString(), e.Font, myBrush, e.Bounds, StringFormat.GenericDefault); // Если ListBox в фокусе, рисуем прямоугольник //вокруг активного элемента. e.DrawFocusRectangle(); } 
    • I did all this and paints everything ... The problem is that you need it to color certain lines, i.e. those lines in which the word "moved" is present. - Jeron
    • So in the code, see the switch and replace the choice from 1,2,3 to check the condition there is in the line the word "moved" or not. - BlackWitcher