【发布时间】:2021-07-08 03:37:49
【问题描述】:
我有一个按钮,在Click 事件中,我对Form 中的一些TextBoxes 进行了一些验证。
如果TextBox 没有通过验证,那么我强制将Focus 输入它(用户必须在TextBox 中输入一些字符)。如果用户按下 Enter 键,我的 TextBox 类已经有一些代码可以转到下一个控件。
MyTextBox.cs 类
public class MyTextBox : TextBox
{
public MyTextBox(){
KeyUp += MyTextBox_KeyUp;
KeyDown += MyTextBox_KeyDown;
}
private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// This will suppress Blink sound
e.SuppressKeyPress = true;
}
}
private void MyTextBox_KeyUp(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
{
// This will go to the next control if Enter will be pressed.
SendKeys.Send("{TAB}");
}
}
}
表单的按钮点击事件:
private void BtnPrint_Click(object sender, EventArgs e){
// txtName is based on MyTextBox class
if(txtName.Text.Length == 0){
MessageBox.Show("Name field could not be empty! Please fill the Name!", "Error Message",
MessageBoxButtons.OK, MessageBoxIcon.Error);
// If I Click the OK button, txtName will stay focused in the next line,
// but if I press Enter key, it will go to the next control.
txtName.Focus();
return;
}
// Some other validations ...
// Calling printing method ...
}
当用户在 MessageBox 中按 Enter 键时,我如何停止失去对文本框的关注?
【问题讨论】:
标签: c# winforms messagebox