c# - 如何在单击按钮时绘制矩形?

标签 c# winforms events drawing

我想当我点击按钮时,在表单中添加一个矩形
我可以在 form paint 中添加我想要的数量,但我不能通过单击按钮添加像矩形这样的形状,我搜索了它,但没有找到解决方案
这里有人知道怎么做吗?

这是我在表单绘制中的代码

    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 窗体中触发重绘的正确方法是将订阅放在 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
}

From the doc :

Invalidate() : Invalidates the entire surface of the control and causes the control to be redrawn.

编辑:

用这个方法,你一次只能画一个矩形,因为整个表面都被重绘,所以表面被完全删除,然后它只画你在 Form1_Paint 方法中要求的东西。

关于如何绘制多个矩形的答案,您应该创建一个矩形列表。在每个单击按钮处,您都会向列表中添加一个矩形,然后重新绘制所有矩形。

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

关于c# - 如何在单击按钮时绘制矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30822805/

相关文章:

c# - Word 编辑器查找模式

winforms - 基于numericupdown在DataGridView中添加行

c# - 使用 mysql 作为数据库的文本框自动完成

html - 阻止 table 和 td 元素获得焦点

html - 单击父元素时防止 contenteditable 元素获得焦点

c# - 如何更改适配器的IP地址?

c# - 为什么 double.NaN 不等于它自己?

c# - 如何列出所有拉丁(英文字母)字符?

c# - 从 Task.Run async 更新进度条

javascript - 将 javascript var 传输到 html 表单文本框