Domanda

I've seen this asked a lot on this site and others, but I've yet to find a answer. What I'm trying to do is draw a series of rectangles roughly 10x10 in size on a click. So I have a button, when I click it, it will create a rectangle inside my panel using

 xgraphics = pnlContainer.CreateGraphics();
 xgraphics.FillRectangle(new SolidBrush(Color.Red), xAxis, yAxis, 10, 10);
 pnlContainer.AutoScrollPosition = new Point(Convert.ToInt32(xAxis),Convert.ToInt32(yAxis));
 yAxis += 10;

It creates the rectangle then moves down, on the next click it creates another rectangle but now it's lower and so on and so forth. I'm utilizing a trick I read on here on how to get the panel to scroll by putting a panel inside a panel with autoscoll on and raise the height on the inner panel when you get to the bottom. It works great HOWEVER!!!! when the panel scrollbar appears it clears all of my graphics.

I read that I counter this to use invalidate(); But when I do this it throws an error that graphics cannot be converted into a rectangle. so what the F???

I seen on MSDN that I could do this:

private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{

  // Draw the rectangle...

  e.Graphics.DrawRectangle(new Pen(Color.Blue, PenWidth), RcDraw);

}

However, this creates a rectangle using the mouse, which wont work in my situation. In a nutshell I need to be able to create a rectangle in a panel that when it gets to the bottom it then will allow you to scroll and add more rectangles to it... It doesn't sound that hard, but I'm missing something fundamental or something and it's really starting to grind my gears! Please Help!

È stato utile?

Soluzione

It's not a good practice to use Graphics property anywhere other than Paint event. Because you don't wanna lose what you've painted after a refresh, so you must paint them whenever needed, that is in Paint event. So you have two choices:

First Create an Image, get Graphics from the image and draw your items to it, then set BackGroundImage property of panel to this image. This way you don't mess with painting and give it to the control itself :)

Second Store the data needed for drawing rectangles in some variables in scope of the form. You may use a List of Rectangles and Add to them on each click, then draw them in Paint event whenever needed:

private List<Rectangle> myrects=new List<Rectangle>;

    private void childPanel_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
    {
      e.Graphics.FillRectangles(Brushes.Red, myrects.ToArray());
    }

Remember to include this in child panel if you use the scrolling trick you mentioned

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top