c# - How to draw a rectangle on a button click? -
i want when click button, add 1 rectangle form
can add in form paint how want can't add shape rectangle click button , searched didn't find solution it
here know how it?
this 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 1 button code
private void button1_click(object sender, eventargs e) { this.paint += form1_paint; }
but not working when click button. why not working?
the line
this.paint += form1_paint;
associate event paint
of form function form1_paint. it doesn't trigger it. want 1 time, not everytime hit button.
to trigger paint
event, usual way call invalidate()
method of form
class. in fact, invalidate method of control. form
derivate control
, have access method in form
too.
so right way trigger repaint in windows forms put subscribe in load method :
private void form1_load(object sender, eventargs e) { this.paint += form1_paint; }
it should hidden in auto generated code. method form1_paint
ok.
finally, button click method should :
private void button1_click(object sender, eventargs e) { this.invalidate(); // force redraw form }
from doc :
invalidate() : invalidates entire surface of control , causes control redrawn.
edit :
with method, can draw 1 rectangle @ time, because whole surface redrawn, surface completly erase, , draws asked in form1_paint method.
for answer on how draw multiple rectangles, should create list of rectangle. @ each click button, add rectangle list, , redraw rectangles.
list<rectangle> _rectangles = new list<rectangle>(); private void button1_click(object sender, eventargs e) { locationx = locationx + 20; locationy = locationy + 20; var rectangle = new rectangle(locationx, locationy, 50, 30)); this._rectangles.add(rectangle); this.invalidate(); // force redraw form } private void form1_paint(object sender, painteventargs e) { foreach(var rectangle in this._rectangles) { e.graphics.drawrectangle(pens.black, rectangle); } }
Comments
Post a Comment