- Программирование на C, C# и Java
- Уроки программирования, алгоритмы, статьи, исходники, примеры программ и полезные советы
- Как поменять цвет фона элементов в Windows Forms
- Как задать фон панели Windows Forms с помощью конструктора How to: Set the background of a Windows Forms panel using the Designer
- Задайте фон в конструктор Windows Forms Set the background in the Windows Forms Designer
- Button background colour
- 6 Answers 6
- Default background color of a button
- 6 Answers 6
- Как задать фон панели Windows Forms с помощью конструктора How to: Set the background of a Windows Forms panel using the Designer
- Задайте фон в конструктор Windows Forms Set the background in the Windows Forms Designer
Программирование на C, C# и Java
Уроки программирования, алгоритмы, статьи, исходники, примеры программ и полезные советы
ОСТОРОЖНО МОШЕННИКИ! В последнее время в социальных сетях участились случаи предложения помощи в написании программ от лиц, прикрывающихся сайтом vscode.ru. Мы никогда не пишем первыми и не размещаем никакие материалы в посторонних группах ВК. Для связи с нами используйте исключительно эти контакты: vscoderu@yandex.ru, https://vk.com/vscode
Как поменять цвет фона элементов в Windows Forms
В данной статье мы разберем несколько вариантов изменения цвета элементов Windows Forms на примере фона формы Form1 и прочих компонентов.
Способ №1. Изменение цвета в свойствах элемента.
Для многих это самый легкий способ изменения цветовой палитры элементов, так как не надо писать код, всё визуализировано и интуитивно понятно.
Для этого надо выбрать элемент формы (или саму форму) и в “Свойствах” найти вкладку “Внешний вид”. Нас интересует строка BackColor:
Здесь имеется большое количество цветовых схем и их визуальных представлений.
Выберем для примера какой-либо из цветов, чтобы изменить фон формы:
Легко, незамысловато, понятно.
Следующие способы будут производиться в коде.
Способ №2. Изменение цвета, используя структуру Color.
Это самый простой способ среди кодовых вариаций.
“На пальцах” это выглядит так:
Если мы захотим закрасить фон формы в зеленый цвет, то строка кода будет выглядеть вот так:
При запуске форма будет выглядеть так:
Если понадобится изменить цвет, например, кнопки Button на тёмно-бордовый, код будет таким:
Данный способ прост тем, что требуется лишь написать название цвета, которых также большое количество.
Зачастую этих двух способов хватает для оформления программы. Если же нужна более гибкая настройка или же среди стандартных цветов не имеется необходимых, можно воспользоваться способами, описанными ниже.
Способ №3. Изменение цвета, используя метод Color.Argb.
Этот и следующий методы позволят генерировать нужный цвет, используя значения цветового канала RGB.
RGB – это цветовая модель, которая синтезирует цвета, используя смешивание трёх основных цветов (Красного – Red, Зеленого – Green, Синего- Blue) с чёрным, вследствие чего получаются новые цвета и оттенки. Зависит получаемый цвет от интенсивности этих трёх основных цветов. Если смешать Красный, Зеленый и Синий в максимальной насыщенности, получится белый цвет. Если не смешивать их, то остаётся чёрный.
Данный способ позволяет регулировать интенсивность трех этих цветов, при смешивании которых и получится нужный нам оттенок.
Интенсивность в числовой форме для удобства применения обозначается от 0 (минимальная интенсивность) до 255(максимальная интенсивность). Все три цвета можно “варьировать” по этой шкале.
Словесно это выглядит вот так:
Названиеэлементаформы.BackColor = Color.FromArgb(Насыщенность красного, Насыщенность зеленого, Насыщенность синего);
Чтобы закрасить фон программы в чёрный цвет, используя данный метод, надо написать вот такую строку:
Как задать фон панели Windows Forms с помощью конструктора How to: Set the background of a Windows Forms panel using the Designer
PanelЭлемент управления Windows Forms может отображать как цвет фона, так и фоновое изображение. A Windows Forms Panel control can display both a background color and a background image. BackColorСвойство задает цвет фона для элементов управления, содержащихся на панели, таких как метки и переключатели. The BackColor property sets the background color for controls that are contained in the panel, such as labels and radio buttons. Если BackgroundImage свойство не задано, BackColor Выделенная область будет заполнена всей панелью. If the BackgroundImage property is not set, the BackColor selection will fill all of the panel. Если BackgroundImage свойство задано, изображение будет отображаться позади элементов управления, содержащихся на панели. If the BackgroundImage property is set, the image will be displayed behind the controls that are contained in the panel.
Для следующей процедуры требуется проект приложения Windows с формой, содержащей Panel элемент управления. The following procedure requires a Windows Application project with a form that contains a Panel control. Сведения о том, как настроить такой проект в Visual Studio, см. в разделе как создать проект приложения Windows Forms и как добавить элементы управления в Windows Forms. For information about how to set up such a project in Visual Studio, see How to: Create a Windows Forms application project and How to: Add Controls to Windows Forms.
Задайте фон в конструктор Windows Forms Set the background in the Windows Forms Designer
Откройте проект в Visual Studio и выберите Panel элемент управления. Open the project in Visual Studio and select the Panel control.
В окне Свойства нажмите кнопку со стрелкой рядом со BackColor свойством, чтобы отобразить окно с тремя вкладками. In the Properties window, click the arrow button next to the BackColor property to display a window with three tabs.
Выберите вкладку Пользовательская , чтобы отобразить палитру цветов. Select the Custom tab to display a palette of colors.
Перейдите на вкладку веб или система , чтобы отобразить список предопределенных имен цветов, а затем выберите цвет. Select the Web or System tab to display a list of predefined names for colors, and then select a color.
В окне Свойства нажмите кнопку со стрелкой рядом со BackgroundImage свойством. In the Properties window, click the arrow button next to the BackgroundImage property.
В диалоговом окне Открыть выберите файл, который требуется отобразить. In the Open dialog box, select the file that you want to display.
Button background colour
I need to change the background colour of a button using C# code (Visual Studio 2008).
I saw some people recommending the inclusion of a directive: using System.Windows.Media ; — I tried it and it triggered this error: Windows does not exist in namespace System . I tried several combinations like:
And neither is working. Is a special directive needed for using colour? What code do you suggest. Thanks a lot.
6 Answers 6
This should change your button background color to Red
You need to include System.Drawing namespace as Color class belongs to that. Like this
And ofcourse you need to add the reference to System.Drawing DLL in your project to use this namespace and Color class.
allows you to use
Although that property is technically available to all WebControls, it may be ignored for buttons (I haven’t confirmed). This, of course, is assuming your project is ASP.NET. Having said that, if it DOES happen to work for you, I highly advise that you test this in other browsers as it may be MS specific.
This property will render for only certain controls. For example, Table, Panel, DataGrid, Calendar, and ValidationSummary will render this property. It will also work for CheckBoxList, RadioButtonList and DataList if their RepeatLayout property is RepeatLayout.Table, not RepeatLayout.Flow.
However, a more flexible and widely practiced method of achieving this is to use CSS.
Default background color of a button
Want to match the default background color of a button for use in an Expander.
What is the default background color of a button?
What have I tried to far?
A lot of different colors but did not find a match.
6 Answers 6
In WPF you can right click on an element and select «Edit Template», this will create the exact template that control is using including background color. You can then apply the same generated background color to whatever control you want.
Alternatively, you can go to that controls brush properties and click on the little square and select «Convert to new resource» if you’re just looking to replicate a single brush. Then apply that newly generated brush to whatever element you want.
Resulting in the following
The WPF will apply different the colors/shapes depending on the operating system. So, there isn’t exactly one default color. But, as for reference, check the button controltemplate page. You should find the static resources WindowBackgroundBrush, DisabledBackgroundBrush and SelectedBackgroundBrush
You will still need to find which one is used by the Button control, you can do that by editing the Button template with Blend.
Depending on the case you might need to reference the brush as
or whatever the brush is.
Edit1: If I’m not mistaken the WindowBrush resource is the one used by the Button control for its default background.
Edit2 Don’t forget that the default Button template also contains a chrome object that adds some impact on the final layout.
you could use ‘Colour to Html’ it’s a nice application and you have a tool to extract any color from you desktop Colour to Html
Blam’s answer works but is a «dynamic reference to the control system brush», so in my case because my button is nested into a stackpanel that starts out disabled, when I used Background=»
As my link says, you can get a static reference to the button using:
Note the only difference is using ControlBrush instead of ControlBrushKey . Doing this allowed my button to start out flat gray when disabled, but was full color when enabled.
Как задать фон панели Windows Forms с помощью конструктора How to: Set the background of a Windows Forms panel using the Designer
PanelЭлемент управления Windows Forms может отображать как цвет фона, так и фоновое изображение. A Windows Forms Panel control can display both a background color and a background image. BackColorСвойство задает цвет фона для элементов управления, содержащихся на панели, таких как метки и переключатели. The BackColor property sets the background color for controls that are contained in the panel, such as labels and radio buttons. Если BackgroundImage свойство не задано, BackColor Выделенная область будет заполнена всей панелью. If the BackgroundImage property is not set, the BackColor selection will fill all of the panel. Если BackgroundImage свойство задано, изображение будет отображаться позади элементов управления, содержащихся на панели. If the BackgroundImage property is set, the image will be displayed behind the controls that are contained in the panel.
Для следующей процедуры требуется проект приложения Windows с формой, содержащей Panel элемент управления. The following procedure requires a Windows Application project with a form that contains a Panel control. Сведения о том, как настроить такой проект в Visual Studio, см. в разделе как создать проект приложения Windows Forms и как добавить элементы управления в Windows Forms. For information about how to set up such a project in Visual Studio, see How to: Create a Windows Forms application project and How to: Add Controls to Windows Forms.
Задайте фон в конструктор Windows Forms Set the background in the Windows Forms Designer
Откройте проект в Visual Studio и выберите Panel элемент управления. Open the project in Visual Studio and select the Panel control.
В окне Свойства нажмите кнопку со стрелкой рядом со BackColor свойством, чтобы отобразить окно с тремя вкладками. In the Properties window, click the arrow button next to the BackColor property to display a window with three tabs.
Выберите вкладку Пользовательская , чтобы отобразить палитру цветов. Select the Custom tab to display a palette of colors.
Перейдите на вкладку веб или система , чтобы отобразить список предопределенных имен цветов, а затем выберите цвет. Select the Web or System tab to display a list of predefined names for colors, and then select a color.
В окне Свойства нажмите кнопку со стрелкой рядом со BackgroundImage свойством. In the Properties window, click the arrow button next to the BackgroundImage property.
В диалоговом окне Открыть выберите файл, который требуется отобразить. In the Open dialog box, select the file that you want to display.