我该如何将反斜杠键('\')转换为键码?
在我的键盘上,反斜杠的代码是220,但以下方法无法正常工作:
(int)'\\'
返回92。
我需要一些通用的转换,比如
int ConvertCharToKeyValue(char c)
{
// some code here...
}
有什么想法吗?
我该如何将反斜杠键('\')转换为键码?
在我的键盘上,反斜杠的代码是220,但以下方法无法正常工作:
(int)'\\'
返回92。
我需要一些通用的转换,比如
int ConvertCharToKeyValue(char c)
{
// some code here...
}
有什么想法吗?
您可以使用P / Invoke VkKeyScan()将键入的键码转换回虚拟键。请注意,修改键状态很重要,获取“|”需要在我的键盘布局上按住shift键。您的函数签名不允许这样做,所以我只是随便写了个东西:
public static Keys ConvertCharToVirtualKey(char ch) {
short vkey = VkKeyScan(ch);
Keys retval = (Keys)(vkey & 0xff);
int modifiers = vkey >> 8;
if ((modifiers & 1) != 0) retval |= Keys.Shift;
if ((modifiers & 2) != 0) retval |= Keys.Control;
if ((modifiers & 4) != 0) retval |= Keys.Alt;
return retval;
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern short VkKeyScan(char ch);
同时要注意那些需要使用死键(Alt+Gr)才能生成打字键的键盘布局。这种代码最好避免使用。
如果
var char = System.Windows.Forms.Keys.OemPipe; // 220
var code = (int)char;
那么
public static int ToKeyValue(this char ch)
{
return (int)(System.Windows.Forms.Keys)ch;
}
OemPipe
应该是|
,而OemBackslash
应该是\\
。 - PowerlordKeyUp
事件,其中 KeyCode = 220
,这正是 OP 所寻找的。 - abatishchev或者你可以保持简单,进行投射。
(Keys)keyToConvert
我不知道有没有一个函数可以将字符映射到虚拟键代码。但是,您可以使用以下表格来开始构建这样的映射。
http://msdn.microsoft.com/en-us/library/dd375731(v=VS.85).aspx。
请注意,您需要了解键盘,查看您提到的“\”键,这是VK_OEM_5虚拟键,对于美国键盘而言,如果未按Shift,则为“\”,如果按下Shift,则为“|”,因此您的函数还需要知道正在使用的键盘。
当然,如果您想从虚拟键代码映射到字符,则可以使用interop调用MapVirtualKeyEx函数。
更新 根据您的评论,这将给您想要的结果。
[DllImport("user32.dll")]
static extern int MapVirtualKey(int uCode, uint uMapType);
const uint MAPVK_VK_TO_CHAR = 0x02;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
int key = MapVirtualKey((int)e.KeyCode, MAPVK_VK_TO_CHAR);
if (key == (int)'\\')
{
}
}
对于美国标准键盘,'\|' 键
我需要一个与键盘无关的解决方案。最好的解决方案可能是这样的:
public void TextBox_KeyDown(object sender, KeyEventArgs e)
{
if ((String.Parse(e.KeyCode).EndsWith("\\"))...
}
- Murat from Daminion Software