C listbox как изменить цвет

It seems to use default color from Windows settings which is blue by default. Let's say I want to change it to red permanently. I'm using Winforms. Thanks in advance.

It seems to use default color from Windows settings which is blue by default.
Let’s say I want to change it to red permanently. I’m using Winforms.

Thanks in advance.

RRUZ's user avatar

RRUZ

134k19 gold badges355 silver badges482 bronze badges

asked Sep 8, 2010 at 0:25

Qosmo's user avatar

You must override the Drawitem event and set the DrawMode property to DrawMode.OwnerDrawFixed

check this sample

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    if (e.Index<0) return;
    //if the item state is selected them change the back color 
    if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
        e = new DrawItemEventArgs(e.Graphics, 
                                  e.Font, 
                                  e.Bounds, 
                                  e.Index,
                                  e.State ^ DrawItemState.Selected,
                                  e.ForeColor, 
                                  Color.Yellow);//Choose the color

    // Draw the background of the ListBox control for each item.
    e.DrawBackground();
    // Draw the current item text
    e.Graphics.DrawString(listBox1.Items[e.Index].ToString(),e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
    // If the ListBox has focus, draw a focus rectangle around the selected item.
    e.DrawFocusRectangle();
}

alt text

answered Sep 8, 2010 at 0:55

RRUZ's user avatar

RRUZRRUZ

134k19 gold badges355 silver badges482 bronze badges

6

Hopefully this will help someone in the future as the above code helped me but not 100%

I still had the following problems:
— when i selected another index, the newly selected index would also highlight red.
— when i changed the font size of the listbox, the highlighted area would be to small.

Below fixes that problem

  • change the DrawMode to ownerdrawvariable
  • create a MeasurItem and DrawItem event for the listbox
private void lstCartOutput_MeasureItem(object sender, MeasureItemEventArgs e)
{
   // Cast the sender object back to ListBox type.
   ListBox listBox = (ListBox)sender;
   e.ItemHeight = listBox.Font.Height;
}

private void lstCartOutput_DrawItem(object sender, DrawItemEventArgs e)
{
   ListBox listBox = (ListBox)sender;
   e.DrawBackground();
   Brush myBrush = Brushes.Black;

   if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
   {
      myBrush = Brushes.Red;
      e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(0, 64, 64)), e.Bounds);
   }

   else
   {
      e.Graphics.FillRectangle(Brushes.White, e.Bounds);

   }

   e.Graphics.DrawString(listBox.Items[e.Index].ToString(),e.Font, myBrush, e.Bounds);
   e.DrawFocusRectangle();
}

I also referenced the MSDN website.

Brian's user avatar

Brian

5,0497 gold badges37 silver badges47 bronze badges

answered Jan 8, 2012 at 18:15

B Nasty's user avatar

B NastyB Nasty

611 silver badge2 bronze badges

0

The below code does exactly what you are saying:

In the InitializeComponent method:

this.listBox1.DrawMode = DrawMode.OwnerDrawFixed;
this.listBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(listBox1_DrawItem);
this.listBox1.SelectedIndexChanged += new System.EventHandler(listBox1_SelectedIndexChanged);

And the event handlers:

void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
    this.listBox1.Invalidate();
}

void listBox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
    int index = e.Index;
    Graphics g = e.Graphics;
    foreach (int selectedIndex in this.listBox1.SelectedIndices)
    {
        if (index == selectedIndex)
        {
            // Draw the new background colour
            e.DrawBackground();
            g.FillRectangle(new SolidBrush(Color.Red), e.Bounds);
        }
    }

    // Get the item details
    Font font = listBox1.Font;
    Color colour = listBox1.ForeColor;
    string text = listBox1.Items[index].ToString();

    // Print the text
    g.DrawString(text, font, new SolidBrush(Color.Black), (float)e.Bounds.X, (float)e.Bounds.Y);
    e.DrawFocusRectangle();
}

Code is taken from:

http://www.weask.us/entry/change-listbox-rsquo-selected-item-backcolor-net

answered Sep 8, 2010 at 0:41

Musa Hafalır's user avatar

Musa HafalırMusa Hafalır

1,7521 gold badge15 silver badges23 bronze badges

1

Why use ListBox in the first place and not replace it with a single-column, no-headers-visible, read-only DataGridView, which is fully customisable?

answered Aug 2, 2020 at 17:07

