2016-08-30 39 views
1

我想我的程序檢查的Windows 10已經被激活如何檢查C#中的Windows許可證狀態?

我有以下代碼

public static bool IsWindowsActivated() 
    { 
     bool activated = true; 
     ManagementScope scope = new ManagementScope(@"\\" + System.Environment.MachineName + @"\root\cimv2"); 
     scope.Connect(); 

     SelectQuery searchQuery = new SelectQuery("SELECT * FROM Win32_WindowsProductActivation"); 
     ManagementObjectSearcher searcherObj = new ManagementObjectSearcher(scope, searchQuery); 

     using (ManagementObjectCollection obj = searcherObj.Get()) 
     { 
      foreach (ManagementObject o in obj) 
      { 
       activated = ((int)o["ActivationRequired"] == 0) ? true : false; 
      } 
     } 
     return activated; 
    } 

嘗試使用此代碼時,調試器抱怨Invalid class,我不知道是什麼是

我該怎麼辦才能解決這個問題?或者有沒有其他方法來檢查Windows的許可證狀態?

+2

在代碼中,您會得到'Invalid class' warning ..? – MethodMan

+0

@ foreach'循環中的@MethodMan –

+0

你在做什麼版本的Windows? –

回答

5

WMI類Win32_WindowsProductActivation僅在Windows XP上受支持。對於Windows 10,您需要使用SoftwareLicensingProduct

public static bool IsWindowsActivated() 
{ 
    ManagementScope scope = new ManagementScope(@"\\" + System.Environment.MachineName + @"\root\cimv2"); 
    scope.Connect(); 

    SelectQuery searchQuery = new SelectQuery("SELECT * FROM SoftwareLicensingProduct WHERE ApplicationID = '55c92734-d682-4d71-983e-d6ec3f16059f' and LicenseStatus = 1"); 
    ManagementObjectSearcher searcherObj = new ManagementObjectSearcher(scope, searchQuery); 

    using (ManagementObjectCollection obj = searcherObj.Get()) 
    { 
     return obj.Count > 0; 
    } 
} 
+0

謝謝!我沒有注意到...... –

+0

在'activated =((int)o [「LicenseStatus」] == 1)中,我仍然收到錯誤,'指定的轉換無效'? true:false;' –

+0

刷新,我剛更新了一個更簡單的檢查。確保你也更新'SelectQuery',查詢改變了。 –