Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert character to the corresponding virtual-key code

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?

Thanks

like image 774
kambamsu Avatar asked May 29 '10 09:05

kambamsu


1 Answers

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.

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
like image 70
João Angelo Avatar answered Oct 31 '22 10:10

João Angelo