Windows forms control color

ForeColor, BackColor. Windows Forms can have colors. The ForeColor property adjusts the text color and some borders on controls. The BackColor property meanwhile adjusts the background of controls. These two properties are available on many control instances.

To begin, you can add a Button control to your Windows Forms project by double-clicking on the Button element in the Toolbox. Next, right-click on the button and select Properties. After this, please scroll down to the ForeColor entry.

Tip: In Visual Studio, you can set the default ForeColor for the control. During execution, you can adjust the ForeColor with C# code.

You can also modify the BackColor property in the C# code of your project. Please assign the property «this.BackColor» to a Color instance. Also, other controls, not just forms, have BackColor properties that are equivalent in meaning.

Tip: The BackColor property in Windows Forms provides a mechanism for mutating the background color of a window or control.

Typically: Using a system value for the background is best, as it will ensure that foreground elements are visible upon the background.

Summary. We examined the ForeColor and BackColor properties in Windows Forms. When you set one of these properties, it is often a good idea to set the other. This prevents illegible combinations: white text on a white background, for example.

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

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

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

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

   

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

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

Итог такой:

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

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

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

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

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

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

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

public Form1()

        {

            InitializeComponent();

            this.BackColor = Color.Green;          

        }

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

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

button1.BackColor = Color.Maroon;

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

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

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

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

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

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

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

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

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

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

public Form1()

        {

            InitializeComponent();

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

        }

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

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

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

Если нам понадобится, для примера, изменить фон 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. Все они не сложные, разобраться можно в каждом. Каким из них пользоваться — решать только Вам.
Спасибо за просмотр!

Last Updated :
30 Jun, 2019

In Windows Forms, Label control is used to display text on the form and it does not take part in user input or in mouse or keyboard events. You are allowed to set the foreground color of the Label control using the ForeColor Property. It makes your label more attractive. It is an ambient property which means if we do not set the value of this property, it will automatically retrieve from the parent control. You can set this property using two different methods:

1. Design-Time: It is the easiest method to set the ForeColor property of the Label control using the following steps:

  • Step 1: Create a windows form as shown in the below image:
    Visual Studio -> File -> New -> Project -> WindowsFormApp

  • Step 2: Drag the Label control from the ToolBox and drop it on the windows form. You are allowed to place a Label control anywhere on the windows form according to your need.
  • Step 3: After drag and drop you will go to the properties of the Label control to set the ForeColor property of the Label.

    Output:

2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the foreground color of the Label control programmatically with the help of given syntax:

public virtual System.Drawing.Color ForeColor { get; set; }

Here, Color indicates the foreground color of the Label. Following steps are used to set the ForeColor property of the Label:

  • Step 1: Create a label using the Label() constructor is provided by the Label class.
    // Creating label using Label class
    Label mylab = new Label();
    
  • Step 2: After creating Label, set the ForeColor property of the Label provided by the Label class.
    // Set ForeColor property of the label
    mylab.ForeColor = Color.DarkBlue;
    
  • Step 3: And last add this Label control to form using Add() method.
    // Add this label to the form
    this.Controls.Add(mylab);
    

    Example:

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Linq;

    using System.Text;

    using System.Threading.Tasks;

    using System.Windows.Forms;

    namespace WindowsFormsApp16 {

    public partial class Form1 : Form {

        public Form1()

        {

            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)

        {

            Label mylab = new Label();

            mylab.Text = "GeeksforGeeks";

            mylab.Location = new Point(222, 90);

            mylab.Size = new Size(120, 25);

            mylab.BorderStyle = BorderStyle.FixedSingle;

            mylab.BackColor = Color.LightBlue;

            mylab.Font = new Font("Calibri", 12);

            mylab.ForeColor = Color.DarkBlue;

            this.Controls.Add(mylab);

        }

    }

    }

    Output:

When developing C# applications using WinForms, customizing the background color of your forms and controls can significantly enhance the visual appeal and user experience. In this blog post, we will explore various methods to set background colors in C# WinForms applications with code examples.

Setting Form Background Color

To set the background color of a form in C#, you can use the BackColor property. Here’s a simple example that changes the background color of a form to light blue:

this.BackColor = Color.LightBlue;

You can choose from a wide range of predefined colors in the System.Drawing.Color class or define your custom colors using RGB values.

Setting Control Background Color

Similarly, you can set the background color of individual controls such as buttons, labels, or panels. For instance, to change the background color of a button:

button1.BackColor = Color.Orange;

By setting the background color of specific controls, you can create a visually appealing layout that aligns with your application’s design requirements.

Handling Dynamic Background Color Changes

In some cases, you may need to change the background color dynamically based on user interactions or specific conditions. You can achieve this by handling events or using conditional statements to update the background color accordingly.

Here’s an example that changes the form’s background color based on a button click event:

private void button_Click(object sender, EventArgs e)
{
    this.BackColor = Color.Green;
}

By incorporating dynamic background color changes, you can provide users with visual feedback and enhance the interactivity of your C# WinForms application.

Best Practices for Background Color Customization

When customizing background colors in C# WinForms applications, consider the following best practices:

  1. Maintain consistency in color schemes across forms and controls.
  2. Ensure sufficient contrast between text and background colors for readability.
  3. Use color psychology principles to evoke desired emotions or convey information effectively.

By following these best practices, you can create visually appealing and user-friendly interfaces that enhance the overall user experience of your C# applications.

