简体   繁体   English

如何在 C# 中将按键转换为 int

[英]How To Convert Pressed Key to int in C#

I want to convert pressed key to int and put in an int variable.我想将按键转换为 int 并放入一个int变量。 I'm trying to get pressed key and convert to int to use it to change a text or set that text to it.我正在尝试按下键并转换为 int 以使用它来更改文本或将该文本设置为它。

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:例如,在textbox键按下事件中,我尝试了此操作,但通常它会获取 D1 或 D2 或...当我按下数字键而不工作时:

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.我建议结合使用 KeyDown 和 KeyPress 事件。 For all the simple keys (excluding Ctrl, Shift etc), KeyPress event will give you the character itself and no need to convert it then.对于所有简单的键(不包括 Ctrl、Shift 等),KeyPress 事件将为您提供字符本身,然后无需对其进行转换。 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.例如,当您按数字 2 而不是 D2 时,e.KeyChar 会给您 2。 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.您可以使用 KeyDown 来记录 Ctrl、Alt 和 Shift 等键。例如,当您按下数字或字母时,应用程序将同时调用 KeyDown 和 KeyPress。 It just makes your code very simple rather than having IF checks for D0,D1 ....D9.它只是让您的代码非常简单,而不是让 IF 检查 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.并且因为 KeyChar 会为您提供字符本身,所以如果您需要进一步转换它,您可以轻松检查它是数字还是字母。

Hope it helps.希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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