Panos Roditakis's user avatar

I have the same problem.

Unfortunately my datasource is a List of Entity Class. So I have the same code with the accepted answer above but with minor modification to select the exact property on my Class that I need on DrawString for my ListBox:

 if (e.Index < 0) return;
        if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            e = new DrawItemEventArgs(e.Graphics,
                                      e.Font,
                                      e.Bounds,
                                      e.Index,
                                      e.State ^ DrawItemState.Selected,
                                      e.ForeColor,
                                      Color.Yellow);

  e.DrawBackground();
  //This is my modification below:
  e.Graphics.DrawString(ctListViewProcess.Items.Cast<entMyEntity>().Select(c => c.strPropertyName).ElementAt(e.Index), e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
  e.DrawFocusRectangle();

answered Jul 28, 2017 at 2:47

Willy David Jr's user avatar

Willy David JrWilly David Jr

8,3585 gold badges44 silver badges55 bronze badges

It seems to use default color from Windows settings which is blue by default.
Let’s say I want to change it to red permanently. I’m using Winforms.

Thanks in advance.

RRUZ's user avatar

RRUZ

134k19 gold badges355 silver badges482 bronze badges

asked Sep 8, 2010 at 0:25

Qosmo's user avatar

You must override the Drawitem event and set the DrawMode property to DrawMode.OwnerDrawFixed

check this sample

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    if (e.Index<0) return;
    //if the item state is selected them change the back color 
    if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
        e = new DrawItemEventArgs(e.Graphics, 
                                  e.Font, 
                                  e.Bounds, 
                                  e.Index,
                                  e.State ^ DrawItemState.Selected,
                                  e.ForeColor, 
                                  Color.Yellow);//Choose the color

    // Draw the background of the ListBox control for each item.
    e.DrawBackground();
    // Draw the current item text
    e.Graphics.DrawString(listBox1.Items[e.Index].ToString(),e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
    // If the ListBox has focus, draw a focus rectangle around the selected item.
    e.DrawFocusRectangle();
}

alt text

answered Sep 8, 2010 at 0:55

RRUZ's user avatar

RRUZRRUZ

134k19 gold badges355 silver badges482 bronze badges

6

Hopefully this will help someone in the future as the above code helped me but not 100%

I still had the following problems:
— when i selected another index, the newly selected index would also highlight red.
— when i changed the font size of the listbox, the highlighted area would be to small.

Below fixes that problem

  • change the DrawMode to ownerdrawvariable
  • create a MeasurItem and DrawItem event for the listbox
private void lstCartOutput_MeasureItem(object sender, MeasureItemEventArgs e)
{
   // Cast the sender object back to ListBox type.
   ListBox listBox = (ListBox)sender;
   e.ItemHeight = listBox.Font.Height;
}

private void lstCartOutput_DrawItem(object sender, DrawItemEventArgs e)
{
   ListBox listBox = (ListBox)sender;
   e.DrawBackground();
   Brush myBrush = Brushes.Black;

   if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
   {
      myBrush = Brushes.Red;
      e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(0, 64, 64)), e.Bounds);
   }

   else
   {
      e.Graphics.FillRectangle(Brushes.White, e.Bounds);

   }

   e.Graphics.DrawString(listBox.Items[e.Index].ToString(),e.Font, myBrush, e.Bounds);
   e.DrawFocusRectangle();
}

I also referenced the MSDN website.

Brian's user avatar

Brian

5,0497 gold badges37 silver badges47 bronze badges

answered Jan 8, 2012 at 18:15

B Nasty's user avatar

B NastyB Nasty

611 silver badge2 bronze badges

0

The below code does exactly what you are saying:

In the InitializeComponent method:

this.listBox1.DrawMode = DrawMode.OwnerDrawFixed;
this.listBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(listBox1_DrawItem);
this.listBox1.SelectedIndexChanged += new System.EventHandler(listBox1_SelectedIndexChanged);

And the event handlers:

void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
    this.listBox1.Invalidate();
}

void listBox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
    int index = e.Index;
    Graphics g = e.Graphics;
    foreach (int selectedIndex in this.listBox1.SelectedIndices)
    {
        if (index == selectedIndex)
        {
            // Draw the new background colour
            e.DrawBackground();
            g.FillRectangle(new SolidBrush(Color.Red), e.Bounds);
        }
    }

    // Get the item details
    Font font = listBox1.Font;
    Color colour = listBox1.ForeColor;
    string text = listBox1.Items[index].ToString();

    // Print the text
    g.DrawString(text, font, new SolidBrush(Color.Black), (float)e.Bounds.X, (float)e.Bounds.Y);
    e.DrawFocusRectangle();
}

