2013-02-08 33 views
1

我有一個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隨着每次迭代而改變。任何想法?

+0

您是否嘗試在文本更改後調用label1.Invalidate();或/和'label1.Update();'? – horgh

+0

不,但添加這兩個語句後,它開始工作。我不明白爲什麼? – deutschZuid

+0

試試看[Control.Update Method](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.update.aspx) – horgh

回答

4

要回答你爲什麼必須這樣做的問題:Windows窗體程序在單個線程中運行一切 - UI線程。這意味着它必須按順序執行代碼,以便它可以在切換回UI代碼之前完成一項功能。換句話說,它不能更新圖片,直到它完成了該功能,所以如果您更新了圖片100次,只有最後一張會實際更新。使用Invalidate/Update代碼會告訴編譯器「暫停」該函數的執行,並強制它更新UI,而不是等到該函數結束。希望有所幫助!

+0

是啊謝謝。它確實+1 – FrostyFire

+0

所以對於表單上的其他控件(在這種情況下,標籤)也是如此......我猜是有道理的。 – deutschZuid

6
// Code fragement... 
// 5 cent solution, add Invalidate/Update 
label1.Text = iterations.ToString(); 
label1.Invalidate(); 
label1.Update(); 
+1

爲什麼會有幫助?解釋你的答案。 – FrostyFire

+1

嗨,約翰。這確實有用。事實上,我決定使用狀態條標籤,因爲條狀標籤沒有自己的更新方法,所以它有點棘手。我結束了調用父容器的更新方法。 toolStripStatusLabel1.Invalidate(); statusStrip1.Update(); – deutschZuid

+0

爲什麼我必須這樣做?我不太明白... – deutschZuid

相關問題