如何取消先前聚焦的文本框的焦点
本文关键字:聚焦 文本 焦点 何取消 取消 | 更新日期: 2023-09-27 18:12:32
我有一个文本框,应该只包含数字。检查在Leave事件中进行。如果文本框中包含字符而不是数字,则提示用户检查其输入并再次尝试,同时保持对文本框的关注。
问题是,如果用户按下取消,文本框仍然保持焦点,不能在表单的其他地方单击。如果他删除文本框的内容,也会发生同样的情况。我做错了什么?希望能得到一些帮助!提前感谢!
private void whateverTextBox_Leave(object sender, EventArgs e)
{
//checks to see if the text box is blank or not. if not blank the if happens
if (whateverTextbox.Text != String.Empty)
{
double parsedValue;
//checks to see if the value inside the checkbox is a number or not, if not a number the if happens
if (!double.TryParse(whateverTextbox.Text, out parsedValue))
{
DialogResult reply = MessageBox.Show("Numbers only!" + "'n" + "Press ok to try again or Cancel to abort the operation", "Warning!", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
//if the user presses ok, textbox gets erased, gets to try again
if (reply == DialogResult.OK)
{
whateverTextbox.Clear();
whateverTextbox.Focus();
}
//if the user presses cancel, the input operation will be aborted
else if (reply == DialogResult.Cancel)
{
whateverTextbox.Clear();
//whateverTextbox.Text = String.Empty;
//nextTextBox.Focus();
}
}
}
}
为什么不这样做呢:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && e.KeyChar != (char)Keys.Back)
{
e.Handled = true;
MessageBox.Show("Numbers only!" + "'n" + "Press ok to try again or Cancel to abort the operation", "Warning!");
}
}