tags:

views:

208

answers:

5

I m drawing rectangle on mouse move in c#,

i wrote the code like this,

onmousemove:

Rectangle rect = new Rectangle(
    Math.Min(mouseMovePoint.X, mouseDownPoint.X), 
    Math.Min(mouseMovePoint.Y, mouseDownPoint.Y),
    Math.Abs(mouseMovePoint.X - mouseDownPoint.X), 
    Math.Abs(mouseMovePoint.Y - mouseDownPoint.Y)
);

    graphics.DrawRectangle(myPen, rect);

onmouseup:

this.Refresh();

Rectangle rect = new Rectangle(
    Math.Min(mouseMovePoint.X, mouseDownPoint.X), 
    Math.Min(mouseMovePoint.Y, mouseDownPoint.Y),
    Math.Abs(mouseMovePoint.X - mouseDownPoint.X), 
    Math.Abs(mouseMovePoint.Y - mouseDownPoint.Y)
);

graphics.DrawRectangle(myPen, rect);

But due to this refresh method when i draw the rectangle it appears like as if it s flickering how to avoid that?

A: 

Enable DoubleBuffering should fix this.

gilbertc
No way this problem is solved by this.
A: 

Use ControlPaint.DrawReversibleFrame for drawing selection boxes, in conjunction with MouseDown, MouseMove and MouseUp events. Check this on MSDN.

Marcel Gheorghita
+3  A: 

It appears that you aren't calling this code an override of the OnPaint method of your Control or the Paint event.

If that is the case, you should be overriding the OnPaint method or setting a handler for the Paint event.

Then, in your mouse events, you store the location of the mouse coordinates and call the Invalidate method on your Control to force a repaint of the control.

Finally, in the override of OnPaint or your Paint event handler, you would access the coordinates/rectangle data that you set in the mouse events, and paint the rectangles there, using the Graphics instance passed to the OnPaint method/Paint event through the Graphics property on the PaintEventArgs class.

casperOne
A: 

Enable double buffering like suggested above, also use Invalidate instead of Refresh. You should get far better performance out of it.

Fadrian Sudaman
enabling double buffering and using invalidate is not effective since i m opening a picture and then drawing rectangle over that
Without the full code, it is hard to guess what may have caused the problem. It could be where you implement the paint, how you use your graphics object and etc. From your description there is probably very heavy processing involved if you include all that in mousemove too which will cause flickering.
Fadrian Sudaman
+1  A: 

The traditional way to avoid flickering, in any circumstances is by drawing all the staff (very time consuming in certain cases) on a bitmap and then sending the bitmap once in the drawing canvas (in a snapshot). Although GDI or GDI+ is not OpenGL, in terms of performance, however this approach, really boosts performance (I've used it in real applications drawing 1-10 million objects).

ileon