3

There are buttons in FormDesign. If first button is clicked,

        brush = Brushes.Red;

there are codes like this for each button. I want to get brushes color for that moment. How can I get it like;

Color c = (color of brush);

this way ?

Edit : I want to keep color data in a List.

PreS
  • 43
  • 1
  • 5

3 Answers3

2

Below code illustrates a Button Click that changes the color of Button and Color of Button is stored in a String

 private void button1_Click(object sender, EventArgs e)
      {
         Brush brush = new SolidBrush(Color.Red);
         button1.BackColor = ((SolidBrush)brush).Color;

         string getColor;
         getColor = button1.BackColor.ToString();
         MessageBox.Show($"Color of Button1  " + getColor);

      }

OR

private void button1_Click(object sender, EventArgs e)
      {
         Brush brush1 = Brushes.Red;
     button1.BackColor = ((SolidBrush)brush1).Color;

     string getColor1;
     getColor1 = button1.BackColor.ToString();
     MessageBox.Show($"Color of Button1  " + getColor1);

     //Similarly store other button colors in a string
     string getColor2 = "Orange"; string getColor3 = "Blue"; 

     //Store these string value in a list 
     List<string> colors = new List<string>();
     colors.Add(getColor1);
     colors.Add(getColor2);
     colors.Add(getColor3);
     foreach (string color in colors) { MessageBox.Show(color); }
      }

enter image description here

Clint
  • 6,011
  • 1
  • 21
  • 28
  • Thanks. I want to keep colors in a List. How can I do that ? I tried to keep it as string list. It's okay to get color that way. But I can't use it. Because I will draw with colors in the list. How can I do that ? – PreS May 05 '18 at 19:57
  • I want to draw with them. e.Graphics.FillPolygon( (brush with colors[0]) , points) – PreS May 05 '18 at 20:03
  • How can I convert that string to color and use it with brush ? – PreS May 05 '18 at 20:04
  • That is a completely different question, Could you post question with the requirements ? – Clint May 05 '18 at 20:08
  • https://stackoverflow.com/questions/50193673/how-to-draw-shape-using-colors-in-a-string-list here it is – PreS May 05 '18 at 20:18
1

Brush is a parent class for various type of brushes; only the SolidBrush has a Color property.

So you need to cast to SolidBrush:

Either:

Brush b1 = Brushes.Red;
Color c1 = ((SolidBrush)b1).Color;

or

SolidBrush b2 = (SolidBrush)Brushes.Red;
Color c2 = b2.Color;
TaW
  • 53,122
  • 8
  • 69
  • 111
0

You can get the Color using Control.BackColor and Control.ForeColor.

Swift
  • 3,250
  • 1
  • 19
  • 35