Windows Forms Application update when minimized

2.5k views Asked by At

I have a windows forms application where i add the mainloop in the constructor of the form like this:

Application.Idle += new EventHandler(Update);

that works fine - however, my update function is not called when I minimize the application window. What do I need to do in order to get my update function called also while the window is minimized?

3

There are 3 answers

0
Jon Seigel On

You can use a timer as Henk suggests, but simply add a flag that signals that the method is still processing.

So, set a delay time of, say, 50ms, and code up the event handler like so:

private void timer1_Tick(object sender, EventArgs e)
{
    if ((this.WindowState == FormWindowState.Minimized) && !_isProcessing)
    {
        _isProcessing = true;

        // Do stuff

        _isProcessing = false;
    }
}

where _isProcessing is a private boolean variable on your form.

If you expect the operations to take less than 50ms each, then aggregate the operations somehow (maybe a queue would be appropriate).

4
Henk Holterman On

You could call it from a System.Threading.Timer. Either start the Timer when you get minimized or just let it run (low frequency) and test for Minimized before calling Update.

Edit based on the comments

The most sensible way to do this is to run the Update code from another thread. The Idle-event or Timer solutions will both run into problems.

But with a thread you have to be careful when touching any UI Control. A simple approach is the BackgroundWorker. It has Completed and Progress events that are executed thread-safe.

2
Charles Bretana On

I'd have to try this to be sure, but my first guess is to wire up the form Resize event, and in the handler, check to see if the form is minimized...