In c# I am using a PictureBox on a win form.
I am trying to recreate MSPaint to learn about the Graphics Object. It all works fine and dandy except that when another window is on on top of the PictureBox, or the entire form is resized, what is drawn under the other window in there is removed.
Here is a scaled down version of the code I am working with.
private Graphics _g;
private bool _bIsMouseDown = false;
private void picCanvas_MouseDown(object sender, MouseEventArgs e)
{
if (!_bIsGraphicsSet) _g = picCanvas.CreateGraphics();
_bIsMouseDown = true;
DrawRectangle(e);
}
private void picCanvas_MouseMove(object sender, MouseEventArgs e)
{
if (_bIsMouseDown) DrawRectangle(e);
}
private void picCanvas_MouseUp(object sender, MouseEventArgs e)
{
_bIsMouseDown = false;
}
private void DrawRectangle(MouseEventArgs e)
{
System.Drawing.Rectangle r = CreateRectangle(e);
Pen pen = ChooseDrawColor();
_g.DrawRectangle(pen, r);
}
private Rectangle CreateRectangle(MouseEventArgs e)
{
int h = 10;
int w = 10;
// there is code in here for multiple sized rectangles,
//I know the math can be simplified for this example.
return new Rectangle(e.X - (w / 2), e.Y - (h / 2), w, h);
}
Any thoughts would be much appreciated.