pro*_*490 3 c# console-application
我正在尝试System.Windows.Forms.Keys使用以下方法转换为字符串/ char:
KeysConverter converter = new KeysConverter();
string text = converter.ConvertToString(keyCode);
Console.WriteLine(text);
Run Code Online (Sandbox Code Playgroud)
但它返回"OemPeriod"为"." 和"Oemcomma"代表",".有没有办法得到确切的角色?
这可能是你真正想要的(有点迟了,但希望这会帮助其他人),将键码直接转换为键打印的字符.
首先将此指令添加到您的类中:
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int ToUnicode(
uint virtualKeyCode,
uint scanCode,
byte[] keyboardState,
StringBuilder receivingBuffer,
int bufferSize,
uint flags
);
Run Code Online (Sandbox Code Playgroud)
如果您只想忽略shift修改器,请使用此选项
StringBuilder charPressed = new StringBuilder(256);
ToUnicode((uint)keyCode, 0, new byte[256], charPressed, charPressed.Capacity, 0);
Run Code Online (Sandbox Code Playgroud)
现在只需打电话charPressed.ToString()来获取密钥.
如果你想要移位修改器,你可以使用这样的东西来使它更容易
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();
}
Run Code Online (Sandbox Code Playgroud)
小智 7
无论如何,您要尝试实现的目标都不是简单的任务。Windows(例如)使用键盘映射(键盘布局)将键盘按键转换为实际字符。这是我如何实现此目标的方法:
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21253 次 |
| 最近记录: |