Monday, 15 April 2013

c# - Label text doesn't get updated until the whole loop is completed -



c# - Label text doesn't get updated until the whole loop is completed -

i have winform programme calculations when user clicks on button , calls picturebox paint event draw new bmp based on results of calculations. works fine.

now want 100 times , every time picturebox refreshed, want see iteration it's in updating text on label per below:

private void button2_click(object sender, eventargs e) { (int iterations = 1; iterations <= 100; iterations++) { // calculations alter cellmap parameters cellmap.calculate(); // refresh picturebox1 picturebox1.invalidate(); picturebox1.update(); // update label 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; (int = 0; < cellmap.dimensions.width; i++) { (int j = 0; j < cellmap.dimensions.height; j++) { // retrieve rectangle , draw 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 bmp gbmp.fillrectangle(whichbrush, i, j, 1f, 1f); } } g.interpolationmode = system.drawing.drawing2d.interpolationmode.nearestneighbor; g.drawimage(bmp, 0, 0, picturebox1.width, picturebox1.height); }

the problem having label text gets displayed after lastly picturebox update completed. essentially, not display 1 through 99. can see picturebox updates after every refresh bmp changes every iteration. idea?

to reply question why have it: windows forms programs run in single thread - ui thread. means must execute code in order, finish function before can switch ui code. in other words, can't update pictures until after finished function, if updated image 100 times, lastly 1 updated. using invalidate/update code tells compiler "pause" execution of function , forces update ui instead of waiting till end of function. hope helps!

c# winforms image repaint

No comments:

Post a Comment