简体   繁体   中英

How To Convert Pressed Key to int in C#

I want to convert pressed key to int and put in an int variable. I'm trying to get pressed key and convert to int to use it to change a text or set that text to it.

For example in a textbox key down event I tried this but ussually it gets the D1 or D2 or... when I press the number keys and not working:

private void txtNumberOfPositions_KeyDown(object sender, KeyEventArgs e)
{
      char PressedKeyForSettingNumberOfPositionsChar = (char)e.KeyCode;

      int PressedKeyForSettingNumberOfPositionsInt = Convert.ToInt32(PressedKeyForSettingNumberOfPositionsChar);

      if (PressedKeyForSettingNumberOfPositionsInt >= 0 && PressedKeyForSettingNumberOfPositionsInt <= 10)
         txtNumberOfPositions.Text = PressedKeyForSettingNumberOfPositionsInt.ToString();
}

I will suggest using a combination of KeyDown and KeyPress events. For all the simple keys (excluding Ctrl, Shift etc), KeyPress event will give you the character itself and no need to convert it then. Example:

private void txInterval_KeyPress(object sender, KeyPressEventArgs e)
        {
            char c = e.KeyChar;
        }

Here e.KeyChar will give you 2 when you press number 2 and not D2 for example. You can use KeyDown to record the keys for Ctrl, Alt and Shift etc. The application will call both KeyDown and KeyPress when you press a numeric or alphabet for example. It just makes your code very simple rather than having IF checks for D0,D1 ....D9. And because KeyChar will give you the character itself, you can easily check if it is a numeric or alphabet if you need to convert this further.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM