Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force redraw before long running operations

When you have a button, and do something like:

Private Function Button_OnClick

    Button.Enabled = False

    [LONG OPERATION] 

End Function

Then the button will not be grayed, because the long operation prevents the UI thread from repainting the control. I know the right design is to start a background thread / dispatcher, but sometimes that's too much hassle for a simple operation.

So how do I force the button to redraw in disabled state? I tried .UpdateLayout() on the Button, but it didn't have any effects. I also tried System.Windows.Forms.DoEvents() which normally works when using WinForms, but it also had no effect.

like image 994
Maestro Avatar asked Nov 14 '11 21:11

Maestro


1 Answers

The following code will do what you're looking for. However I would not use it. Use the BackgroundWorker class for long time operations. It's easy to use and very stable.
Here the code:

   public static void ProcessUITasks() {            
        DispatcherFrame frame = new DispatcherFrame();
        Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(delegate(object parameter) {
            frame.Continue = false;
            return null;
        }), null);
        Dispatcher.PushFrame(frame);
    }

Here you will find a sample on how to use the BackgroundWorker.

like image 149
HCL Avatar answered Sep 22 '22 04:09

HCL