C# 使图形无效

C# 使图形无效,c#,gdi+,C#,Gdi+,我有一个矩形的图形对象,这是在点击picturebox上的按钮时创建的,但是如果窗体从屏幕上移开,图形会消失,整个窗体也会变白。我尝试过使picturebox无效,但这会停止按钮的工作。有人能帮我将对象保留在窗体上吗使用无效方法我知道有一种方法,但我似乎无法掌握它 private void squareButton_Click(object sender, EventArgs e) { // Declaring a new graphics obje

我有一个矩形的图形对象,这是在点击picturebox上的按钮时创建的,但是如果窗体从屏幕上移开,图形会消失,整个窗体也会变白。我尝试过使picturebox无效,但这会停止按钮的工作。有人能帮我将对象保留在窗体上吗使用无效方法我知道有一种方法,但我似乎无法掌握它

  private void squareButton_Click(object sender, EventArgs e)
        {

            // Declaring a new graphics object has been assigned null
            Graphics objGraphics = null;
            // This will create the picture graphics to be drawn in the picturebox
            objGraphics = PictureBox1.CreateGraphics();
            // This will redraw the picture box with a fill chosen after the systemcolors
            objGraphics.Clear(SystemColors.ControlDark);
            // This will draw the rectangle with a red pen 10,10 represent position and 50,50 reprsent the width and height 
            objGraphics.DrawRectangle(Pens.Red, 10, 10, 50, 50);
            // This will draw the rectangle
            objGraphics.Dispose();
invalidate(PictureBox1);

// This is not redrawing the graphic it just shows a blank form

        }
试试这个:

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    Graphics objGraphics = null;
    // This will create the picture graphics to be drawn in the picturebox
    objGraphics = e.Graphics;
    // This will redraw the picture box with a fill chosen after the systemcolors
    objGraphics.Clear(SystemColors.ControlDark);
    // This will draw the rectangle with a red pen 10,10 represent position and 50,50 reprsent the width and height 
    objGraphics.DrawRectangle(Pens.Red, 10, 10, 50, 50);
    // This will draw the rectangle
    //objGrphics.Dispose();

}

不要使用CreateGraphics。使用PictureBox的Paint事件,然后只需调用
PictureBox1.Invalidate()