How do I convert a “Keys” enum value to an “int” c

2019-04-26 15:51发布

This seems like something that should be easy, but I am having a tough time figuring out what needs to happen here.

In the "KeyDown" eventhandler, if the "e.KeyValue" is a number, I want to treat it as a number and store it as an int. So, if I hit "8" on the number pad, I don't want "Numpad8" I want the int value 8 that I can add or subtract or whatever.

So, how do I convert from the KeyValue to an int?

10条回答
混吃等死
2楼-- · 2019-04-26 16:35

The KeyValue represents the character code for the key that was pressed. In order to obtain its numerical valaue you should find the character for the key that was pressed, then parse it from a character to an integer.

Something like Convert.ToInt32(e.KeyCode.ToString())

查看更多
成全新的幸福
3楼-- · 2019-04-26 16:38

Depending on how many keys you are keeping track of, the simplest method would be for you to create a select case (or switch statement in C# I guess?) that would check the value of your keydown and depending upon that value assign a value to an integer that is appropriate.

查看更多
Ridiculous、
4楼-- · 2019-04-26 16:39

Something like this should work well: (Edited)

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;
}
查看更多
Anthone
5楼-- · 2019-04-26 16:40

If you want NUMERIC values, you'll have to create a switch(e.KeyCode) statement and evaluate the key and create your own int. There's no simple way to turn a Keys into a numeric value that represents the number on the key. The closest you could get might be the ASCII equivalent, which would still need to be translated.

查看更多
淡お忘
6楼-- · 2019-04-26 16:40

Could you just listen for the KeyPress event instead? It will give the character that was actually pressed.

查看更多
疯言疯语
7楼-- · 2019-04-26 16:41

This function will do what you want:

private int GetKeyValue(int keyValue)
{
    if (keyValue >= 48 && keyValue <= 57)
    {
        return keyValue - 48;
    }
    else if (keyValue >= 96 && keyValue <= 105)
    {
        return keyValue - 96;
    }
    else
    {
        return -1; // Not a number... do whatever...
    }
}

Call it like so:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    int num = GetKeyValue(e.KeyValue);  
}
查看更多
登录 后发表回答