sara sara - 29 days ago 21
C# Question

button click windows form c#

hi guys I'm trying to make a minipaint which has three buttons(rectangle , circle and line). I'm having problem with making my buttons work. for example I have this rectangle class which inherits color,thickness,startpoints x , y from 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 I want my
rectangle_btn_Click
to print a rectangle in my panel whenever I click on it. here is my panel code:

private void panel1_Paint(object sender, PaintEventArgs e)
{
Graphics g = panel1.CreateGraphics();
}


and this is my button:

private void rectangle_btn_Click(object sender, EventArgs e)
{
rectangle r = new rectangle();
int retval = r.Draw(g);
}


but it has error and it does not recognize g. how should I make this work?

Answer

You should perform any painting only in Paint event handler. Use graphics object from Paint event handler.

Implementing this way may be tricky but whenever your panel is redrawn, your painted shape will disappear if you don't perform painting in Paint event.

private shape _shape;

private void panel1_Paint(object sender, PaintEventArgs e)
{
    _shape.Draw(e.Graphics);
}

private void rectangle_btn_Click(object sender, EventArgs e)
{
    _shape = new rectangle();
    panel1.Invalidate();
}

Update: Above answer is assuming you have Draw(Graphics g) method in your base class shape and it's overridden/implemented in rectangle class.