Code is taken from:

http://www.weask.us/entry/change-listbox-rsquo-selected-item-backcolor-net

answered Sep 8, 2010 at 0:41

Musa Hafalır's user avatar

Musa HafalırMusa Hafalır

1,7521 gold badge15 silver badges23 bronze badges

1

Why use ListBox in the first place and not replace it with a single-column, no-headers-visible, read-only DataGridView, which is fully customisable?

answered Aug 2, 2020 at 17:07

Panos Roditakis's user avatar

I have the same problem.

Unfortunately my datasource is a List of Entity Class. So I have the same code with the accepted answer above but with minor modification to select the exact property on my Class that I need on DrawString for my ListBox:

 if (e.Index < 0) return;
        if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            e = new DrawItemEventArgs(e.Graphics,
                                      e.Font,
                                      e.Bounds,
                                      e.Index,
                                      e.State ^ DrawItemState.Selected,
                                      e.ForeColor,
                                      Color.Yellow);

  e.DrawBackground();
  //This is my modification below:
  e.Graphics.DrawString(ctListViewProcess.Items.Cast<entMyEntity>().Select(c => c.strPropertyName).ElementAt(e.Index), e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
  e.DrawFocusRectangle();

answered Jul 28, 2017 at 2:47

Willy David Jr's user avatar

Willy David JrWilly David Jr

8,3585 gold badges44 silver badges55 bronze badges

It seems to use default color from Windows settings which is blue by default.
Let’s say I want to change it to red permanently. I’m using Winforms.

Thanks in advance.

RRUZ's user avatar

RRUZ

134k19 gold badges355 silver badges482 bronze badges

asked Sep 8, 2010 at 0:25

Qosmo's user avatar

You must override the Drawitem event and set the DrawMode property to DrawMode.OwnerDrawFixed

check this sample

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    if (e.Index<0) return;
    //if the item state is selected them change the back color 
    if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
        e = new DrawItemEventArgs(e.Graphics, 
                                  e.Font, 
                                  e.Bounds, 
                                  e.Index,
                                  e.State ^ DrawItemState.Selected,
                                  e.ForeColor, 
                                  Color.Yellow);//Choose the color

    // Draw the background of the ListBox control for each item.
    e.DrawBackground();
    // Draw the current item text
    e.Graphics.DrawString(listBox1.Items[e.Index].ToString(),e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
    // If the ListBox has focus, draw a focus rectangle around the selected item.
    e.DrawFocusRectangle();
}

alt text

answered Sep 8, 2010 at 0:55

RRUZ's user avatar

RRUZRRUZ

134k19 gold badges355 silver badges482 bronze badges

6

Hopefully this will help someone in the future as the above code helped me but not 100%

I still had the following problems:
— when i selected another index, the newly selected index would also highlight red.
— when i changed the font size of the listbox, the highlighted area would be to small.

Below fixes that problem

  • change the DrawMode to ownerdrawvariable
  • create a MeasurItem and DrawItem event for the listbox
private void lstCartOutput_MeasureItem(object sender, MeasureItemEventArgs e)
{
   // Cast the sender object back to ListBox type.
   ListBox listBox = (ListBox)sender;
   e.ItemHeight = listBox.Font.Height;
}

private void lstCartOutput_DrawItem(object sender, DrawItemEventArgs e)
{
   ListBox listBox = (ListBox)sender;
   e.DrawBackground();
   Brush myBrush = Brushes.Black;

   if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
   {
      myBrush = Brushes.Red;
      e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(0, 64, 64)), e.Bounds);
   }

   else
   {
      e.Graphics.FillRectangle(Brushes.White, e.Bounds);

   }

   e.Graphics.DrawString(listBox.Items[e.Index].ToString(),e.Font, myBrush, e.Bounds);
   e.DrawFocusRectangle();
}

I also referenced the MSDN website.

Brian's user avatar

Brian

5,0497 gold badges37 silver badges47 bronze badges

answered Jan 8, 2012 at 18:15

B Nasty's user avatar

B NastyB Nasty

611 silver badge2 bronze badges

0

