如何判断TextBox失去焦点是因为点击了CancelButton?
在WinForms场景下,要判断TextBox的Validating事件是否是点击CancelButton(或按Esc键)导致的,有两种可靠的实现方式:
方法一:通过标记变量判断
这种方式逻辑清晰,兼容性强,适用于所有WinForms版本:
- 在窗体类中声明一个私有标记字段:
private bool _isCancelTriggered = false;
- 给CancelButton的Click事件添加处理逻辑,设置标记:
private void btnCancel_Click(object sender, EventArgs e) { _isCancelTriggered = true; // 后续关闭窗体或其他操作可正常执行 }
- 在TextBox的Validating事件中检查标记,区分触发来源:
private void textBox1_Validating(object sender, CancelEventArgs e) { if (_isCancelTriggered) { // 确认是CancelButton触发的验证,跳过校验逻辑 e.Cancel = false; _isCancelTriggered = false; // 重置标记,避免影响后续操作 return; } // 正常的输入校验逻辑 if (string.IsNullOrWhiteSpace(textBox1.Text)) { e.Cancel = true; MessageBox.Show("请输入内容"); } }
方法二:直接判断激活控件或按键状态
无需额外标记,通过检测当前激活控件或按键状态判断:
private void textBox1_Validating(object sender, CancelEventArgs e) { // 检查当前激活控件是否是CancelButton,或是否按下了Esc键 bool isCancelAction = this.ActiveControl == this.CancelButton || IsEscapeKeyPressed(); if (isCancelAction) { e.Cancel = false; return; } // 正常校验逻辑 if (string.IsNullOrWhiteSpace(textBox1.Text)) { e.Cancel = true; MessageBox.Show("请输入内容"); } } // 辅助方法:检测Esc键是否按下 [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern short GetAsyncKeyState(Keys vKey); private bool IsEscapeKeyPressed() { return (GetAsyncKeyState(Keys.Escape) & 0x8000) != 0; }
注意:方法二中的
this.ActiveControl判断仅对鼠标点击CancelButton的场景有效,结合IsEscapeKeyPressed才能覆盖按Esc触发CancelButton的情况。
内容的提问来源于stack exchange,提问作者Tony H
相关产品推荐
相关产品推荐

