C# 将图形指定给pictureBox

C# 将图形指定给pictureBox,c#,picturebox,system.drawing,C#,Picturebox,System.drawing,我有一个函数,每500毫秒调用一次,它应该删除PictureBox中包含的旧图形,并用新图形替换它 public override void onUpdate() { pictureBox.Image = null; Graphics g = pictureBox.CreateGraphics(); Pen p = new Pen(System.Drawing.Color.Blue, 3);

我有一个函数,每500毫秒调用一次,它应该删除PictureBox中包含的旧图形,并用新图形替换它

public override void onUpdate()
        {
            pictureBox.Image = null;
            Graphics g = pictureBox.CreateGraphics();
            Pen p = new Pen(System.Drawing.Color.Blue, 3);
            Random rnd = new Random();
            int randomInt = rnd.Next(0, 11);
            g.DrawEllipse(p, new Rectangle(new Point(0,randomInt), pictureBox.Size));
            p.Dispose();
            g.Dispose();
            return;
        }
不工作(屏幕上没有显示任何内容),调试时除外。。 鉴于当我这样做时:

 public override void onUpdate()
        {
            Graphics g = pictureBox.CreateGraphics();
            Pen p = new Pen(System.Drawing.Color.Blue, 3);
            Random rnd = new Random();
            int randomInt = rnd.Next(0, 11);
            g.DrawEllipse(p, new Rectangle(new Point(0,randomInt), pictureBox.Size));
            p.Dispose();
            g.Dispose();
            System.Threading.Thread.Sleep(5000);
            pictureBox.Image = null;
            return;
        }
圆圈每5秒绘制一次,然后消失500毫秒

第二个对我来说是合乎逻辑的,但我不明白为什么第一个不能按我想要的方式工作。。如果删除“pictureBox.Image=null;”行,则不会删除旧的圆


我能做什么,每次调用onUpdate()时都重新绘制圆,并让它一直保持这样直到下次调用它?

Winforms GDI+已经有一段时间了

新方法:创建一个usercontrol并在其中输入下面的代码,然后用新控件(您必须编译它一次,以便它位于工具箱中)和您的代码替换图片框,只需调用新控件的UpdateCircle方法:

 public partial class CircleControl : UserControl
{
    private Random rnd = new Random();
    Pen p = new Pen(Color.Blue, 3);

    public CircleControl()
    {
        InitializeComponent();
        this.Paint += CircleControl_Paint;

    }

    public void UpdateCircle() 
    {
        this.Invalidate();
    }

    void CircleControl_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.Clear(Color.White);
        int randomInt = rnd.Next(0, 11);
        e.Graphics.DrawEllipse(p, new Rectangle(new Point(0, randomInt), this.Size));
    }
}

我不知道你到底是什么意思,但这个不起作用:Graphics Graphics=pictureBox.CreateGraphics();笔p=新笔(System.Drawing.Color.Blue,1);graphics.drawerlipse(p,新矩形(新点(0,新随机().Next(0,11)),新尺寸(pictureBox.Size.Width-20,pictureBox.Size.Height-20));p、 处置();graphics.Dispose();位图Bitmap=Bitmap.FromHbitmap(graphics.GetHdc());pictureBox.Image=位图;您应该使用paint事件中的图形对象,而不是CreateGraphics。您还应该使用计时器,而不是循环(我猜这就是您调用onUpdate的方式)。在勾号事件中,调用
pictureBox.Invalidate()并在绘制事件中绘制图片。无需设置图像属性。