我有一個Winform程序,當用戶單擊某個按鈕時執行一些計算,然後調用該圖片框繪畫事件以基於該結果繪製一個新的BMP計算。這工作正常。直到整個循環完成後,標籤文本纔會更新
現在,我想這樣做100次,每次PictureBox的刷新時間,我想看到的迭代,它是目前在用的標籤上更新文本按如下:
private void button2_Click(object sender, EventArgs e)
{
for (int iterations = 1; iterations <= 100; iterations++)
{
// do some calculations to change the cellmap parameters
cellMap.Calculate();
// Refresh picturebox1
pictureBox1.Invalidate();
pictureBox1.Update();
// Update label with the current iteration number
label1.Text = iterations.ToString();
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Bitmap bmp = new Bitmap(cellMap.Dimensions.Width, cellMap.Dimensions.Height);
Graphics gBmp = Graphics.FromImage(bmp);
int rectWidth = scaleFactor;
int rectHeight = scaleFactor;
// Create solid brushes
Brush blueBrush = new SolidBrush(Color.Blue);
Brush greenBrush = new SolidBrush(Color.Green);
Brush transparentBrush = new SolidBrush(Color.Transparent);
Graphics g = e.Graphics;
for (int i = 0; i < cellMap.Dimensions.Width; i++)
{
for (int j = 0; j < cellMap.Dimensions.Height; j++)
{
// retrieve the rectangle and draw it
Brush whichBrush;
if (cellMap.GetCell(i, j).CurrentState == CellState.State1)
{
whichBrush = blueBrush;
}
else if (cellMap.GetCell(i, j).CurrentState == CellState.State2)
{
whichBrush = greenBrush;
}
else
{
whichBrush = transparentBrush;
}
// draw rectangle to bmp
gBmp.FillRectangle(whichBrush, i, j, 1f, 1f);
}
}
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
g.DrawImage(bmp, 0, 0, pictureBox1.Width, pictureBox1.Height);
}
問題我的意思是標籤文本只有在最後一個圖片框更新完成後纔會顯示。所以基本上,它不會顯示1到99.每次刷新後,我都可以看到圖片框更新,因爲BMP隨着每次迭代而改變。任何想法?
您是否嘗試在文本更改後調用label1.Invalidate();或/和'label1.Update();'? – horgh
不,但添加這兩個語句後,它開始工作。我不明白爲什麼? – deutschZuid
試試看[Control.Update Method](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.update.aspx) – horgh