1

我已经通过 Windows WMI 实现了一个远程 hyper-v 管理类,但是ENTER 键的键码是什么。

方法是“PressKey”,类是 Hyper-V WMI 类中的 Msvm_Keyboard。

示例代码在Msvm_Keyboard 类的 PressKey 方法中

上面示例中 ENTER 键的第二个参数是什么?

根据Virtual-Key Codes 表,它必须是“0”或“0x0D”,但本示例不接受这两者!

示例代码:

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);
    }

}
4

1 回答 1

1

我发现了问题。代码“0x0D”对于回车键是正确的,但 Microsoft 示例代码中存在错误。第 40 行Msvm_Keyboard 类的 PressKey 方法

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

上面的演员表不正确,然后我认为虚拟键码不正确。

于 2013-08-05T08:15:35.320 回答