c# - Paintbox content doesn't get repainted in an other Form


Keywords:c# 


Question: 

I simple want to create a picturebox in a new Form and display a chart with it, but when I try to draw something in the picturebox nothing appears.

I take some research and now I think the Rectangle that I want to draw in the picturebox doesn't get re-painted when the whole Form gets re-drawn.

Can someone give me advise how can I fix that?

private void chartToolStripMenuItem1_Click(object sender, EventArgs e)
{
    PictureBox pictureBox = new PictureBox();
    Graphics g = pictureBox.CreateGraphics();
    Form chartForm = new Form();

    chartForm.Controls.Add(pictureBox);
    pictureBox.Location = new Point(0, 0);

    chartForm.Show();
    chartForm.DesktopLocation = new Point(this.DesktopLocation.X + this.Size.Width + 10, this.DesktopLocation.Y);
    chartForm.Icon = this.Icon;
    chartForm.Height = this.Size.Height;

    pictureBox.Size = chartForm.Size;

    Pen pen = new Pen(Color.Orange, 10);
    Rectangle rectangle = new Rectangle(new Point(20, 20), new Size(100, 100));
    g.DrawRectangle(pen, rectangle);
}

EDIT: I added a System.Threading.Thread.Sleep(5000); at the end of the Function. The Rectangle is shown in the Picturebox until the 5 seconds runs out.


1 Answer: 

I just used the wrong tools like LarsTech and melya said in the comments under my Question. With the Paint event handler and the delivered Graphics funktion.