Force redraw before long running operations

此生再无相见时 提交于 2020-01-19 04:00:43

问题


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.


回答1:


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.




回答2:


InvalidateVisual(); @HCL is right... don't do this

Like you say, it is better to start use a background thread / dispatcher and keep the UI thread unblocked. Consider looking at the Reactive Extensions library from Microsoft for high level asynchronous ui programming




回答3:


In Windows.Forms, you can Button.Refresh().

In Windows.Forms or WPF, you can yield to the message pump to let it redraw. Async/Await were designed to allow you to do this without the nastiness of HCL's answer.

Private Async Function Button_OnClick

    Button.Enabled = False

    Await Task.Yield

    [LONG OPERATION] 

End Function


来源:https://stackoverflow.com/questions/8128670/force-redraw-before-long-running-operations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!