.net NET中的键盘映射
如果我知道某个键被按下了(例如,.net NET中的键盘映射,.net,keyboard,.net,Keyboard,如果我知道某个键被按下了(例如,key.D3),并且Shift键也被按下了(Keyboard.IsKeyDown(key.LeftShift)| Keyboard.IsKeyDown(key.RightShift)),我怎么才能知道它指的是什么字符(例如,美国键盘上的#,英国键盘上的英镑符号等等) 换句话说,我如何通过编程发现Shift+3产生#(在非美国键盘上不会)。如果您想确定使用给定的修改器从给定的键中获得什么字符,应该使用该函数。或者,如果要使用当前布局以外的键盘布局 using Sys
key.D3
),并且Shift键也被按下了(Keyboard.IsKeyDown(key.LeftShift)| Keyboard.IsKeyDown(key.RightShift)
),我怎么才能知道它指的是什么字符(例如,美国键盘上的#,英国键盘上的英镑符号等等)
换句话说,我如何通过编程发现Shift+3产生#(在非美国键盘上不会)。如果您想确定使用给定的修改器从给定的键中获得什么字符,应该使用该函数。或者,如果要使用当前布局以外的键盘布局
using System.Runtime.InteropServices;
public static class User32Interop
{
public static char ToAscii(Keys key, Keys modifiers)
{
var outputBuilder = new StringBuilder(2);
int result = ToAscii((uint)key, 0, GetKeyState(modifiers),
outputBuilder, 0);
if (result == 1)
return outputBuilder[0];
else
throw new Exception("Invalid key");
}
private const byte HighBit = 0x80;
private static byte[] GetKeyState(Keys modifiers)
{
var keyState = new byte[256];
foreach (Keys key in Enum.GetValues(typeof(Keys)))
{
if ((modifiers & key) == key)
{
keyState[(int)key] = HighBit;
}
}
return keyState;
}
[DllImport("user32.dll")]
private static extern int ToAscii(uint uVirtKey, uint uScanCode,
byte[] lpKeyState,
[Out] StringBuilder lpChar,
uint uFlags);
}
您现在可以这样使用它:
char c = User32Interop.ToAscii(Keys.D3, Keys.ShiftKey); // = '#'
如果您需要多个修饰符,只需
或它们即可Keys.ShiftKey | Keys.AltKey
是的,但为什么?(不要回答这个问题)。我怎样才能从程序上发现Shift+Key.D3会产生“#”(在非美国键盘上不会)。哦,也许你应该改进你的问题以明确这一点。找到了一个解决方案,让我改变答案,看起来像是赢家!谢谢。嗯,我想这不是一个非常常用的函数,WinForms团队也没有优先考虑包装它。至少你可以一直使用PInvoke Win32代码。用解决方案更新我的答案,干杯。