Search code examples
c#charkeyspecial-characters

Convert A Char To Keys


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});

Solution

  • 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.