在长时间运行之前强制重绘 [英] Force redraw before long running operations

查看:252
本文介绍了在长时间运行之前强制重绘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用按钮时,请执行以下操作:

When you have a button, and do something like:

Private Function Button_OnClick

    Button.Enabled = False

    [LONG OPERATION] 

End Function

然后,该按钮将不会显示为灰色,因为较长的操作会阻止UI线程重新绘制控件。我知道正确的设计是启动后台线程/调度程序,但有时对于一个简单的操作来说太麻烦了。

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.

所以我如何强制按钮重新绘制禁用状态?我在Button上尝试了.UpdateLayout(),但没有任何效果。我还尝试了System.Windows.Forms.DoEvents(),该功能在使用WinForms时通常可以正常使用,但也没有任何作用。

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.

推荐答案

以下代码将满足您的需求。但是我不会使用它。使用 BackgroundWorker 类进行长时间操作。它易于使用且非常稳定。

这里的代码:

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);
    }

此处,您将找到有关如何使用BackgroundWorker的示例。

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

这篇关于在长时间运行之前强制重绘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