-3

I create a Windows Forms application and I want to draw a shape on the Button click. How can I call Form_Paint on the Button_Click event?

dotNet_d19
  • 43
  • 2
  • 6

2 Answers2

0

Here's a quick example that stores each "shape" as a GraphicsPath in a class level List. Each path is drawn using the supplied Graphics in the Paint() event of the form. A random rectangle is added to the List<> with each button click and Refresh() is called against the form to force it to redraw itself:

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
        this.Paint += new PaintEventHandler(Form1_Paint);
    }

    private Random R = new Random();
    private List<System.Drawing.Drawing2D.GraphicsPath> Paths = new List<System.Drawing.Drawing2D.GraphicsPath>();

    private void button1_Click(object sender, EventArgs e)
    {
        Point pt1 = new Point(R.Next(this.Width), R.Next(this.Height));
        Point pt2 = new Point(R.Next(this.Width), R.Next(this.Height));

        System.Drawing.Drawing2D.GraphicsPath shape = new System.Drawing.Drawing2D.GraphicsPath();
        shape.AddRectangle(new Rectangle(new Point(Math.Min(pt1.X,pt2.X), Math.Min(pt1.Y, pt2.Y)), new Size(Math.Abs(pt2.X - pt1.X), Math.Abs(pt2.Y - pt1.Y))));
        Paths.Add(shape);

        this.Refresh();
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Graphics G = e.Graphics;
        foreach (System.Drawing.Drawing2D.GraphicsPath Path in Paths)
        {
            G.DrawPath(Pens.Black, Path);
        }
    }

}
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40
0

To raise the Paint even by hand read this SO post (basically call the Invalidate() method)

SO post: How do I call paint event?

However, you'll probably need to have some sort of internal "drawshape" flag that you set/clear on the button click and check inside your paint even handler method. This flag will tel your paint event handler to either continue drawing your shape or not draw your shape at all (every time the form paint is called)

Community
  • 1
  • 1
Miguel Sevilla
  • 466
  • 3
  • 11