views:

257

answers:

2

Hi. I made a click-drag selection box in a picture box. In the picturebox Paint event hander I use

e.Graphics.DrawRectangle(pen, rectangle);

and update the rectangle and refreshe the picturebox in the mouse move event handler.

The selection box looks smooth as long as the mouse remains at the bottom-right corner (i.e. drag to right/bottom). However if I want to drag the mouse to the left or up, rectangle.X/rectangle.Y has to be re-set constantly and the box flickers very noticeably.

Is there a better/more efficient way to do the drawing? Much appreciated!

+1  A: 

I just found the solution: Replacing pictureBox.Refresh() with pictureBox.Invalidate() would make the redrawing smooth at all times. It seems Refresh() adds huge overhead in this case, that even setting the main Form or the PictureBox's DoubleBuffered property to true will not help.

Dan7
+1  A: 

another thing to take into account is DoubleBuffering

http://stackoverflow.com/questions/220100/how-do-i-enable-double-buffering-of-a-control-using-c-window-forms

have a look at the excepted answer here for the correct double buffering code.

Alastair Pitts
Yes I tried setting my main form's DoubleBuffered to true but to no avail. I guess I could extend the default PictureBox so I can access its DoubleBuffered property and see how it goes. But the flicker was so bad with Refresh() (I have some numericUpDown controls updating the selection box's values and they wouldn't event update if I am rapidly dragging the selection box), I suspect doublebuffering would barely help. Thanks anyway.
Dan7
I think `.Refresh()` does some fancy message pumping as well, so that might have been why `Invalidate()` worked better. Anyway, glad to see that you got it working.
Alastair Pitts