Flickering when mouse moves

Dec 6 2005 1:36 PM
Hi,
I have an application in which I need to move my drawing continuosly when the user moves the mouse. The problem is that I am getting a flickering when Invalidate function is called after mouse move. Any solution? Following demostrates the sample:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Drawing2D;

namespace DrawPad
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;

private int currentPointX=0, currentPointY=0;
private Rectangle prevRectangle = new Rectangle(0,0,120,30);

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

//
// TODO: Add any constructor code after InitializeComponent call
//
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackColor = System.Drawing.SystemColors.ControlText;
this.ClientSize = new System.Drawing.Size(292, 273);
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Form1";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseUp);
this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseMove);

}
#endregion

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}

protected override void OnPaint(PaintEventArgs e)
{
SolidBrush mainBrush = new SolidBrush(Color.Red);
e.Graphics.FillRectangle(mainBrush, currentPointX, currentPointY, 120, 30);
mainBrush.Dispose();
}

private void Form1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
this.Invalidate(prevRectangle);
currentPointX = e.X;
currentPointY = e.Y;
prevRectangle.X = currentPointX;
prevRectangle.Y = currentPointY;
}

private void Form1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
{
return;
}
currentPointX = e.X;
currentPointY = e.Y;
}

}
}

Answers (3)