字符转换到相应的虚拟键码 [英] Convert character to the corresponding virtual-key code

查看:593
本文介绍了字符转换到相应的虚拟键码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我使用Win32 API中的方法 VkKeyScan 来一个字符的虚拟键代码转换。不过,这似乎有问题是,当我通过小字母,它而当我在一个英文大写字母来传递,它不与特殊字符,如返回相应的键码,同样工作正常(或}

Currently, I'm using the method VkKeyScan in the Win32 API to convert a character to its virtual-key code. But the problem that this seems to have is that, when i pass small alphabets, it works fine whereas when i pass in a capital alphabet, it doesn't return the appropriate key code and similarly with special characters like "(" or "}".

我该怎么办呢?反正对我来说,直接字符串转换为它的虚拟相当于不考虑其是否包含大写或特殊字符?

How do i do this? Is there anyway for me to directly convert a string to its virtual equivalent without considering whether it contains capitalized or special characters?

感谢

推荐答案

您应该是更清楚你的要求是什么,更具体你认为什么是适当的键码, VkKeyScan 按规定在它的documentation 返回的低位字节,并在返回值的高字节移位状态的虚拟键码。

You should be clearer in what your requirements are, more specifically in what you consider to be an appropriate key code. The VkKeyScan as specified in it's documentation returns the virtual-key code in the low-order byte and the shift state in the high-byte of the return value.

这是表现在下面的代码片段使用了字符作为 VkKeyScan

This is demonstrated in the code snippet below that uses the '(' character as input for the VkKeyScan method.

[DllImport("user32.dll")]static extern short VkKeyScan(char ch);

static void Main(string[] args)
{
    var helper = new Helper { Value = VkKeyScan('(') };

    byte virtualKeyCode = helper.Low;
    byte shiftState = helper.High;

    Console.WriteLine("{0}|{1}", virtualKeyCode, (Keys)virtualKeyCode);
    Console.WriteLine("SHIFT pressed: {0}", (shiftState & 1) != 0);
    Console.WriteLine("CTRL pressed: {0}", (shiftState & 2) != 0);
    Console.WriteLine("ALT pressed: {0}", (shiftState & 4) != 0);
    Console.WriteLine();

    Keys key = (Keys)virtualKeyCode;

    key |= (shiftState & 1) != 0 ? Keys.Shift : Keys.None;
    key |= (shiftState & 2) != 0 ? Keys.Control : Keys.None;
    key |= (shiftState & 4) != 0 ? Keys.Alt : Keys.None;

    Console.WriteLine(key);
    Console.WriteLine(new KeysConverter().ConvertToString(key));
}

[StructLayout(LayoutKind.Explicit)]
struct Helper
{
    [FieldOffset(0)]public short Value;
    [FieldOffset(0)]public byte Low;
    [FieldOffset(1)]public byte High;
}



运行这个片段将导致以下的输出:

Running this snippet will result in the following output:

// 56|D8
// SHIFT pressed: True
// CTRL pressed: False
// ALT pressed: False
// 
// D8, Shift
// Shift+8

这篇关于字符转换到相应的虚拟键码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