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

C# .NET 6 WinForm中TextBox Validating事件无法触发Button点击?

问题解答:TextBox的Validating事件无法触发Button点击的原因

你的代码里按钮点击操作没被触发,核心原因是WinForms的控件验证机制限制:

当TextBox的Validating事件触发时,WinForms正处于控件的验证流程中,此时控件的焦点状态被锁定在验证序列里。而调用button1.PerformClick()本质上会触发焦点切换(按钮会尝试获取焦点),但WinForms为了保证验证流程的完整性,会阻止这种在验证过程中切换焦点的操作,导致按钮的点击逻辑无法正常执行。

如果需要在验证通过后执行按钮操作,可以通过BeginInvoke将点击操作延迟到验证流程结束后执行,修改后的代码示例:

private void textBox1_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
    if (!string.IsNullOrWhiteSpace(textBox1.Text))
    {
        // 延迟执行,避开验证流程的焦点锁定
        BeginInvoke(new Action(() => button1.PerformClick()));
    }
}

内容的提问来源于stack exchange,提问作者Carlos J. Pacheco

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 18:22:00