好的,我希望用户能够在文本框输入期间按 Enter 键来启动单击按钮。
我有以下代码:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyValue == 13)
{
button3_Click(sender, e);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
this.textBox1.KeyUp += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown);
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("Please enter a value.", "No name entered", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
if (listBox1.Items.Contains(textBox1.Text) == true)
{
MessageBox.Show("You have tried to enter a duplicate.", "No duplicates allowed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
listBox1.Items.Add(textBox1.Text);
textBox1.Text = "";
}
}
}
但是,当我按 Enter 键时,值会保存,然后 MessageBox 出现大约 4 次“请输入值”。如何使此代码使 button_click 仅在按 Enter 时发生一次?
有没有更简单的方法来做到这一点?
谢谢!