Eitan Yona
Eitan Yona

Reputation: 75

The buttons in project delete the squares?

I have problem with my C# winform project.

I have function that draw squares:

public void DrawingSquares(int x, int y)
{
  System.Drawing.Graphics graphicsObj;
  graphicsObj = this.CreateGraphics();
  Pen myPen = new Pen(System.Drawing.Color.Black, 5);
  Rectangle myRectangle = new Rectangle(x, y, 100, 100);
  graphicsObj.DrawRectangle(myPen, myRectangle);
}

private void button1_Click(object sender, EventArgs e)
{
  z = Convert.ToInt16(textBox1.Text)-1;
  k = Convert.ToInt16(textBox2.Text)-1;
  DrawAllSquares();
}

private void DrawAllSquares()
{
  int tempy = y;
  for (int i = 0; i < z; i++)
  {
    DrawingSquares(x, y);
    for (int j = 0; j < k - 1; j++)
    {
      tempy += 50;
      DrawingSquares(x, tempy);
    }
    x += 50;
    tempy = y;
  }
}

In my project, I have a function that I use to move button around the form at runtime, but when the button is moved onto the drawing the drawing is deleted.

What can I do to make the drawing permanent?

Upvotes: 0

Views: 159

Answers (1)

Tigran
Tigran

Reputation: 62286

If you need permanently (in terms of application life time), by any means, you need to use it inside you Control's (the Control where rectangle is have to be drawn), OnPaint method.

If you need an animation too: it could be resolved by using a timer and changing coordinates that you pass like a parameters to your DrawSquares.

Hope this helps.

EDIT

A pseudocode:

public class MyControl : Control 
{
    public override void OnPaint(PaintEventArgs e)
    {
       base.OnPaint(e); 

       DrawingSquares(e.Graphics, valueX, valueY);
    }

    public void DrawingSquares(Graphics graphicsObj, int x, int y)
    {      
       Pen myPen = new Pen(System.Drawing.Color.Black, 5);
       Rectangle myRectangle = new Rectangle(x, y, 100, 100);
       graphicsObj.DrawRectangle(myPen, myRectangle);
    }

}

valueX and valueY are relative X and Y coordinates where you want the rectangle to be drawn.

These coordinates can be constant values, or you can change them from some timer and call Invalidate() on MyControl, so paint will be executed.

Upvotes: 2

Related Questions