views:

50

answers:

1

Hi..i m currently working on visual c++ 2008 express edition.. in my project i have a picturebox which contains an image, now i have to draw a rectangle to enaable the user to select a part of the image.. I have used the "MouseDown" event of the picturebox and the below code to draw a rectangle:

Void pictureBox1_MouseDown(System::Object^ sender, Windows::Forms::MouseEventArgs^  e)   
                 {  
             Graphics^ g = pictureBox1->CreateGraphics();  
             Pen^ pen = gcnew Pen(Color::Blue);  
             g->DrawRectangle( pen , e->X ,e->Y,width,ht);           
         }

now in the "DrawRectangle" the arguments "width" and "ht" are static, so the above code results in the drawing of a rectangle at the point where the user presses the mouse button on the image in picturebox... i want to allow the user to be able to drag the cursor and draw a rectangle of size that he wishes to.. Plz help me on this.. Thanx..

A: 

You shouldn't draw directly to your window in your event handlers - all drawing should be in your Paint event handler.

There is a lot more you can do to make it work well, but the core of the technique you need is:

To move a rectangle around as the user drags the mouse, you have to handle Mouse Moved events. Each time you get one, you need to Invalidate() to cause a redraw of your window. In your Paint handler, if the mouse button is down, get the mouse pointer position and draw the rectangle at that location.

That will get you started, but it will have a few problems - the window will flicker as it constantly redraws, and it may be a bit slow.

There are other things you can do to improve this, including:

  • Only Invalidate the parts of the form that you need to (where the old rectangle needs to be erased from, and where the new rectangle needs to be drawn)

  • After Invalidate(), call Update() immediately to cause the redraw to happen as soon as possible

  • "double buffered" rendering, and/or storing the window content in an offscreen bitmap so that you can re-render the background with the rectangle on top more quickly and without flicker. (But this is quite an advanced technique).

Jason Williams