为何示例代码会再次触发textbox1.Leave()事件,counter值为2?
问题原因分析
这段代码里counter最终为2,核心原因是禁用文本框的操作会再次触发Leave事件:
- 第一次触发
textbox1_Leave是因为用户手动让文本框失去焦点(比如点击其他控件),此时counter自增到1。 - 接着执行
textbox1.Enabled = false,这个操作会强制textbox1放弃当前的焦点状态——哪怕它已经失去焦点,禁用控件的行为仍会触发焦点变更相关的事件逻辑,这就导致textbox1_Leave被第二次调用,counter再自增到2。
如果要避免这种重复触发,可以通过以下两种简单方式处理:
方式一:添加状态判断标志
int counter = 0; bool isProcessing = false; void textbox1_Leave(object sender, EventArgs e) { if (isProcessing) return; isProcessing = true; counter++; textbox1.Enabled = false; button1.Enabled = false; Console.WriteLine(counter.ToString()); isProcessing = false; }
方式二:临时移除事件绑定
int counter = 0; void textbox1_Leave(object sender, EventArgs e) { counter++; // 先移除事件绑定,避免重复触发 textbox1.Leave -= textbox1_Leave; textbox1.Enabled = false; button1.Enabled = false; Console.WriteLine(counter.ToString()); // 如果后续需要文本框重新可用后仍能触发事件,可重新绑定 // textbox1.Leave += textbox1_Leave; }
内容的提问来源于stack exchange,提问作者Mustafa Vural
相关产品推荐
相关产品推荐

