这可以通过查询 WMI(Windows 管理规范)的 Win32_WindowsProductActivation(XP 及以下)或 SoftwareLicensingProduct(Vista 或更高)类来实现:
需要声明这些命名空间:
- 系统
- System.Collections.Generic
- 系统管理
- System.Text
使用using 在代码文件的顶部 声明这些命名空间,就其本身而言:
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;
然后在函数中使用以下代码:
ManagementScope Scope;
Scope = new ManagementScope("\\\\.\\ROOT\\cimv2");
Scope.Connect();
ObjectQuery Query = new ObjectQuery("SELECT OfflineInstallationId FROM SoftwareLicensingProduct");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
foreach (ManagementObject WmiObject in Searcher.Get())
{
//Do whatever with the Offline Installation ID here.
}
我注意到,因为我使用了一次 Windows 8.1 的“刷新”功能,我的 WMI 为我返回了 两个 脱机安装 ID,因此这应该是您需要考虑的事情(第一个离线安装 ID 是有效的):
你可能想要类似这样的东西:
static string getOfflineInstallId()
{
ManagementScope Scope;
Scope = new ManagementScope("\\\\.\\ROOT\\cimv2");
Scope.Connect();
ObjectQuery Query = new ObjectQuery("SELECT OfflineInstallationId FROM SoftwareLicensingProduct");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
foreach (ManagementObject WmiObject in Searcher.Get())
{
if (WmiObject["OfflineInstallationId"] != null)
return WmiObject["OfflineInstallationId"].ToString();
}
return ""; //Making the compiler happy.
}
如前所述,SoftwareLicensingProduct 和 OfflineInstallationId 仅适用于比 Vista 更新的 Windows 版本(例如 Vista、7、8、8.1 和 10),因此如果您(或您的程序的用户)希望在 XP 或更早版本上使用它,您也许可以使用以下内容,但是由于我无法访问 XP,因此无法对此进行测试:
ObjectQuery Query = new ObjectQuery("SELECT GetInstallationID FROM Win32_WindowsProductActivation");
如果你想将ID的每个块分开并插入一个TextBox到一个Windows窗体(WinForm)中,你可以使用下面的代码:
string installId = getOfflineInstallId();
StringBuilder sb = new StringBuilder();
bool fRun = false;
for (int i = 0; i < installId.Length; i++)
{
if (i % 7 == 0)
{
if (fRun)
sb.Append('-');
else
fRun = true; //Stops a '-' being added at the 1st position.
}
sb.Append(installId[i]);
}
idTextBox.Text = sb.ToString();
类似这样的:
除此之外,您还需要通过在解决方案资源管理器中右键单击 References、单击 Add New Reference 并添加 System.Management 和 @987654339 来引用 System.Management 库@给项目:
此示例中使用的项目可以在here 下载(需要 Visual Studio 2013 或更高版本)。