WinForms Draw, Then Move Rectangle

大兔子大兔子 提交于 2019-12-11 16:34:05

问题


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".

Thank you for your time.


回答1:


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

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.



来源:https://stackoverflow.com/questions/23954653/winforms-draw-then-move-rectangle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!