winforms - button click windows form c# -
hi guys i'm trying make "minipaint" application has 3 buttons(rectangle, circle , line). i'm having problem making buttons
work. example have rectangle class inherits color, thickness, startpoints x, y shape:
class rectangle : shape { public int length { get; set; } public int width { get; set; } public override void draw(graphics g) { g.drawrectangle(new pen(color), new rectangle(startx, starty, width, length)); } }
now want rectangle_btn_click
print rectangle in panel
whenever click on it. here panel
code:
private void panel1_paint(object sender, painteventargs e) { graphics g = panel1.creategraphics(); }
and button
:
private void rectangle_btn_click(object sender, eventargs e) { rectangle r = new rectangle(); int retval = r.draw(g); }
but has error , not recognize g
. how should make work?
you need declare graphics object globally:
private graphics g; private void panel1_paint(object sender, painteventargs e) { g = panel1.creategraphics(); }
then should work
private void rectangle_btn_click(object sender, eventargs e) { rectangle r = new rectangle(); r.draw(g); }
this assumes panel1_paint
, rectangle_btn_click
both declared in same class.
edit:
as @krw12572 pointed out problem after minimizing form drawn object disappear because panel redrawn. solve problem following edits need made:
private list<shape> shapes = new list<shape>(); private void panel1_paint(object sender, painteventargs e) { foreach (var shape in shapes) { shape.draw(e.graphics); } } private void button1_click(object sender, eventargs e) { //this draw rectangle @ fixed position fixed size rectangle r = new rectangle() {startx = 10, starty = 10, length = 10, width = 10, color = color.black}; shapes.add(r); panel1.invalidate(); }
also classes should this:
public class shape { public color color { get; set; } public int width { get; set; } public int startx { get; set; } public int starty { get; set; } public virtual void draw(graphics g) { } } public class rectangle : shape { public int length { get; set; } public int width { get; set; } public override void draw(graphics g) { g.drawrectangle(new pen(color), new rectangle(startx, starty, width, length)); } }
this approach uses cache objects need drawn. on button click object added cache.
Comments
Post a Comment