简体   繁体   中英

how to draw rectangle by selecting four coordinate points by user in C# windows form and display the coordinate points in text box

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM