如果我知道某个键被按下(例如Key.D3),并且该Shift键也是向下(Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)),我怎么能找出所指的字符(例如,#在美国键盘上,英国键盘上的英镑符号等) ?
换句话说,我怎么能以编程方式找出Shift+ 3产生#(它不会在非美国键盘上).
如果要确定使用给定修饰符从给定键获得的字符,则应使用该user32 ToAscii函数.或者,ToAsciiEx如果您想使用当前键盘布局以外的键盘布局.
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);
}
Run Code Online (Sandbox Code Playgroud)
您现在可以像这样使用它:
char c = User32Interop.ToAscii(Keys.D3, Keys.ShiftKey); // = '#'
Run Code Online (Sandbox Code Playgroud)
如果您需要多个修改器,只需要or它们.Keys.ShiftKey | Keys.AltKey