I want when I click button, add one rectangle to the form
I can add in form paint how much I want but I can't add shape like rectangle by click button and I searched about it but I didn't find a solution for it
is here somebody know how to do it?
This is my code in form paint
private void Form1_Paint(object sender, PaintEventArgs e)
{
locationX = locationX + 20;
locationY = locationY + 20;
e.Graphics.DrawRectangle(Pens.Black,
new Rectangle(10 + locationX, 10 + locationY, 50, 30));
}
and this one is my button code
private void button1_Click(object sender, EventArgs e)
{
this.Paint += Form1_Paint;
}
but its not working when I click button. why its not working?
The line
Associate the event
Paint
of your Form to your function Form1_Paint. It doesn't trigger it. This is something you want to do only 1 time, not everytime you hit a button.To trigger the
Paint
event, the usual way is to call theInvalidate()
method of theForm
class. In fact, Invalidate is a method of Control. ButForm
derivate fromControl
, so we have access to the method inForm
too.So the right way to trigger a repaint in Windows Forms is to put the subscribe in the Load method :
It should already be hidden in the auto generated code. Your method
Form1_Paint
is ok.Finally, the button click method should be :
From the doc :
Edit :
With this method, you can draw only 1 rectangle at a time, because the whole surface is redrawn, so the surface is completly erase, and then it draws only what you asked in the Form1_Paint method.
For the answer on how to draw multiple rectangles, you should create a List of Rectangle. At each click button, you add a Rectangle to the list, and you redraw all the rectangles.