C# .NET 6 WinForm中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
相关产品推荐
相关产品推荐

