0

In my c# windows form application I am trying to draw a rectangle by getting the coordinates from the user through 4 mouse click events in the windows form, one for each point.

Here is what I've tried so far.

private void Form1_Click(object sender, EventArgs e)
{
    using (Graphics g = this.CreateGraphics())
    {
        Pen pen = new Pen(Color.Black, 2);
        Brush brush = new SolidBrush(this.BackColor);
        g.FillRectangle(brush, this.Bounds);  // redraws background
        g.DrawRectangle(pen,textBox1.Text,textBox2.Text,textBox3.Text,textBox4.Text);
        pen.Dispose();
        brush.Dispose();
    }
}    
Nick Udell
  • 2,420
  • 5
  • 44
  • 83
user3413736
  • 163
  • 1
  • 4
  • 11
  • If you just want to get the position of the mouse when you click, check out this answer: http://stackoverflow.com/questions/7055211/how-to-get-the-position-of-a-click As for drawing the rectangle, look into this question, perhaps: http://stackoverflow.com/questions/2529567/draw-a-rectangle-using-winforms – Nick Udell Apr 24 '14 at 11:12
  • 1
    if you get 4 points as input from the user (i assume you would be using the mouse click to capture the co-ordinates) without any validations then its not necessary you would have a rectangle .. you could end up drawing a quadrilateral ... what is the requirement ? please be more specific .. – Rachit Apr 24 '14 at 11:15
  • 1
    using mouse click i need to select four points on windows form and draw line to points in rectangle form ... – user3413736 Apr 24 '14 at 11:24
  • A rectangle is defined by two not four points. Maybe you want to draw a quadrangle? Will you trust your user to select the points in a meaningful order? For quadrangles collect the four points in a list, add the first one as the fifth point and do a drawlines.. – TaW Apr 24 '14 at 12:06

1 Answers1

0

Your first mistake is drawing in a Click handler. Don't use CreateGraphics. Anything you draw with that is volatile and unlikely to play well.

What you should do is collect the points you want to draw when the Click event fires. Add a handler for the form's Paint event and do your drawing there. The event args will provide a Graphics object for you to use.

A separate method for calculating the rectangle might also be useful to keep that work out of the Paint handler.

DonBoitnott
  • 10,787
  • 6
  • 49
  • 68