Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PictureBox.Paint event keeps firing

My PictureBox.Paint event keeps firing, and I don't know what's causing it.

    private void GamePictureBox_Paint(object sender, PaintEventArgs e)
    {
        DrawMap(e.Graphics);
    }

    public void DrawMap(Graphics g)
    {
        lock (MainBlock)
        {
            for (int RectsX = 0; RectsX < GamePictureBox.Width - 1; RectsX += (int)MainBlock.RectSize.X)
                for (int RectsY = 0; RectsY < GamePictureBox.Height - 1; RectsY += (int)MainBlock.RectSize.Y)
                    g.DrawRectangle(MainBlock.BlockColor, RectsX, RectsY, MainBlock.RectSize.X, MainBlock.RectSize.Y);
            Invoke((MethodInvoker)(() =>
            {
                GamePictureBox.Invalidate();
                GamePictureBox.Update();
            }));
        }
    }

GamePictureBox.Width and GamePictureBox.Height = 601; MainBlock.RectSize.X and MainBlock.RectSize.Y = 60.1f; The main problem is that after the 2 for loops inside DrawMap, finish, the Paint event calls DrawMap again! This keeps happening (infinite loop) and it's kinda annoying. I've tried debugging but my debugging skills only took me far enough to know that the cause of the problem was the Paint event.

The event is called NOWHERE other than the Paint event.

like image 962
Moeyy AS Avatar asked Dec 15 '25 02:12

Moeyy AS


1 Answers

The Invalidate() forces a new Paint, what triggers infinite loop.

In the Paint event, you should only draw on the graphics, i.e. no Invoke().

like image 133
Graffito Avatar answered Dec 16 '25 15:12

Graffito



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!