我已经通过 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);
}
}