The below code does exactly what you are saying:

In the InitializeComponent method:

this.listBox1.DrawMode = DrawMode.OwnerDrawFixed;
this.listBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(listBox1_DrawItem);
this.listBox1.SelectedIndexChanged += new System.EventHandler(listBox1_SelectedIndexChanged);

And the event handlers:

void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
    this.listBox1.Invalidate();
}

void listBox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
    int index = e.Index;
    Graphics g = e.Graphics;
    foreach (int selectedIndex in this.listBox1.SelectedIndices)
    {
        if (index == selectedIndex)
        {
            // Draw the new background colour
            e.DrawBackground();
            g.FillRectangle(new SolidBrush(Color.Red), e.Bounds);
        }
    }

    // Get the item details
    Font font = listBox1.Font;
    Color colour = listBox1.ForeColor;
    string text = listBox1.Items[index].ToString();

    // Print the text
    g.DrawString(text, font, new SolidBrush(Color.Black), (float)e.Bounds.X, (float)e.Bounds.Y);
    e.DrawFocusRectangle();
}

Code is taken from:

http://www.weask.us/entry/change-listbox-rsquo-selected-item-backcolor-net

answered Sep 8, 2010 at 0:41

Musa Hafalır's user avatar

Musa HafalırMusa Hafalır

1,7521 gold badge15 silver badges23 bronze badges

1

Why use ListBox in the first place and not replace it with a single-column, no-headers-visible, read-only DataGridView, which is fully customisable?

answered Aug 2, 2020 at 17:07

Panos Roditakis's user avatar

I have the same problem.

Unfortunately my datasource is a List of Entity Class. So I have the same code with the accepted answer above but with minor modification to select the exact property on my Class that I need on DrawString for my ListBox:

 if (e.Index < 0) return;
        if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            e = new DrawItemEventArgs(e.Graphics,
                                      e.Font,
                                      e.Bounds,
                                      e.Index,
                                      e.State ^ DrawItemState.Selected,
                                      e.ForeColor,
                                      Color.Yellow);

  e.DrawBackground();
  //This is my modification below:
  e.Graphics.DrawString(ctListViewProcess.Items.Cast<entMyEntity>().Select(c => c.strPropertyName).ElementAt(e.Index), e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
  e.DrawFocusRectangle();

answered Jul 28, 2017 at 2:47

Willy David Jr's user avatar

Willy David JrWilly David Jr

8,3585 gold badges44 silver badges55 bronze badges

  • Remove From My Forums
  • Question

  • How to add items with different color in ListBox control?This code for example change the colors of all items in the ListBox.
    Obviously i do not want that.

    Code Block

    this.listBox1.DrawItem += new DrawItemEventHandler(this.DrawItemHandler);

       private void DrawItemHandler(object sender, DrawItemEventArgs e)
            {
                e.DrawBackground();
                e.DrawFocusRectangle();
                e.Graphics.DrawString(someString,
                                      new Font(FontFamily.GenericSansSerif,
                                               8, FontStyle.Bold),
                                               new SolidBrush(tColor),e.Bounds);
            }

    How to achieve what i want?AFAIK i should remove e.Bounds and play with e.Index or something…but don’t know what to do exactly.Thanks in advance.

Answers

  • Hi cygnusx,

    To set different color for each item in the ListBox, please check the following sample.

    Code Block

    namespace ListBox

    {

        public partial class ColoredLB : Form

        {

            public ColoredLB()

            {

                InitializeComponent();

            }

            private void ColoredLB_Load(object sender, EventArgs e)

            {

                this.listBox1.Items.AddRange(new object[] { «Red», «Blue», «Yellow»,«Other Color» });

                this.listBox1.DrawMode = DrawMode.OwnerDrawVariable;

                this.listBox1.DrawItem += new DrawItemEventHandler(listBox1_DrawItem);

            }

            void listBox1_DrawItem(object sender, DrawItemEventArgs e)

            {

                e.DrawBackground();

                e.DrawFocusRectangle();

                Color c = Color.Pink;

                if (this.listBox1.Items[e.Index].ToString() == «Red»)

                    c = Color.Red;

                else if (this.listBox1.Items[e.Index].ToString() == «Blue»)

                    c = Color.Blue;

                else if (this.listBox1.Items[e.Index].ToString() == «Yellow»)

                    c = Color.Yellow;

                e.Graphics.DrawString(this.listBox1.Items[e.Index].ToString(), new Font(FontFamily.GenericSansSerif, 8, FontStyle.Bold), new SolidBrush(c), e.Bounds);

            }

        }

    }

    Hope this helps.
    Best regards.
    Rong-Chun Zhang

0 / 0 / 2

Регистрация: 16.06.2016

Сообщений: 87

1

03.12.2016, 17:06. Показов 5000. Ответов 6


Как при добавлении элемента в коллекцию ListBox установить ему цвет, т.е элементы должны быть разных цветов

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



edward_freedom

1568 / 1447 / 303

Регистрация: 01.10.2011

Сообщений: 2,636

03.12.2016, 17:24

2

Александр1906,

XML
1
 <ListBox Name="ListBox1"> </ListBox>
C#
1
2
3
ListBox1.Items.Add(new ListBoxItem(){Content = "test1", Background = Brushes.Aqua});
            ListBox1.Items.Add(new ListBoxItem() { Content = "test2", Background = Brushes.Red });
            ListBox1.Items.Add(new ListBoxItem() { Content = "test1", Background = Brushes.Green });

Миниатюры

Цвет элементов ListBox
 



1



0 / 0 / 2

Регистрация: 16.06.2016

Сообщений: 87

03.12.2016, 18:33

 [ТС]

3

а где нужно писать верхню строчку <ListBox Name=»ListBox1″> </ListBox>

Добавлено через 51 минуту
какая сборка должна быть?



0



71 / 68 / 46

Регистрация: 02.12.2015

Сообщений: 890

Записей в блоге: 1

03.12.2016, 19:04

4

Это WPF, не WindowsForms



0



0 / 0 / 2

Регистрация: 16.06.2016

Сообщений: 87

03.12.2016, 19:13

 [ТС]

5

Ошибку пишет Ошибка 1 Неявное преобразование типа «System.Drawing.Brush» в «System.Windows.Media.Brush» невозможно C:ставкипрогиАнализАнализForm1.cs 62 100 Анализ

Добавлено через 47 секунд
а как в сделать
WindowsForms ?



0



aleksskay4

71 / 68 / 46

Регистрация: 02.12.2015

Сообщений: 890

Записей в блоге: 1

03.12.2016, 19:37

6

где то нашел

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
      
        public Form1()
        {
            InitializeComponent();
            listBox1.DrawMode = DrawMode.OwnerDrawVariable;
            listBox1.DataSource =
                new object[] { "1", "2", "3", "4", "5", "6", "7" };
            
        }
 
        private void listBox1_DrawItem(object sender, 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();
 
 
        }
    }
}



