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.
That is because you are not drawing on the window, you are just drawing on the screen where the window happens to be.
You need to use the
Paintevent to do the drawing. You need to store what you draw in some way, either as a list of commands so that you can repeat them, or as a bitmap image.So, when you want to draw something, you add it to your list of commands or draw it on the bitmap, then you invalidate the control so that the
Paintevent is invoked. In thePainteven you add the code to do the actual drawing, i.e. repeat the commands in your list, or draw the bitmap onto the control.