You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何示例代码会再次触发textbox1.Leave()事件,counter值为2?

问题原因分析

这段代码里counter最终为2,核心原因是禁用文本框的操作会再次触发Leave事件:

  1. 第一次触发textbox1_Leave是因为用户手动让文本框失去焦点(比如点击其他控件),此时counter自增到1。
  2. 接着执行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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 22:40:26