2

I'm trying to have a rectangle that changes size based on a value, But I cannot get it to update. If I draw the rectangle with set values it shows up, But if I then add a "*" operator to it, it does not show.

I've never used winform graphics before, this is based on other posts i've come across.

The code:

private void Send()
        {
            int l = 25, r = 20; // Testing values

            using (Graphics g = this.MainPanel.CreateGraphics())
            {

                Brush brush = new SolidBrush(Color.LimeGreen);

                g.FillRectangle(brush, 59, 74, 16, 56 * (l / 100));
                g.FillRectangle(brush, 81, 74, 16, 56 * (r / 100));

                brush.Dispose();
                this.Invalidate();
            }

            string start = l + ":" + r + ".";
            char[] end = start.ToCharArray();
            port.Write(new string(end));
        }

This bit of code runs every 15ms if that matters.

Tristan Cunningham
  • 909
  • 2
  • 10
  • 24
  • possible duplicate of [How do I suspend painting for a control and its children?](http://stackoverflow.com/questions/487661/how-do-i-suspend-painting-for-a-control-and-its-children) – Tarec Feb 13 '14 at 09:56

1 Answers1

2

Use RectangleF instead. The height of your calculated rectangle is 0, because the int value is rounded to 0 when you're dividing. Better use float and RectangleF.

Also, in my opinion is better to calculate the rectangle you need to draw in the method Send(), and then invalidate the Form. You paint the rectangles in the method OnPaint() of the form. For example:

    private void Send()
    {
        float l = 25, r = 20; // Testing values

        mRectangle1 = new RectangleF(59, 74, 16, 56 * (l / 100));
        mRectangle2 = new RectangleF(81, 74, 16, 56 * (r / 100));

        Invalidate();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        using (Brush brush = new SolidBrush(Color.LimeGreen))
        {
            e.Graphics.FillRectangle(brush, mRectangle1);
            e.Graphics.FillRectangle(brush, mRectangle2);
        }
    }

    private RectangleF mRectangle1;
    private RectangleF mRectangle2;

And this is the result:

enter image description here

Hope it helps.

Daniel Peñalba
  • 30,507
  • 32
  • 137
  • 219
  • Thanks, Seems to work great apart from its always on the bottom. How would I make it be on the top of everything. – Tristan Cunningham Feb 13 '14 at 10:16
  • If you want to paint over child controls, the solution is a little bit more complicated. Take a look to this article: http://www.codeproject.com/Articles/26071/Draw-Over-WinForms-Controls – Daniel Peñalba Feb 13 '14 at 10:46