Can someone please explain the purpose of this C# code. It's a code snippet in a Windows based application. Is it counting the number of keypress? What is the purpose of 13 here?
Any help would be much appreciated
private void num2_KeyPress(object sender, KeyPressEventArgs e)
{
if ((int) e.KeyChar != 13)
return;
this.Calculate();
}
That code is unfortunately written - KeyPressEventArgs.KeyChar
basically returns the character pressed (so shift-a will return 'A' for example). 13 is just the Unicode character for "carriage return" which is returned when the user hits return. I would have written that method as:
// Possibly rename to CalculateIfReturnIsPressed or something similar.
private void num2_KeyPress(object sender, KeyPressEventArgs e)
{
// Perform the calculation if the user hit return
if (e.KeyChar == '\r')
{
Calculate();
}
}
\r
is the same character as (char) 13
.
See more on this question at Stackoverflow