2013-08-04 91 views
1

我已經通過windows WMI實現了一個遠程hyper-v管理類,但是對於ENTER鍵,keycode是什麼。
該方法是「PressKey」,類是Hyper-V WMI類中的Msvm_Keyboard類。
示例代碼是PressKey method of the Msvm_Keyboard class
上面示例中的ENTER鍵的第二個參數是什麼?
根據Virtual-Key Codes table它必須是「0」或「0x0D」,但它們都不被這個樣本接受!什麼是ENTER鍵的虛擬鍵碼?

示例代碼:

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

} 
+0

你是什麼意思「不可接受的樣本」?你是否遇到編譯器錯誤或運行時問題? –

+0

只需將常量'VK_RETURN'放在那裏,並告訴我們什麼不起作用。 –

回答

0

我已經發現這個問題。代碼「0x0D」對於輸入密鑰是正確的,但是Microsoft示例代碼中存在錯誤。 PressKey method of the Msvm_Keyboard class
在第40行:

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

上面鑄是不正確的話,我認爲虛擬鍵碼不正確。