Reputation: 45
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.
Upvotes: 3
Views: 1384
Reputation: 5019
Quoting the MSDN documentation on Control.Update: "Causes the control to redraw the invalidated regions within its client area."
Quoting the MSDN documentation on the Control.Paint event: "Occurs when the control is redrawn."
So when you call GamePictureBox.Update();
you trigger a new Paint event.
Remove the whole section with the Invalidate + Update, that's intended when something has changed that requires new rendering (in your scenario, if MainBlock.BlockColor is changed, for example, you'll want to trigger a new event).
Upvotes: 0
Reputation: 1718
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().
Upvotes: 2