In conclusion, setting background colors in C# WinForms applications is a simple yet effective way to customize the visual appearance of your user interface.

By leveraging the techniques and examples discussed in this blog post, you can enhance the aesthetics and usability of your C# applications with ease.

A C# ColorDialog control is used to select a color from available colors and also define custom colors. A typical Color Dialog looks like Figure 1 where you can see there is a list of basic solid colors and there is an option to create custom colors.


Figure 1


Creating a ColorDialog

We can create a ColorDialog control using a Forms designer at design-time or using the ColorDialog class in code at run-time (also known as dynamically). Unlike other Windows Forms controls, a ColorDialog does not have and not need visual properties like others. The only purpose of ColorDialog to display available colors, create custom colors and select a color from these colors. Once a color is selected, we need that color in our code so we can apply it on other controls.

Again, you can create a ColorDialog at design-time but It is easier to create a ColorDialog at run-time.

Design-timeTo create a ColorDialog control at design-time, you simply drag and drop a ColorDialog control from Toolbox to a Form in Visual Studio. After you drag and drop a ColorDialog on a Form, the ColorDialog looks like Figure 2.


Figure 2


Adding a ColorDialog to a Form adds following two lines of code.

  1. private System.Windows.Forms.ColorDialog colorDialog1;  
  2. this.colorDialog1 = new System.Windows.Forms.ColorDialog(); 

Run-time

Creating a ColorDialog control at run-time is merely a work of creating an instance of ColorDialog class, set its properties and add ColorDialog class to the Form controls.

First step to create a dynamic ColorDialog is to create an instance of ColorDialog class. The following code snippet creates a ColorDialog control object.

  1. ColorDialog colorDlg = new ColorDialog();  

ShowDialog method of ColorDialog displays the ColorDialog. The following code snippet sets background color, foreground color, Text, Name, and Font properties of a ColorDialog.

  1. colorDlg.ShowDialog();  

Once the ShowDialog method is called, you can pick colors on the dialog.

ColorDialog Properties

After you place a ColorDialog control on a Form, the next step is to set properties.

The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item. The Properties window looks like Figure 3.


Figure 3


AllowFullOpen

If you look at Figure 1, you will see a button called Define Custom Colors on the ColorDialog. Clicking on this button opens the custom color editor area where you can define colors by setting RGB color values (between 0 to 255) and can also select a color from the color area as you can see in Figure 4.

ColorDialogImg4.jpg


Figure 4


AllowFullOpen property makes sure that Define Custom Color option is enabled on a ColorDialog. If you wish to disable this option, you can set AllowFullOpen property to false and your ColorDialog will look like Figure 5. 


Figure 5


The following code snippet sets the AllowFullOpen property to false.

  1. colorDlg.AllowFullOpen = false;  

Color, AnyColor, and SolidColorOnly

Color property is used to get and set the color selected by the user in a ColorDialog.

AnyColor is used to get and set whether a ColorDialog displays all available colors in the set of basic colors.

SolidColorOnly is used to get and set whether a ColorDialog restricts users to selecting solid colors only.

The following code snippet sets these properties.

  1. colorDlg.AnyColor = true;  
  2. colorDlg.SolidColorOnly = false;  
  3. colorDlg.Color = Color.Red;  

ColorDialog Code Example

Now let’s create an application that will use a ColorDialog to set colors of bunch of controls. The Windows Forms application looks like Figure 6.

ColorDialogImg6.jpg


Figure 6


In Figure 6, we have a few Windows Forms controls and clicking on Foreground Color and Background Color buttons will let user select a color and set that color as foreground and background colors of the controls. After selecting foreground and background colors, the Form looks like Figure 7.

ColorDialogImg7.jpg


Figure 7


The following code snippet is the code for Foreground Color and Background Color buttons click event handlers.

  1. private void ForegroundButton_Click(object sender, EventArgs e)  
  2. {  
  3.     ColorDialog colorDlg = new ColorDialog();  
  4.     colorDlg.AllowFullOpen = false;  
  5.     colorDlg.AnyColor = true;  
  6.     colorDlg.SolidColorOnly = false;  
  7.     colorDlg.Color = Color.Red;                      
  8.   
  9.     if (colorDlg.ShowDialog() == DialogResult.OK)  
  10.     {  
  11.         textBox1.ForeColor = colorDlg.Color;  
  12.         listBox1.ForeColor = colorDlg.Color;  
  13.         button3.ForeColor = colorDlg.Color;  
  14.     }  
  15. }  
  16.   
  17.   
  18. private void BackgroundButton_Click(object sender, EventArgs e)  
  19. {  
  20.     ColorDialog colorDlg = new ColorDialog();  
  21.     if (colorDlg.ShowDialog() == DialogResult.OK)  
  22.     {  
  23.         textBox1.BackColor = colorDlg.Color;  
  24.         listBox1.BackColor = colorDlg.Color;  
  25.         button3.BackColor = colorDlg.Color;  
  26.     }  
  27. }  

Summary

A ColorDialog control allows users to launch Windows Color Dialog and let them select a solid color or create a custom color from available colors. In this article, we discussed how to use a Windows Color Dialog and set its properties in a Windows Forms application.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Не загружается windows 10 восстановление загрузчика
  • Что значит trial version windows
  • Как включить режим для глаз на windows 10
  • Удаление учетной записи windows 10 с компьютера
  • Как настроить языки ввода windows 10