在长时间运行的操作之前强制重绘
当你有一个按钮,并执行以下操作:
Private Function Button_OnClick
Button.Enabled = False
[LONG OPERATION]
End Function
那么按钮将不会变灰,因为长操作会阻止 UI 线程重新绘制控件。我知道正确的设计是启动后台线程/调度程序,但有时这对于简单的操作来说太麻烦了。
那么如何强制按钮在禁用状态下重绘呢?我在按钮上尝试了 .UpdateLayout() ,但没有任何效果。我还尝试了 System.Windows.Forms.DoEvents() ,它在使用 WinForms 时通常有效,但也没有效果。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Windows.Forms 中,您可以使用
Button.Refresh()
。在 Windows.Forms 或 WPF 中,您可以屈服于消息泵以使其重绘。 Async/Await 的设计目的是让您能够做到这一点,而无需 HCL 的回答。
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.
InvalidateVisual();@HCL 是对的...不要这样做就像你说的那样,最好开始使用后台线程/调度程序并保持 UI 线程畅通无阻。考虑查看 Microsoft 的 Reactive Extensions 库,以进行高级异步 UI 编程
InvalidateVisual();@HCL is right... don't do thisLike 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
以下代码将执行您正在寻找的操作。但我不会使用它。使用 BackgroundWorker 类进行长时间操作。它易于使用且非常稳定。
这里是代码:
在这里您将找到有关如何进行的示例使用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:
Here you will find a sample on how to use the BackgroundWorker.