0



0 / 0 / 2

Регистрация: 16.06.2016

Сообщений: 87

03.12.2016, 19:41

 [ТС]

7

мне кажется что при добавлении элемента элемента этот код не прокатит, здесь уже обращение происходит к готовой колекции



0



В данной статье мы разберем несколько вариантов изменения цвета элементов Windows Forms на примере фона формы Form1 и прочих компонентов.

Способ №1. Изменение цвета в свойствах элемента.

Для многих это самый легкий способ изменения цветовой палитры элементов, так как не надо писать код, всё визуализировано и интуитивно понятно.

Для этого надо выбрать элемент формы (или саму форму) и в «Свойствах» найти вкладку «Внешний вид». Нас интересует строка BackColor:

Как поменять цвет фона элементов в Windows Forms   Как поменять цвет фона элементов в Windows Forms

Здесь имеется большое количество цветовых схем и их визуальных представлений.

Как поменять цвет фона элементов в Windows Forms

Как поменять цвет фона элементов в Windows Forms

Как поменять цвет фона элементов в Windows Forms

Выберем для примера какой-либо из цветов, чтобы изменить фон формы:

Как поменять цвет фона элементов в Windows Forms

Итог такой:

Как поменять цвет фона элементов в Windows Forms

Легко, незамысловато, понятно.

Следующие способы будут производиться в коде.

Способ №2. Изменение цвета, используя структуру Color.

Это самый простой способ среди кодовых вариаций.

«На пальцах» это выглядит так:

Названиеэлементаформы.BackColor = Color.Название_цвета;

Если мы захотим закрасить фон формы в зеленый цвет, то строка кода будет выглядеть вот так:

public Form1()

        {

            InitializeComponent();

            this.BackColor = Color.Green;          

        }

