我发现在构建 Windows Mobile 应用程序时经常需要这样做,所以制作了一个简单的实用程序类。
public static class FormUtility
{
/// <summary>
/// Lock the form whilst processing
/// </summary>
/// <param name="controlCollection"></param>
/// <param name="enabled"></param>
public static void FormState(Control.ControlCollection controlCollection, bool enabled)
{
foreach (Control c in controlCollection)
{
c.Enabled = enabled;
c.Invalidate();
c.Refresh();
}
}
}
然后我需要做的就是调用一行来锁定表单。
FormUtility.FormState(this.Controls, false);
你应该得到类似的东西
private void btnSave_Click(object sender, EventArgs e)
{
FormUtility.FormState(this.Controls, false);
//Do your work
if (!SaveSuccessful())
//Renable if your validation failed
FormUtility.FormState(this.Controls, true);
}
编辑:我认为@tcarvin 的建议是您不需要在每个控件上调用刷新,而只需使控件无效,然后刷新容器,这将导致所有无效控件立即重绘。我还没有测试过这个,但是对类似的东西做了一个小改动......
public static void FormState(Form form, bool enabled)
{
foreach (Control c in form.Controls)
{
c.Enabled = enabled;
c.Invalidate();
}
form.Refresh();
}
然后使用
FormUtility.FormState(this, true);