简体   繁体   English

如何通过用户在C#Windows窗体中选择四个坐标点来绘制矩形并在文本框中显示坐标点

[英]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. 在我的C#Windows窗体应用程序中,我试图通过在Windows窗体中通过4个鼠标单击事件从用户获取坐标来绘制一个矩形,每个点一个。

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. 您的第一个错误是绘制Click处理程序。 Don't use CreateGraphics . 不要使用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. 您应该做的是收集Click事件触发时要绘制的Click Add a handler for the form's Paint event and do your drawing there. 为该窗体的Paint事件添加一个处理程序,然后在此处进行绘制。 The event args will provide a Graphics object for you to use. 事件args将提供一个Graphics对象供您使用。

A separate method for calculating the rectangle might also be useful to keep that work out of the Paint handler. 另一种计算矩形的方法可能也很有用,以使该工作不受Paint处理程序的影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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