我想让计算器只能用键盘工作。 如果我在textbox1上按(+, - ,,/),我想对组合框做出反应 但问题是当我按下键盘上的(+, - ,,/)时,它不起作用。 我该如何解决这个问题?
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "+")
{
int tmp = int.Parse(textBox1.Text) + int.Parse(textBox2.Text);
textBox3.Text = tmp.ToString();
}
if (comboBox1.SelectedItem.ToString() == "-")
{
int tmp = int.Parse(textBox1.Text) - int.Parse(textBox2.Text);
textBox3.Text = tmp.ToString();
}
if (comboBox1.SelectedItem.ToString() == "*")
{
int tmp = int.Parse(textBox1.Text) * int.Parse(textBox2.Text);
textBox3.Text = tmp.ToString();
}
if (comboBox1.SelectedItem.ToString() == "/")
{
int tmp = int.Parse(textBox1.Text) / int.Parse(textBox2.Text);
textBox3.Text = tmp.ToString();
}
}
private void Form1_Shown(object sender, EventArgs e)
{
textBox1.Focus();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e .KeyCode == Keys.Add )
{
comboBox1.Text = "+";
textBox2.Focus();
textBox2.SelectAll();
}
if (e .KeyCode == Keys.Subtract )
{
comboBox1.Text = "-";
textBox2.Focus();
textBox2.SelectAll();
}
if (e .KeyCode == Keys.Multiply )
{
comboBox1.Text = "*";
textBox2.Focus();
textBox2.SelectAll();
}
if (e .KeyCode == Keys.Divide )
{
comboBox1.Text = "/";
textBox2.Focus();
textBox2.SelectAll();
}
}
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if (e .KeyCode == Keys.Enter )
{
this.button1_Click(sender, e);
textBox1.Focus();
textBox1.SelectAll();
}
}
}
我想只在键盘上工作,当我在textbox1上按(+, - ,*,/)时,焦点需要改变comboBox去textbox2。
答案 0 :(得分:0)
只有当您从键盘的小键盘上发送+,-,*,/
时,您的代码才有效。
将您的textBox1_KeyDown
更改为textBox1_KeyPress
事件。这使您能够从键盘(+,-,*,/
)检查输入字符:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '+')
{
comboBox1.Text = "+";
textBox2.Focus();
textBox2.SelectAll();
}
else if (e.KeyChar == '-')
{
comboBox1.Text = "-";
textBox2.Focus();
textBox2.SelectAll();
}
else if (e.KeyChar == '*')
{
comboBox1.Text = "*";
textBox2.Focus();
textBox2.SelectAll();
}
else if (e.KeyChar == '/')
{
comboBox1.Text = "/";
textBox2.Focus();
textBox2.SelectAll();
}
}