【问题标题】:C# PictureBox and Timer don't work togetherC# PictureBox 和 Timer 不能一起工作
【发布时间】:2014-07-02 06:12:04
【问题描述】:

所以我试图用 C# 制作一个简单的游戏,使用 PictureBox 进行绘画和计时器来更新功能,但我注意到当我开始在我的图片框上绘画时,我的计时器停止工作..我不知道为什么..

这是图片框代码:

private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        Console.WriteLine("PicBox running!");
        if (this.MyGame.InGame)
        {
            this.pictureBox1.Refresh();
            e.Graphics.Clear(Color.White);               
            MyGame.CurrentMap.Draw(e.Graphics);
            //e.Graphics.Dispose(); <- if I uncomment this, then the whole programm just freezes
        }
    }

这是定时器代码:

private void timer1_Tick(object sender, EventArgs e)
    {
        Console.WriteLine("Timer running!");
        if (this.MyGame.InGame)
        {
            MyGame.CurrentMap.Update();
            MyGame.UpdateTime();                
        }
    }

这是 MyGame.CurrentMap.Draw(e.Graphics) 调用的方法; :

public void Draw(Graphics g)
    {
        foreach(Planet item in Entities){
            item.Draw(g);
        }            
    }

任何帮助将不胜感激。我来自 javascript,所以我真的不知道我是否在这里做错了什么。

【问题讨论】:

  • 请展示你如何初始化计时器。
  • 我认为你需要在另一个线程中绘画。
  • this.pictureBox1.Refresh();不应该在pictureBox1_Paint,而是在timer1_Tick的末尾。
  • @Zoyd 我爱你!现在效果很好。我已经尝试解决这个问题大约 2 小时了。你能向我解释为什么它必须在计时器结束时吗?
  • 我同意 Gleb,如果你有你的计时器和你的私人 void pictureBox1_Paint(object sender, PaintEventArgs e) 在同一个线程中,一旦你在你的图片框中绘画,你就会去 pictureBox1_Paint方法,然后停止所有其他方法,因为您的 picturebox1_Paint 是一个事件处理程序。从我所见。

标签: c# timer drawing picturebox


【解决方案1】:

当发生计时器滴答时,您想重新绘制 PictureBox。为此,您应该使 PictureBox 接收到 Paint 事件。这就是 Refresh() 所做的,所以调用 this.pictureBox1.Refresh();在 timer1_Tick 结束时进行。

Paint 事件包含对 Refresh 的调用是没有意义的,因为这反过来会生成一个 Paint 事件。

【讨论】:

    猜你喜欢
    • 2016-03-29
    • 2019-07-01
    • 2011-03-24
    • 1970-01-01
    • 2014-01-07
    • 2019-08-17
    • 2016-11-23
    • 2019-02-18
    • 2015-05-16
    相关资源
    最近更新 更多