Marcin Majewski
Marcin Majewski

Reputation: 1047

Drawing in Windows Forms

I am beginner in drawing anything using Windows Forms and C# and I have a question(I couldnt have found answer on the internet). So here is my problem : I am trying to build simple application where i use trackbar to manipulate the size of rectangle.

    namespace Drawing
{
    public partial class Form1 : Form
    {
        int size = 10;
        public Form1()
        {
            InitializeComponent();
            CenterToScreen();
        }

        protected override void OnPaint(PaintEventArgs pe)
        {

            Graphics g = pe.Graphics;
            Rectangle rect = new Rectangle(50,50, size,size);
            LinearGradientBrush IBrush = new LinearGradientBrush(rect, Color.Green, Color.Yellow,
                LinearGradientMode.BackwardDiagonal);
            g.FillRectangle(IBrush, rect);

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void trackBar1_Scroll(object sender, EventArgs e)
        {
           size = trackBar1.Value;
 // I was trying to put here OnPaint method but it doesnt work.
        }


    }
}

And I just cant figure out how to call OnPaint method when tracBar1_Scroll occurs? Any suggestions? Thank you in advance.

Upvotes: 0

Views: 2674

Answers (3)

kmontgom
kmontgom

Reputation: 1429

One possibility is to put your drawing code into a separate function which is called from both Form1_Paint and trackBar1_Scroll.

This method would take a Graphics object as a parameter. Something like this:

private void DrawStuff( Graphics g )
{
    // your drawing logic goes here
}

And then modify _Paint and _Scroll as follows:

private void Form1_Paint( object sender, PaintEventArgs e )
{
    DrawStuff( e.Graphics );
}

private void trackBar1.Scroll( object sender, EventArgs e )
{
    Graphics g = this.CreateGraphics();

    DrawStuff( g );

    g.Dispose();
}

Alternatively, you could force your form to invalid which would also trigger _Paint to be called:

private void trackBar1.Scroll( object sender, EventArgs e )
{
    this.Invalidate();
}

Note that Invalidate() has 6 overloads, which allow you varying levels of control over what needs to be invalidated for drawing.

Upvotes: 1

Simagen
Simagen

Reputation: 419

you should also have a look at this link:

http://msdn.microsoft.com/en-us/library/system.windows.forms.trackbar.aspx

it has all the information about trackbar which you might find useful, such as the InvokePaintBackground method, or BackColour

Upvotes: 0

Gerald Versluis
Gerald Versluis

Reputation: 34103

Call this.Invalidate() this will trigger the event which makes the OnPaint go off.

Upvotes: 3

Related Questions