Thunderlol
Thunderlol

Reputation: 35

How can I convert a System.Windows.Input.Key to a number?

I'm using an event PreviewKeyDown, and am adding the key in a list of key, as shown in the example below:

    List<Key> keys = new List<Key>();
    private void MDIChildBackground_PreviewKeyDown(object sender, KeyEventArgs e)
    {        

        keys.Add(e.Key);
    }

Then I wanted to take the keys from the list and convert to integer.

Example:

    int number=int.parse(keys[0].ToString());

ps: will only be typed numbers

But the problem is in converting to string because when I type one (1) in keyboard and convert to string the string value is "D1" and not "1". Soon, if I try to convert this string to integer, it will give exception.

Now, how can I handle this?

Upvotes: 3

Views: 3544

Answers (2)

Guillaume Lebeau
Guillaume Lebeau

Reputation: 58

You could use the KeyInterop.VirtualKeyFromKey method to convert a WPF Key into a Win32 Virtual-Key. It will return the integer value of the pressed key.

For example, if you hit the T key it will return 84.

Upvotes: 3

Gareth Wilson
Gareth Wilson

Reputation: 853

If you're sure that you're only dealing with number keys, then the following should work (I'm not that familiar with Windows.Input - is that WPF stuff?);

int Number = -1;

if( keys[0] >= Key.D0 && keys[0] <= Key.D9 )
   Number = keys[0] - Key.D0;

Repeat for other keys in list.

Upvotes: 0

Related Questions