WinForms绘制,然后移动矩形 [英] WinForms Draw, Then Move Rectangle

查看:243
本文介绍了WinForms绘制,然后移动矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矩形,正在尝试使用C#在WinForms项目中绘制。我在窗体的Paint事件上绘制矩形:

I have a rectangle I am trying to draw in a WinForms project using C#. I am drawing the rectangle on the form's Paint event:

private void onPaintHandler(object sender, PaintEventArgs e) {
    using (Pen pen = new Pen(Color.Black, 1)) {
        Brush brush = new SolidBrush(Color.Gray);

        e.Graphics.FillRectangle(brush, 0, this.Height - 100, this.Width, 100);
        e.Graphics.DrawRectangle(pen, -1, this.Height - 100, this.Width, 100);

        brush.Dispose();
        pen.Dispose();
    }
}

我对能够移动矩形感兴趣。如果在上面的代码中在运行时更改位置值,则会看到在多个位置绘制了相同的矩形,但实际上并未移动。

I am interested in being able to move the rectangle. If I change the location values at runtime in the code above, I see the same rectangle drawn in multiple places, but not actually "moved".

谢谢您的时间。

推荐答案

您需要坚持在类变量
中的坐标,然后调用 Invalidate()每当您更改它们时。

You need to persist the coordinates in a class variable and call Invalidate() whenever you change them.

这将导致最初的绘画事件会触发,除了Windows注意到的时间外,该控件或窗体的表面不再有效。

This will cause the initial Paint event to fire, in addition to the times when Windows notices, that the control's or the form's surface is no longer valid.

这篇关于WinForms绘制,然后移动矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