Search code examples
c#polygonmouseclick-event

Draw a Polygon using Mouse Points in C#


I need to be able to draw a polygon using mouse click locations. Here is my current code:

 //the drawshape varible is called when a button is pressed to select use of this tool
             if (DrawShape == 4)
                {
                    Point[] pp = new Point[3];
                    pp[0] = new Point(e.Location.X, e.Location.Y);
                    pp[1] = new Point(e.Location.X, e.Location.Y);
                    pp[2] = new Point(e.Location.X, e.Location.Y);
                    Graphics G = this.CreateGraphics();
                    G.DrawPolygon(Pens.Black, pp);
                }

Thanks


Solution

  • Ok here is some sample code:

    private List<Point> polygonPoints = new List<Point>();
    
    private void TestForm_MouseClick(object sender, MouseEventArgs e)
    {
        switch(e.Button)
        {
            case MouseButtons.Left:
                //draw line
                polygonPoints.Add(new Point(e.X, e.Y));
                if (polygonPoints.Count > 1)
                {
                    //draw line
                    this.DrawLine(polygonPoints[polygonPoints.Count - 2], polygonPoints[polygonPoints.Count - 1]);
                }
                break;
    
            case MouseButtons.Right:
                //finish polygon
                if (polygonPoints.Count > 2)
                {
                    //draw last line
                    this.DrawLine(polygonPoints[polygonPoints.Count - 1], polygonPoints[0]);
                    polygonPoints.Clear();
                }
                break;
        }
    }
    
    private void DrawLine(Point p1, Point p2)
    {
        Graphics G = this.CreateGraphics();
        G.DrawLine(Pens.Black, p1, p2);
    }