2016-01-13 49 views

回答

1

GetProductInfo API function返回該信息。

using System; 
using System.Runtime.InteropServices; 
using System.Text; 

namespace ConsoleApplication4 
{ 
    public class Program 
    { 
    [DllImport("kernel32.dll", SetLastError = true)] 
    internal static extern Boolean GetProductInfo(
     Int32 dwOSMajorVersion, 
     Int32 dwOSMinorVersion, 
     Int32 dwSpMajorVersion, 
     Int32 dwSpMinorVersion, 
     out Int32 pdwReturnedProductType); 

    [DllImport("Kernel32.dll", CharSet = CharSet.Auto, EntryPoint = "FormatMessage", SetLastError = true)] 
    internal static extern Int32 FormatMessage(
     Int32 flags, 
     IntPtr source, 
     Int32 messageId, 
     Int32 languageId, 
     StringBuilder buffer, 
     Int32 size, 
     IntPtr arguments); 

    public static void Main(String[] args) 
    { 
     /* Other product codes can be found on the help page for 
     the GetProductInfo API function: 
     https://msdn.microsoft.com/en-us/library/windows/desktop/ms724358%28v=vs.85%29.aspx */ 

     const Int32 PRODUCT_ENTERPRISE_S = 0x7D; 

     var productId = GetProductIdNumber(); 

     Console.Write("Product: "); 
     Console.WriteLine(
     (productId == PRODUCT_ENTERPRISE_S) 
     ? "Windows 10 LTSB" 
     : "Product Number " + productId.ToString("X")); 
    } 

    private static Int32 GetProductIdNumber() 
    { 
     Int32 productId; 

     if (GetProductInfo(
      Environment.OSVersion.Version.Major, 
      Environment.OSVersion.Version.Minor, 
      0, 
      0, 
      out productId)) 
     return productId; 
     else 
     throw new Exception(GetSystemErrorMessage(Marshal.GetLastWin32Error())); 
    } 

    private static String GetSystemErrorMessage(Int32 win32ErrorCode) 
    { 
     const Int32 formatMessageFromSystem = 0x00001000; 
     const Int32 defaultLanguageID = 0; 

     var buffer = new StringBuilder(256); 
     var numberOfCharactersInBuffer = FormatMessage(formatMessageFromSystem, IntPtr.Zero, win32ErrorCode, defaultLanguageID, buffer, buffer.Capacity, IntPtr.Zero); 

     if (numberOfCharactersInBuffer > 0) 
     return buffer.ToString().Trim(); 
     else 
     return String.Concat("Error ", win32ErrorCode, " occurred. No error description is available."); 
    } 
    } 
} 
+0

啊,很好。你參考的API文檔就是這樣。 –

相關問題