Convert A Char To Keys

2019-04-07 06:28发布

I have a special char (/ @) That I want to convert to Keys.

I am currently using this :

Keys k = (Keys)'/';

And while debugging, I get that k equals to :

LButton | RButton | MButton | Back | Space type - System.Windows.Forms.Keys

k's keycode was suppose to be 111.

NOTE: The code does work for uppercase letters such as :

Keys k = (Keys)'Z';

In that case, k's key code is 90, which is ok.

I'm trying to find a way to convert special chars to Keys. (or to their proper key code)

Trying to send keys globally using :

public static void SendKey(byte keycode)
    {
        const int KEYEVENTF_EXTENDEDKEY = 0x1;
        const int KEYEVENTF_KEYUP = 0x2;
        keybd_event(keycode, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr)0);
        keybd_event(keycode, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, (UIntPtr)0);
    }

SendKey((byte)Keys.{SomethingHere});

6条回答
看我几分像从前
2楼-- · 2019-04-07 06:42

It's old question, but I used this:

Keys k = (Keys)char.ToUpper(c);

If char value is a (with code 97) then converting into A (with code 65) maps to Keys.A and so on...

Hope this will help someone.

查看更多
混吃等死
3楼-- · 2019-04-07 06:51

It should work!

Keys o = (Keys)Enum.Parse(typeof(Keys), ((int)e.KeyChar).ToString());

查看更多
Root(大扎)
4楼-- · 2019-04-07 07:00

As far as I know there is no way to map the Keys enumeration to char. One specifies key codes and modifiers, useful for System.Windows.Forms.Control while the other represents a 16 bit Unicode character (U+0000 to U+ffff).

To alltogether different concepts.

查看更多
forever°为你锁心
5楼-- · 2019-04-07 07:00

In my opinion this the ideal solution in terms of readability.

Keys key = (Keys) Enum.Parse(typeof(Keys), c.ToString(), ignoreCase: true);
查看更多
男人必须洒脱
6楼-- · 2019-04-07 07:02

You can't cast from char to Keys. Keys is a flags enumeration that represents which physical keys are pressed on the keyboard. What you are trying might not be a straightforward problem to solve. Who's to say what keyboard the user used and what mapping generates what particular character on the user's keyboard and their locale?

Can you be more specific about your goal? Are you trying to teach a user how to type a special character or something else?

Based on your update, you should be using the SendKeys class.

查看更多
混吃等死
7楼-- · 2019-04-07 07:03

My way only works with letters and some other keys.

string s = char.ToString(e.KeyChar);

This gives you string of Keys equivalent. Something like output of Keys.ToString(). So all we need that converting s to its Keys equivalent!

(Keys) Enum.Parse(typeof(Keys), char.ToString(e.KeyChar).ToUpper());

good luck...

查看更多
登录 后发表回答