Question

so I am trying to make a simple game in C# using PictureBox for painting and timer for update functions, but what I noticed is that when I start painting on my picturebox my timer stops working.. I have no idea why..

Here is the picturebox code:

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
        }
    }

Here is the timer code:

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

Here is a method called by MyGame.CurrentMap.Draw(e.Graphics); :

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

Any help would be greately appreciated. I come from javascript, so I don't really know if I am doing something terribly wrong here.

Was it helpful?

Solution

When a timer tick occurs, you want to repaint your PictureBox. To do this, you should make it so that the PictureBox receives a Paint event. This is what Refresh() does, so the call to this.pictureBox1.Refresh(); goes in the end of timer1_Tick.

It doesn't make sense for the Paint event to contain a call to Refresh, because this, in turn, generates a Paint event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top