问题描述
我正在尝试使用以下命令将 System.Windows.Forms.Keys
转换为字符串/字符:
I'm trying to convert System.Windows.Forms.Keys
to string/char using :
KeysConverter converter = new KeysConverter();
string text = converter.ConvertToString(keyCode);
Console.WriteLine(text);
但是它返回 OemPeriod作为。 Oemcomma代表,。有什么方法可以获取确切的字符?
But it returned "OemPeriod" for "." and "Oemcomma" for ",". Is there any way to get the exact character?
推荐答案
这可能是您真正想要的(有点晚了,但是希望这会
This is probably what you really want (bit late, but hope this will help someone else), converting the keycode directly to the character the key prints.
首先将此指令添加到您的类中:
First add this directive into your class:
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int ToUnicode(
uint virtualKeyCode,
uint scanCode,
byte[] keyboardState,
StringBuilder receivingBuffer,
int bufferSize,
uint flags
);
然后,如果您只想忽略换档修饰符,请使用此选项
Then use this if you just want to ignore the shift modifier
StringBuilder charPressed = new StringBuilder(256);
ToUnicode((uint)keyCode, 0, new byte[256], charPressed, charPressed.Capacity, 0);
现在只需调用 charPressed.ToString()
如果想要使用shift修饰符,可以使用类似的方法使其变得更简单
If you want the shift modifier, you can use something like this to make it easier
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();
}
这篇关于将键码转换为char / string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!