将键代码转换为char/string
本文关键字:char string 转换 代码 | 更新日期: 2023-09-27 17:59:04
我正在尝试使用将System.Windows.Forms.Keys
转换为字符串/字符
KeysConverter converter = new KeysConverter();
string text = converter.ConvertToString(keyCode);
Console.WriteLine(text);
但它为"."返回"OemPeriod",为","返回"Oemcomma"。有什么方法可以得到确切的字符吗?
您试图实现的目标绝非易事。窗口(例如)使用键盘映射(键盘布局)将键盘键转换为实际字符。以下是我实现这一目标的方法:
public string KeyCodeToUnicode(Keys key)
{
byte[] keyboardState = new byte[255];
bool keyboardStateStatus = GetKeyboardState(keyboardState);
if (!keyboardStateStatus)
{
return "";
}
uint virtualKeyCode = (uint)key;
uint scanCode = MapVirtualKey(virtualKeyCode, 0);
IntPtr inputLocaleIdentifier = GetKeyboardLayout(0);
StringBuilder result = new StringBuilder();
ToUnicodeEx(virtualKeyCode, scanCode, keyboardState, result, (int)5, (uint)0, inputLocaleIdentifier);
return result.ToString();
}
[DllImport("user32.dll")]
static extern bool GetKeyboardState(byte[] lpKeyState);
[DllImport("user32.dll")]
static extern uint MapVirtualKey(uint uCode, uint uMapType);
[DllImport("user32.dll")]
static extern IntPtr GetKeyboardLayout(uint idThread);
[DllImport("user32.dll")]
static extern int ToUnicodeEx(uint wVirtKey, uint wScanCode, byte[] lpKeyState, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszBuff, int cchBuff, uint wFlags, IntPtr dwhkl);
这可能是您真正想要的(有点晚了,但希望这能帮助其他人),将键代码直接转换为键打印的字符。
首先将此指令添加到您的类中:
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int ToUnicode(
uint virtualKeyCode,
uint scanCode,
byte[] keyboardState,
StringBuilder receivingBuffer,
int bufferSize,
uint flags
);
如果你只想忽略移位修饰符,那么就用这个
StringBuilder charPressed = new StringBuilder(256);
ToUnicode((uint)keyCode, 0, new byte[256], charPressed, charPressed.Capacity, 0);
现在只需致电charPressed.ToString()
即可获取您的钥匙。
如果你想要shift修饰符,你可以使用这样的东西来简化
static string GetCharsFromKeys(Keys keys, bool shift)
{
var buf = new StringBuilder(256);
var keyboardState = new byte[256];
if (shift)
{
keyboardState[(int)Keys.ShiftKey] = 0xff;
}
ToUnicode((uint)keys, 0, keyboardState, buf, 256, 0);
return buf.ToString();
}
由于问题标签中有"控制台应用程序",请尝试此
ConsoleKeyInfo input = Console.ReadKey(true);
StringBuilder output = new StringBuilder(
String.Format("You pressed {0}", input.KeyChar));
Console.WriteLine(output.ToString());
这些是键盘上逗号和句点键的正确名称和预期名称。您可以从文档中清楚地看到这一点。KeysConverter
类的行为符合预期和设计。
如果你想为这些密钥想出一个不同的名称,你可以检测它们并替换你想要使用的名称。例如:
string name;
switch (e.KeyCode)
{
case Keys.Oemcomma:
name = "Comma";
break;
case Keys.OemPeriod:
name = "Period";
break;
default:
name = (new KeysConverter()).ConvertToString(e.KeyCode);
break;
}