При запуске форма будет выглядеть так:

Как поменять цвет фона элементов в Windows Forms

Если понадобится изменить цвет, например, кнопки Button на тёмно-бордовый, код будет таким:

button1.BackColor = Color.Maroon;

Данный способ прост тем, что требуется лишь написать название цвета, которых также большое количество.

Зачастую этих двух способов хватает для оформления программы. Если же нужна более гибкая настройка или же среди стандартных цветов не имеется необходимых, можно воспользоваться способами, описанными ниже.

Способ №3. Изменение цвета, используя метод Color.Argb.

Этот и следующий методы позволят генерировать нужный цвет, используя значения цветового канала RGB.

RGB — это цветовая модель, которая синтезирует цвета, используя смешивание трёх основных цветов (Красного — Red, Зеленого — Green, Синего- Blue) с чёрным, вследствие чего получаются новые цвета и оттенки. Зависит получаемый цвет от  интенсивности этих трёх основных цветов. Если смешать Красный, Зеленый и Синий в максимальной насыщенности, получится белый цвет. Если не смешивать их, то остаётся чёрный. Как поменять цвет фона элементов в Windows Forms

Данный способ позволяет регулировать интенсивность трех этих цветов, при смешивании которых и получится нужный нам оттенок.

Интенсивность в числовой форме для удобства применения обозначается от 0 (минимальная интенсивность) до 255(максимальная интенсивность). Все три цвета можно «варьировать» по этой шкале.

Словесно это выглядит вот так:

Названиеэлементаформы.BackColor = Color.FromArgb(Насыщенность красного, Насыщенность зеленого, Насыщенность синего);

Чтобы закрасить фон программы в чёрный цвет, используя данный метод, надо написать вот такую строку:

public Form1()

        {

            InitializeComponent();

            this.BackColor = Color.FromArgb(0, 0, 0);    

        }

На выходе получим:

Как поменять цвет фона элементов в Windows Forms

Можно и поэкспериментировать:

this.BackColor = Color.FromArgb(111, 121, 131);

Как поменять цвет фона элементов в Windows Forms

Если нам понадобится, для примера, изменить фон Listbox’a на красный данных способом, то код у нас будет следующий:

listBox1.BackColor = Color.FromArgb(255, 0, 0);

Данный способ и способ ниже подходят больше для людей, разбирающихся в цветовых моделях, гаммах и числовых значениях цветов.

Способ №4. Изменение цвета, используя метод ColorTranslator.FromHtml

Этот метод также основывается на модели RGB, но записывается она в шестнадцатеричном виде, а именно #RrGgBb. Первые две шестнадцатеричные цифры после решетки обозначают насыщенность Красного, вторые две — насыщенность Зеленого, последние — насыщенность Синего. Минимальная насыщенность здесь — 00, максимальная — FF(В переводе с шестнадцатеричной системы счисления в десятичную это число обозначает 255). Остальной принцип смешивания цветов такой же.

Данный метод создан для языка веб-разметки HTML, но пользуются им повсеместно.

Принцип кода такой:

