Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

c# - How to convert a character to key code?

How can I convert backslash key ('') to key code?

On my keyboard backslash code is 220, but the method below

(int)'\'

returns me 92.

I need some generic conversion like

 int ConvertCharToKeyValue(char c)
 {
     // some code here...
 }

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can P/Invoke VkKeyScan() to convert a typing key code back to a virtual key. Beware that the modifier key state is important, getting "|" requires holding down the shift key on my keyboard layout. Your function signature doesn't allow for this so I just made something up:

public static Keys ConvertCharToVirtualKey(char ch) {
    short vkey = VkKeyScan(ch);
    Keys retval = (Keys)(vkey & 0xff);
    int modifiers = vkey >> 8;

    if ((modifiers & 1) != 0) retval |= Keys.Shift;
    if ((modifiers & 2) != 0) retval |= Keys.Control;
    if ((modifiers & 4) != 0) retval |= Keys.Alt;

    return retval;
}

[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern short VkKeyScan(char ch);

Also beware of keyboard layouts that need to use dead keys (Alt+Gr) to generate typing keys. This kind of code is really best avoided.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...