Draw rectangle over a picturebox problem

Hi all. I try to draw a rectangle over a picturebox, but I face a problem. The object (rectangle) is drawing successfully but the problem is that when I move some other picturebox which is over the first picturebox several times and it passed over the location where I have drawn the object the rectangle disappears. I use picBox.CreateGraphics().DrawRectangle(...) to draw the rectangle over the pictureBox. How can I draw something over a pictureBox so it will not disappear after some other pictureBox passed over it? Thanks a lot.
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mike TomlinsonMiddle School Assistant TeacherCommented:
Do NOT use CreateGraphics().

Instead, use the graphics supplied in the PAINT Event of the PictureBox.'

It is passed via the "e" Parameter:
public void pictureBox1_Paint(object sender, PaintEventArgs e)
    Graphics g = e.Graphics;

Open in new window

Instead of getting the Graphics of the pictureBox, try to get the graphics of the image displayed in the picturebox.
Then handle it during the Paint event.

This link will provide more detail


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Mike TomlinsonMiddle School Assistant TeacherCommented:
Just noticed I have a small typo in my snippet.

Obviously, this:


Should be:


If you use the Paint() Event graphics then you can draw "on top" any Image currently being displayed in the PictureBox...WITHOUT permanently changing the actual image.  Whether this is desirable or not really depends on your application...  =)
mg_miro_86Author Commented:
Thank you CuteBug:. You solution solved my problem. Thanks and for Idle_Mind for his reply. Have a nice day. ;)
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.