Draw a polygon using mouse points in C #

I need to be able to draw a polygon using mouse click points. 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

+4
source share
2 answers

Ok here is a 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(eX, eY)); 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); } 
+5
source

First add this code:

 List<Point> points = new List<Point>(); 

On the object you are drawing on, record the OnClick event. One of the arguments must have the X and Y coordinates of the click. Add them to the array of points:

 points.Add(new Point(xPos, yPos)); 

And finally, where you draw the lines, use this code:

  if (DrawShape == 4) { Graphics G = this.CreateGraphics(); G.DrawPolygon(Pens.Black, points.ToArray()); } 

EDIT:

Good, so the code above is not entirely correct. First of all, this is most likely a Click event, not an OnClick event. Secondly, to get the mouse position, you need two variables declared with an array of points,

  int x = 0, y = 0; 

Then we get the mouse move event:

  private void MouseMove(object sender, MouseEventArgs e) { x = eX; y = eY; } 

Then in the Click event:

  private void Click(object sender, EventArgs e) { points.Add(new Point(x, y)); } 
+3
source

All Articles