Названиеэлементаформы.BackColor = ColorTranslator.FromHtml(«#КрЗлГб»);

Для изменения бэкграунда формы в белый код такой:

public Form1()

        {

            InitializeComponent();

            this.BackColor=ColorTranslator.FromHtml(«#FFFFFF»);  

        }

Если понадобится изменить данным способом фон Label’a в коричневый:

label1.BackColor = ColorTranslator.FromHtml(«#A52A2A»);

Мы рассмотрели 4 основных способа изменения цвета фона элементов в Windows Forms. Все они не сложные, разобраться можно в каждом. Каким из них пользоваться — решать только Вам.
Спасибо за просмотр!


This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

Show hidden characters

<Window x:Class=«ListBoxStyle.MainWindow«
xmlns=«http://schemas.microsoft.com/winfx/2006/xaml/presentation«
xmlns:x=«http://schemas.microsoft.com/winfx/2006/xaml«
xmlns:src=«clr-namespace:ListBoxStyle«
Title=«MainWindow« Height=«350« Width=«525«>
<Window.Resources>
<Style x:Key=«_ListBoxItemStyle« TargetType=«ListBoxItem«>
<Setter Property=«Template«>
<Setter.Value>
<ControlTemplate TargetType=«ListBoxItem«>
<Border Name=«_Border«
Padding=«2«
SnapsToDevicePixels=«true«>
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property=«IsSelected« Value=«true«>
<Setter TargetName=«_Border« Property=«Background« Value=«Yellow«/>
<Setter Property=«Foreground« Value=«Red«/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<ListBox ItemContainerStyle=«{DynamicResource _ListBoxItemStyle}«
Width=«200« Height=«250«
ScrollViewer.VerticalScrollBarVisibility=«Auto«
ScrollViewer.HorizontalScrollBarVisibility=«Auto«>
<ListBoxItem>Hello</ListBoxItem>
<ListBoxItem>Hi</ListBoxItem>
</ListBox>
</Grid>
</Window>

5 ответов

Вероятно, единственный способ добиться этого — нарисовать элементы самостоятельно.

Установите DrawMode в OwnerDrawFixed

и введите код такого типа в событие DrawItem:

private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    Graphics g = e.Graphics;

    g.FillRectangle(new SolidBrush(Color.Silver), e.Bounds);

    // Print text

    e.DrawFocusRectangle();
}

Второй вариант будет использовать ListView, хотя у них есть другой способ реализации (на самом деле не связанный с данными, а более гибкий в виде столбцов)

Grad van Horck
18 сен. 2008, в 12:46

Поделиться

Спасибо за ответ от Grad van Horck, он направил меня в правильном направлении.

Чтобы поддерживать текст (а не только цвет фона), вот мой полностью рабочий код:

//global brushes with ordinary/selected colors
private SolidBrush reportsForegroundBrushSelected = new SolidBrush(Color.White);
private SolidBrush reportsForegroundBrush = new SolidBrush(Color.Black);
private SolidBrush reportsBackgroundBrushSelected = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
private SolidBrush reportsBackgroundBrush1 = new SolidBrush(Color.White);
private SolidBrush reportsBackgroundBrush2 = new SolidBrush(Color.Gray);

//custom method to draw the items, don't forget to set DrawMode of the ListBox to OwnerDrawFixed
private void lbReports_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected);

    int index = e.Index;
    if (index >= 0 && index < lbReports.Items.Count)
    {
        string text = lbReports.Items[index].ToString();
        Graphics g = e.Graphics;

        //background:
        SolidBrush backgroundBrush;
        if (selected)
            backgroundBrush = reportsBackgroundBrushSelected;
        else if ((index % 2) == 0)
            backgroundBrush = reportsBackgroundBrush1;
        else
            backgroundBrush = reportsBackgroundBrush2;
        g.FillRectangle(backgroundBrush, e.Bounds);

        //text:
        SolidBrush foregroundBrush = (selected) ? reportsForegroundBrushSelected : reportsForegroundBrush;
        g.DrawString(text, e.Font, foregroundBrush, lbReports.GetItemRectangle(index).Location);
    }

    e.DrawFocusRectangle();
}

Приведенный выше добавляет к данному коду и отображает правильный текст плюс выделение выделенного элемента.

Shadow Wizard
14 сен. 2010, в 15:31

Поделиться

// Set the background to a predefined colour
MyListBox.BackColor = Color.Red;
// OR: Set parts of a color.
MyListBox.BackColor.R = 255;
MyListBox.BackColor.G = 0;
MyListBox.BackColor.B = 0;

Если вы хотите установить несколько цветов фона, установите другой цвет фона для каждого элемента, это невозможно в ListBox, но IS с ListView с чем-то вроде:

// Set the background of the first item in the list
MyListView.Items[0].BackColor = Color.Red;

Matthew Scharley
18 сен. 2008, в 13:25

Поделиться

public MainForm()
{
    InitializeComponent();
    this.listbox1.DrawItem += new DrawItemEventHandler(this.listbox1_DrawItem);
}

private void listbox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
    e.DrawBackground();
    Brush myBrush = Brushes.Black;
    var item = listbox1.Items[e.Index];
    if(e.Index % 2 == 0)
    {
        e.Graphics.FillRectangle(new SolidBrush(Color.Gold), e.Bounds);
    }
        e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(), 
            e.Font, myBrush,e.Bounds, StringFormat.GenericDefault);
        e.DrawFocusRectangle();
    }
}

Serdar Karaca
13 янв. 2017, в 11:12

Поделиться

public Picker()
{
    InitializeComponent();
    this.listBox.DrawMode = DrawMode.OwnerDrawVariable;
    this.listBox.MeasureItem += listBoxMetals_MeasureItem;
    this.listBox.DrawItem += listBoxMetals_DrawItem;
}

