[英]How to draw a rectangle on a button click?
我想当我单击按钮时,在表单中添加一个矩形
我可以在表单颜料中添加我想要的数量,但是我无法通过单击按钮添加矩形之类的形状,我进行了搜索,但没有找到解决方案
这里有人知道怎么做吗?
这是我在窗体绘画中的代码
private void Form1_Paint(object sender, PaintEventArgs e)
{
locationX = locationX + 20;
locationY = locationY + 20;
e.Graphics.DrawRectangle(Pens.Black,
new Rectangle(10 + locationX, 10 + locationY, 50, 30));
}
这是我的按钮代码
private void button1_Click(object sender, EventArgs e)
{
this.Paint += Form1_Paint;
}
但是当我单击按钮时它不起作用。 为什么它不起作用?
线
this.Paint += Form1_Paint;
将窗体的事件Paint
关联到函数Form1_Paint。 它不会触发它。 这是您只想执行1次的操作,而不是每次按键都要做的。
要触发Paint
事件,通常的方法是调用Form
类的Invalidate()
方法。 实际上,Invalidate是Control的一种方法。 但是Form
源自Control
,因此我们也可以访问Form
的方法。
因此,在Windows窗体中触发重新绘制的正确方法是将subscription放入Load方法:
private void Form1_Load(object sender, EventArgs e)
{
this.Paint += Form1_Paint;
}
它应该已经隐藏在自动生成的代码中。 您的方法Form1_Paint
可以。
最后,按钮单击方法应为:
private void button1_Click(object sender, EventArgs e)
{
this.Invalidate(); // force Redraw the form
}
从文档 :
Invalidate():使控件的整个表面无效, 并使控件重绘 。
编辑:
使用此方法,一次只能绘制1个矩形,因为整个表面都被重新绘制,因此该表面被完全擦除,然后仅绘制您在Form1_Paint方法中要求的内容。
有关如何绘制多个矩形的答案,应创建一个矩形列表。 在每个单击按钮处,将一个Rectangle添加到列表中,然后重新绘制所有矩形。
List<Rectangle> _rectangles = new List<Rectangle>();
private void button1_Click(object sender, EventArgs e)
{
locationX = locationX + 20;
locationY = locationY + 20;
var rectangle = new Rectangle(locationX, locationY, 50, 30));
this._rectangles.Add(rectangle);
this.Invalidate(); // force Redraw the form
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
foreach(var rectangle in this._rectangles)
{
e.Graphics.DrawRectangle(Pens.Black, rectangle);
}
}
调用方法,您需要使用括号。
private void button1_Click(object sender, EventArgs e)
{
Form1_Paint(sender, e);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.