Draw the shape on the Button click

我只是一个虾纸丫 提交于 2019-12-13 23:07:29

问题


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?


回答1:


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);
        }
    }

}



回答2:


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)



来源:https://stackoverflow.com/questions/17383936/draw-the-shape-on-the-button-click

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!