Once again, I’m hoping some of you experienced .NET programmers can help me figure out a solution to the problem I’m having.
We have a very simple Windows Form that is being used in a data conversion project. Basically it consists of a button and a text box. Clicking on the button starts the conversion process, and the text box is periodically updated with a record counter, so that we can monitor the progress.
This works fine as long as the form retains focus, but as soon as focus is lost the counter stops updating. The process continues to run, but even when focus comes back to the form, it is frozen at the point where focus was lost. When the process finishes, then it works again to display the final count.
Each time I display a counter in the text box, I am calling the refresh() method of the text box. What piece of code do I need to add to keep the display updating when focus is lost? We’re using C#, BTW.
The quick and simple fix is probably to call Application.DoEvents() instead of the textbox refresh. I think that will work but it’s still a bit kludgy. The form will probably be “dead” between DoEvents() calls.
A better way is to spin off another thread for the code that runs. That’s more difficult and dangerous than what you’re doing now but a lot easier these days with the BackgroundWorker component introduced in .NET 2. That gives you a fairly simple and safe way of getting your process to call back to the form to update the count or a progress bar etc and gives you a way of doing a cancel button.
Thanks, tetranz, the Application.DoEvents() looks like it has done the trick. I knew it was something simple like that. Maybe next time we’ll try the separate thread trick.
Having a separate worker thread to keep your UI alive is pretty standard practice, so you should be able to find a lot of information about it pretty easily.