gpt4 book ai didi

C# 窗体 : selective disabling of UI whilst a thread runs

转载 作者:太空狗 更新时间:2023-10-30 01:24:32 24 4
gpt4 key购买 nike

我有一个非常复杂的表单,它提供了运行脚本(我们自己的类型)的选项。当它运行时,我不想完全锁定 UI,所以我想在一个线程中启动它。到目前为止一切顺利,但为了防止用户弄乱我需要有选择地禁用部分 UI 的东西。我可以递归地设置 Enabled = false,然后在线程结束时设置 Enabled = true。但这忽略了运行时控件的状态(即由于各种原因被禁用的控件将被错误地重新启用)。除了构建 bool 树之外,是否还有其他方法来阻止输入(例如 Java 中的 GlassPane 类型)?

最佳答案

不要使用DoEvents,它是evil .

使用面板并在其中添加要禁用的所有控件。当面板将被禁用时,所有内部控件都将被禁用,但它们的 Enabled 属性的值实际上不会被修改。

这是一个工作示例:

    public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
// Disables UI elements using the panel
this.SetPanelEnabledProperty(false);

// Starts the background work
System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(this.Worker));
}

private void Worker(object state)
{
// Simulates some work
System.Threading.Thread.Sleep(2000);

// Now the work is done, enable the panel
this.SetPanelEnabledProperty(true);
}

private void SetPanelEnabledProperty(bool isEnabled)
{
// InvokeRequired is used to manage the case the UI is modified
// from another thread that the UI thread
if (this.panel1.InvokeRequired)
{
this.panel1.Invoke(new MethodInvoker(() => this.SetPanelEnabledProperty(isEnabled)));
}
else
{
this.panel1.Enabled = isEnabled;
}
}
}

关于C# 窗体 : selective disabling of UI whilst a thread runs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9003175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com