I have made a basic calculator form in visual studio that is fully functional using the mouse click events. I am trying to add keyboard press events so you can use keyboard or mouse but am having trouble figuring it out.
I added some code for the keypress event but it only works if I mouse click the button first then the keyboard event will work, if I mouse select another number it stops working.
//Code that handles click events
private void number_Click(object sender, EventArgs e)
{
if((txtResult.Text == "0")||(operation))
{
txtResult.Clear();
}
//Cast button to the object sender
operation = false;
Button button = (Button)sender;
//If the button pressed is a "." then check if the txtResult already contains
//a ".", if it does contain a "." then do nothing
if (button.Text == ".")
{
if (!txtResult.Text.Contains("."))
{
txtResult.Text = txtResult.Text + button.Text;
}
}else
txtResult.Text = txtResult.Text + button.Text;
}
//Keyboard press event code
private void num1_key(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '1')
{
//If keyboard '1' pressed perform number_click()
btn1.PerformClick();
e.Handled = true;
}
}
Is there anything glaringly obvious Im missing or am I on the wrong track?