0

Using GDI+ and C#, I am trying to Draw a Rectangle with my Mouse Movement on a Panel (called DrawingPanel), I am using Double buffered as well I am doing the drawing in Paint Event, Still It is causing a Lots of flickering when my Mouse is Moving.

Here is my Code...

Rectangle mRect = new Rectangle();
Boolean isDragging = false;

public Form1()
{
   InitializeComponent();
   this.DrawingPanel.Paint += new PaintEventHandler(this.OnPanelPaint);
   this.DrawingPanel.MouseMove += new MouseEventHandler(this.OnPanelMouseMove);
   this.DrawingPanel.MouseDown += new MouseEventHandler(this.OnPanelMouseDown);
   this.DrawingPanel.MouseUp += new MouseEventHandler(this.OnPanelMouseUp);
   this.DoubleBuffered = true;
}

private void OnPanelPaint(object sender, PaintEventArgs e)
{
   using (Graphics g = this.DrawingPanel.CreateGraphics()) 
   {
      g.DrawRectangle(Pens.Black, mRect);
      g.FillRectangle(Brushes.SkyBlue, mRect);
   }
}


private void OnPanelMouseMove(object sender, MouseEventArgs e)
{
    if(isDragging)
    {
      mRect = new Rectangle(mRect.Left, mRect.Top, e.X - mRect.Left, e.Y - mRect.Top);
      this.DrawingPanel.Invalidate();
    }
}

private void OnPanelMouseDown(object sender, MouseEventArgs e)
{
    mRect = new Rectangle(e.Location, new Size(0, 0));
    this.DrawingPanel.Invalidate();
    isDragging = true;
}

private void OnPanelMouseUp(object sender, MouseEventArgs e)
{
    isDragging = false;
}

Any Idea why it is happening still ?

Pankaj
  • 2,618
  • 3
  • 25
  • 47
  • how about changing the code in the `OnPanelMouseDown` and do the `InValidate()` method on the `Forms MouseMove Event` so instead of `this.DrawingPanel.Invalidate();` just call `Invalidate()` see if that helps – MethodMan Feb 13 '13 at 00:23
  • Thanks @DJKRAZE for your reply, I changed my OnPanelMouseDown code to this... private void OnPanelMouseDown(object sender, MouseEventArgs e) { isDragging = true; mRect = new Rectangle(e.Location, new Size(0, 0)); } but still the same effect. :( – Pankaj Feb 13 '13 at 00:26
  • 2
    Using CreateGraphics() instead of e.Graphics in the Paint event handler is fundamentally wrong. The panel also isn't double-buffered itself. See http://stackoverflow.com/questions/3113190/double-buffering-when-not-drawing-in-onpaint-why-doesnt-it-work/3113515#3113515 – Hans Passant Feb 13 '13 at 00:32
  • 1
    Pankaj- check out this link I tested the code here and zero flickering.. http://stackoverflow.com/questions/2608909/c-sharp-graphics-flickering use this to correct your use case.. – MethodMan Feb 13 '13 at 00:39
  • Thanks@DJKRAZE, I will check the code you have posted, However when I use another class called "BufferedPanel", as mentioned in the link posted by Hans, It works fine. Thanks @Hans Passant. – Pankaj Feb 13 '13 at 00:45

0 Answers0