In C#, how can I change a solidbrush color dynamically using numericupdown control?

Heres the code I'm using:

    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 Colors_Form
    {
        public partial class Form1 : Form
        {
            public int RedValue;
            public int GreenValue;
            public int BlueValue;
            public SolidBrush sb = new SolidBrush(Color.FromArgb(255, 0, 0, 0));
            public Form1()
            {
                InitializeComponent();
            }

            private void Form1_Paint(object sender, PaintEventArgs e)
            {
                Graphics g = e.Graphics;
                RedValue = (int)RedNumBox.Value;
                GreenValue = (int)GreenNumBox.Value;
                BlueValue = (int)BlueNumBox.Value;

                //SolidBrush sb = new SolidBrush(Color.FromArgb(255, RedValue, GreenValue, BlueValue ));
                g.FillRectangle(sb, 10, 150, 300, 200);
            }

            private void RedNumBox_ValueChanged(object sender, EventArgs e)
            {
                sb = new SolidBrush(Color.FromArgb(255, RedValue, GreenValue, BlueValue));


            }

            private void GreenNumBox_ValueChanged(object sender, EventArgs e)
            {
                GreenValue = (int)GreenNumBox.Value;
                sb = new SolidBrush(Color.FromArgb(255, RedValue, GreenValue, BlueValue));
            }

            private void BlueNumBox_ValueChanged(object sender, EventArgs e)
            {
                BlueValue = (int)GreenNumBox.Value;
                sb = new SolidBrush(Color.FromArgb(255, RedValue, GreenValue, BlueValue));
            }
        }
    }

What I'm trying to do is get the solid brush to change color when the 'valuechanged' event is triggered. Unfortunately, I have been unsuccessful. I have tried variations on:

    sb = sb.Color(Color.FromArgb(255,RedValue, GreenValue, BlueValue));

but that code fails as well. I placed the solid brush globally, so there could be access to it from any method created. I have looked everywhere and cannot find any color update instructions and all I see is 'new brush' and now, I'm unsure how to proceed. I appreciate any assistance.

1 answer

  • answered 2018-03-13 21:44 Kevbo

    You should move the brush into the paint event and remove the global variable. SolidBrush should be disposed of when its done. Better to do that in one place than all the change events.

    using (SolidBrush sb = new SolidBrush(Color.FromArgb(255, RedValue, GreenValue, BlueValue )))
            {
                g.FillRectangle(sb, 10, 150, 300, 200);
            }