keyboard response

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a windows from which I want to react only when the user presses one of
the digits keys (0-9). And every digit key should enter the string "str"
variable. If the user presses the enter key I want the program to make some
additional oparations and when the backspace is pressed I want the last digit
to be removed from the string str.
Unfortunately this doesn't work.
Here is the code:

private void Form1_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
if(e.KeyChar==Convert.ToChar(Keys.Decimal) &&
e.KeyChar!=Convert.ToChar(Keys.Back))
str=str+e.KeyChar.ToString();
if(e.KeyChar==Convert.ToChar(Keys.Back))
str.Remove(str.Length-1,1);
if(e.KeyChar==Convert.ToChar(Keys.Enter))
{
if(Convert.ToDecimal(str)==y*x)
{
MessageBox.Show("Correct");
StopTime();
ChangeStatus();
}
else
MessageBox.Show("WRONG!!!");
}


}
I used the Convert class because it would say it cannot convert a char to a
Keys in the if statements
What should I do?
 
Hi Michael,

In your keypress event, use

if(!Char.IsDigit(e.KeyChar) || e.KeyChar != '\b' || e.KeyChar != '\n' ||
e.KeyChar != dot)
e.Handled = true;

where dot is the decimal point obtained using

char dot =
Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator[0];

.. for US numbers , for at least some European numbers. Then again, if a
decimal point isn't needed, drop this.

Your code isn't working because the if statement only accepts backspace
that is also a numeric character, which never happens.

Note also that any control that accepts input will get focus, so
Form.KeyPress might not be called.
 
Back
Top