void listBoxMetals_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    Brush myBrush = Brushes.Black;
    var item = listBox.Items[e.Index] as Mapping;
    if (e.Index % 2 == 0)
    {
        e.Graphics.FillRectangle(new SolidBrush(Color.GhostWhite), e.Bounds);
    }
    e.Graphics.DrawString(item.Name,
        e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
    e.DrawFocusRectangle();
}

Полный образец

Thulani Chivandikwa
09 июль 2014, в 08:28

Поделиться

Ещё вопросы

  • 1ссылка на библиотеку Android
  • 0Многопоточное приложение CPU CUDA не асинхронно при вызове CudaFree
  • 0как работает bufferedPercent
  • 1Сокет клиент / сервер остановить метод в Java
  • 1Как сделать так, чтобы оси занимали несколько вспомогательных участков при использовании графика даты и времени панд?
  • 0DirectX ошибки Vector3
  • 0дата форматирования от контроллера не получает ожидаемый результат
  • 1Python Tkinter GUI формат грязной печати
  • 0Кендо У.И. Грид, Дюрандаль
  • 0php form — перезагрузить при отправке
  • 1как получить и установить параметры в Camel HTTP Proxy
  • 1Использование классов в цикле for в node.js
  • 0Вставка нового имени в поле mysql с временной таблицей
  • 1Python: получить размер отображаемой веб-страницы
  • 1Проблема с многопоточностью при подключении к нескольким устройствам одновременно
  • 0.hover () с jQuery работает только один раз
  • 1Обмен сообщениями и электронной почтой в Android?
  • 0jQuery: получить оригинальный селектор в функции члена плагина
  • 1Добавить разбор функции в простой разбор с нечисловыми аргументами
  • 0PayPal периодические платежи с одноразовыми платежами
  • 0ассоциативный массив установлен неправильно
  • 0SELECT * FROM tableName WHERE ‘num + sometext’
  • 0Как я могу реализовать производителя-потребителя, где потребитель может запросить свежие данные
  • 0Безопасное встраивание строки в C-код (Безопасная строка, Безопасный символ *)
  • 0ExpressJS + AngularJS одна страница без шаблона страница не найдена (404)
  • 0Выбор варианта с заданным значением
  • 0JQuery: предотвращение запуска функции до тех пор, пока другая функция не будет выполнена условно за «X» промежуток времени
  • 0AngularJS Получить отфильтрованный объем onClick
  • 0Сервер WAMP не позволяет загружать файлы (PHP application)
  • 0Как узнать, доступен ли уровень отладки dx?
  • 0Как получить обложку альбома из музыкального файла с помощью PHP?
  • 0Запустите проект Playn HTML в Remote
  • 1Элементы списка в файл данных c #
  • 0Firefox семейства шрифтов дочерние элементы не наследуют, в то время как Chrome работает правильно
  • 1Как Spring boot / Application.java может собрать Mongo AbstractMongoConfiguration в другой пакет?
  • 0Как получить доступ к имени пользователя из ng-repeat
  • 0Проверьте, находится ли дата в определенном диапазоне дат PHP [дубликаты]
  • 0prevAll () и фильтр по дочернему присутствию
  • 0SOAP возвращает ошибку «значение не может быть недействительным. Параметр имя документа »
  • 1Войти в Jabber-сеть
  • 0Как сделать так, чтобы основной тег div получал большую высоту, если содержимое добавлено в два плавающих элемента div (#content и #sidebar)?
  • 0ионное содержимое с прокруткой
  • 0IE / Edge рендеринг SVG-элементов с директивой Angular
  • 0Отправить название столбца с кнопки
  • 0Неразрешенные внешние проблемы, Неразрешенные внешние символы LNK 1120
  • 1Google Guice: помогите ввести
  • 1Android VideoView не воспроизводит пример видео на T-Mobile G2 (только аудио)
  • 1javascript ответ загрузки XMLHttpRequest после ответа сервера
  • 0Массивы не публикуются в php
  • 0Почему минимальный проект MFC имеет ошибку компоновки в Visual Studio 2013?

Понравилась статья? Поделить с друзьями:
  • C error e2075 incorrect project override option files
  • C error c2280
  • C error c2079
  • C error 4996
  • C duplicate symbol error