加载表单时禁用按钮,关闭表单时启用按钮
本文关键字:按钮 表单 启用 加载 | 更新日期: 2023-09-27 17:58:06
我想在加载第二个无模式窗体(Form2
)时禁用主窗体上的按钮(button3
),然后在关闭无模式窗体时重新启用该按钮。
以下是我尝试过的:
private void button3_Click(object sender, EventArgs e)
{
Form2 p = new Form2(label1.Text);
p.Show();
if (p.Shown)
this.button3.Click += new System.EventHandler(this.button3_Click);
else
this.button3.Click -= new System.EventHandler(this.button3_Click);
}
实现这一点的最佳方法是在显示Form2
之前禁用button3
,并在表单关闭后使用Form2
上的FormClosed
事件重新启用button3
:
public partial class Form1 : Form
{
...
private void button3_Click(object sender, EventArgs e)
{
// Instantiate the form and assign the FormClosed event
var form = new Form2(label1.Text);
form.FormClosed += Form2_FormClosed;
// Disable button3
button3.Enabled = false;
// Show the form
form.Show();
}
// Occurs when Form2 is closed
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
// Re-enable button3
button3.Enabled = true;
}
}
另一种方法,将lambda表达式分配给FormClosed
事件:
private void button3_Click(object sender, EventArgs e)
{
// Instantiate the form
var form = new Form2(label1.Text);
// Assign a lambda method to the FormClosed event to re-enable button3
form.FormClosed += (s, a) => button3.Enabled = true;
// Disable button3
button3.Enabled = false;
// Show the form
form.Show();
}
我也做过类似的事情,我不确定是否理解你想做什么,但也许这会对你有所帮助。
public partial class Form2 : Form
{
private void button3_Click(object sender, EventArgs e)
{
Button3.Enabled = false;
Form2 p = new Form2(label1.Text);
p.ShowDialog();
//the code will stop here until you finish your work on form2
Button3.Enabled=true;
}
它对我有用。
但如果你的form3只是一个简短的标签使用:
Button3.Enabled= false;
MessageBox.show ("blabla");
Button3.Enabled=true;