如何在 C# 中将按下的键转换为 int
How To Convert Pressed Key to int in C#
我想将按下的键转换为 int 并放入一个 int
变量。
我正在尝试按下按键并将其转换为 int 以使用它来更改文本或将文本设置为它。
例如,在 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();
}
我建议结合使用 KeyDown 和 KeyPress 事件。对于所有简单的键(不包括 Ctrl、Shift 等),KeyPress 事件将为您提供字符本身,无需转换。示例:
private void txInterval_KeyPress(object sender, KeyPressEventArgs e)
{
char c = e.KeyChar;
}
此处 e.KeyChar 会在您按数字 2 而不是 D2 时给您 2。您可以使用 KeyDown 记录 Ctrl、Alt 和 Shift 等键。例如,当您按下数字或字母时,应用程序将同时调用 KeyDown 和 KeyPress。它只是使您的代码非常简单,而不是对 D0、D1 ....D9 进行 IF 检查。因为 KeyChar 会给你字符本身,如果你需要进一步转换它,你可以很容易地检查它是数字还是字母。
希望对您有所帮助。
我想将按下的键转换为 int 并放入一个 int
变量。
我正在尝试按下按键并将其转换为 int 以使用它来更改文本或将文本设置为它。
例如,在 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();
}
我建议结合使用 KeyDown 和 KeyPress 事件。对于所有简单的键(不包括 Ctrl、Shift 等),KeyPress 事件将为您提供字符本身,无需转换。示例:
private void txInterval_KeyPress(object sender, KeyPressEventArgs e)
{
char c = e.KeyChar;
}
此处 e.KeyChar 会在您按数字 2 而不是 D2 时给您 2。您可以使用 KeyDown 记录 Ctrl、Alt 和 Shift 等键。例如,当您按下数字或字母时,应用程序将同时调用 KeyDown 和 KeyPress。它只是使您的代码非常简单,而不是对 D0、D1 ....D9 进行 IF 检查。因为 KeyChar 会给你字符本身,如果你需要进一步转换它,你可以很容易地检查它是数字还是字母。
希望对您有所帮助。