user986166
user986166

Reputation: 21

What is virtual-key code for the ENTER Key?

I have implemented a remote hyper-v management class through windows WMI but what is the keycode for ENTER key.

The method is "PressKey" and the class is Msvm_Keyboard in Hyper-V WMI Classes.

sample code is in PressKey method of the Msvm_Keyboard class

What is the second argument for ENTER key in above sample?

According to Virtual-Key Codes table it must be "0" or "0x0D" but both of them are not acceptable by this sample!

Sample code:

class PressKeyClass
{
    static ManagementObject GetComputerKeyboard(ManagementObject vm)
    {
        ManagementObjectCollection keyboardCollection = vm.GetRelated
        (
            "Msvm_Keyboard",
            "Msvm_SystemDevice",
            null,
            null,
            "PartComponent",
            "GroupComponent",
            false,
            null
        );

        ManagementObject keyboard = null;

        foreach (ManagementObject instance in keyboardCollection)
        {
            keyboard = instance;
            break;
        }

        return keyboard;
    }

    static void PressKey(string vmName, int keyCode)
    {
        ManagementScope scope = new ManagementScope(@"root\virtualization", null);
        ManagementObject vm = Utility.GetTargetComputer(vmName, scope);
        ManagementObject keyboard = GetComputerKeyboard(vm);

        ManagementBaseObject inParams = keyboard.GetMethodParameters("PressKey");

        inParams["keyCode"] = keyCode;

        ManagementBaseObject outParams = keyboard.InvokeMethod("PressKey", inParams, null);

        if ((UInt16)outParams["ReturnValue"] == ReturnCode.Completed)
        {
            string.Format("Key {0} was pressed on {1}", keyCode, vm["ElementName"]);
        }
        else
        {
            string.Format("Unable to press key {0}' on {1}", keyCode, vm["ElementName"]);
        }

        inParams.Dispose();
        outParams.Dispose();
        keyboard.Dispose();
        vm.Dispose();
    }

    static void Main(string[] args)
    {
        if (args != null && args.Length != 2)
        {
            Console.WriteLine("Usage: PressKey vmName keyCode");
            return;
        }
        string vmName = args[0];
        int keyCode = int.Parse(args[1]);
        PressKey(args[0], keyCode);
    }

}

Upvotes: 1

Views: 2803

Answers (1)

user986166
user986166

Reputation: 21

i have found the problem. the code "0x0D" is correct for enter key but there is an error in Microsoft sample code. PressKey method of the Msvm_Keyboard class
in line 40:

if ((UInt16)outParams["ReturnValue"] == ReturnCode.Completed)

the above cast is incorrect then i thought the Virtual Key-code is incorrect.

Upvotes: 1

Related Questions