我正在实现一个winform应用程序,我需要一个用指针移动的矩形。我在timer_tick上创建它,如下所示。唯一的问题是它是闪烁的。如何消除闪烁?
private void timer1_Tick(object sender, EventArgs e)
{
//Gets the Mouse position on the X-axis
int posX = MousePosition.X;
//Gets the mouse poisiton on the Y-Axis
int posY = MousePosition.Y;
Graphics g = Graphics.FromHwnd(IntPtr.Zero);
mouseNewRect = new Rectangle(new Point(posX, posY), new
Size(500, 500));
g.DrawRectangle(new Pen(Brushes.Chocolate), mouseNewRect);
this.Refresh();
}
答案 0 :(得分:1)
为了在上面的评论中添加更多细节,这里有一个示例控件,演示如何设置双缓冲以及如何正确挂钩到paint事件处理。
class CustomControl : Control
{
private bool mShouldDrawMouseRect;
private Rectangle mMouseRect;
public CustomControl()
{
this.mMouseRect.Width = 500;
this.mMouseRect.Height = 500;
this.SetStyle(
ControlStyles.DoubleBuffer |
ControlStyles.ResizeRedraw |
ControlStyles.AllPaintingInWmPaint,
true);
}
protected override void OnMouseEnter(EventArgs e)
{
// No actual painting done here, just updating fields.
this.mShouldDrawMouseRect = true;
this.Invalidate();
}
protected override void OnMouseLeave(EventArgs e)
{
// No actual painting done here, just updating fields.
this.mShouldDrawMouseRect = false;
this.Invalidate();
}
protected override void OnMouseMove(MouseEventArgs e)
{
// No actual painting done here, just updating fields.
this.mMouseRect.X = e.X;
this.mMouseRect.Y = e.Y;
this.Invalidate();
}
protected override void OnPaint(PaintEventArgs e)
{
// ALL painting stays in the paint event, using the graphics provided
if (this.mShouldDrawMouseRect)
{
// If you're just using named colors, we can access the static Pen objects.
e.Graphics.DrawRectangle(Pens.Chocolate, this.mMouseRect);
// If you create your own Pen, put it in a Using statement.
// Including the following commented example:
// using (var pen = new Pen(Color.Chocolate))
// {
// e.Graphics.DrawRectangle(pen, this.mMouseRect);
// }
}
}
}