问题
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