如何在C#中将"Keys"枚举值转换为"int"字符?

And*_*por 7 c# keydown winforms

这似乎应该很容易,但我很难搞清楚这里需要做些什么.

在"KeyDown"事件处理程序中,如果"e.KeyValue"是一个数字,我想将其视为一个数字并将其存储为int.所以,如果我在数字键盘上点击"8",我不想要"Numpad8"我想要我可以加或减的int值8或者其他什么.

那么,我如何从KeyValue转换为int?

Tom*_*röm 15

我会选择这个解决方案:

int value = -1;
if (e.KeyValue >= ((int) Keys.NumPad0) && e.KeyValue <= ((int) Keys.NumPad9)) { // numpad
    value = e.KeyValue - ((int) Keys.NumPad0);
} else if (e.KeyValue >= ((int) Keys.D0) && e.KeyValue <= ((int) Keys.D9)) { // regular numbers
    value = e.KeyValue - ((int) Keys.D0);
}
Run Code Online (Sandbox Code Playgroud)

...如果要获得被打孔的键的标签的数值.

  • 这段代码中有很多神奇的数字.使用Keys.X枚举更加清晰. (4认同)
  • 为什么不使用枚举代替数字,以便更具可读性?"> =(int)Keys.D0"和"> =(int)Keys.Numpad0"等...... (3认同)

Joh*_*her 5

像这样的东西应该运作良好:(编辑)

int keyVal = (int)e.KeyValue;
int value = -1;
if ((keyVal >= (int)Keys.D0 && keyVal <= (int)Keys.D9)
{
    value = (int)e.KeyValue - (int)Keys.D0;
}
else if (keyVal >= (int)Keys.NumPad0 && keyVal <= (int)Keys.NumPad9)
{
    value = (int)e.KeyValue - (int)Keys.NumPad0;
}
Run Code Online (Sandbox Code Playgroud)


THX*_*138 5

事实:键盘有键.有些键代表数字,有些则代表数字.

问题(改写):如果键表示数字,则产生由键表示的数值.

为了解决这个问题,有必要知道哪些键(所有键中的一组)代表数字以及每个(数字)键代表的精确数值.

据我所知,没有一种简单的方法可以从框架中获得这样的映射.

注意:事实D0-D9和NumPad0-NamPad9在Keys枚举中是顺序的是偶然的,并且依赖于按顺序排序的这些值是没有根据的.

所以解决方案是:

  1. 确定给定的键是否代表数字.
  2. 如果key表示数字,则返回键的数值.

private static readonly IDictionary<Keys, int> NumericKeys = 
    new Dictionary<Keys, int> {
        { Keys.D0, 0 },
        { Keys.D1, 1 },
        { Keys.D2, 2 },
        { Keys.D3, 3 },
        { Keys.D4, 4 },
        { Keys.D5, 5 },
        { Keys.D6, 6 },
        { Keys.D7, 7 },
        { Keys.D8, 8 },
        { Keys.D9, 9 },
        { Keys.NumPad0, 0 },
        { Keys.NumPad1, 1 },
        { Keys.NumPad2, 2 },
        { Keys.NumPad3, 3 },
        { Keys.NumPad4, 4 },
        { Keys.NumPad5, 5 },
        { Keys.NumPad6, 6 },
        { Keys.NumPad7, 7 },
        { Keys.NumPad8, 8 },
        { Keys.NumPad9, 9 }
   };

private int? GetKeyNumericValue(KeyEventArgs e) {
    if (NumericKeys.ContainsKey(e.KeyCode)) return NumericKeys[e.KeyCode];
    else return null;
}
Run Code Online (Sandbox Code Playgroud)

可以说,不是最简单的解决方案,而是密切建模解决方案的解决方案.