计算机序号函数,用api函数读取硬盘的序列号
时间: 2023-06-26 14:09:16 浏览: 300
在Windows操作系统中,可以使用WMI(Windows Management Instrumentation)API函数来获取硬盘的序列号。以下是一个示例代码:
```c++
#include <iostream>
#include <windows.h>
#include <winioctl.h>
#include <Ntddscsi.h>
#pragma comment(lib, "wbemuuid.lib")
using namespace std;
int main()
{
// 初始化COM库
HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (FAILED(hr))
{
cerr << "Failed to initialize COM library." << endl;
return 1;
}
// 连接WMI服务
IWbemLocator *pLoc = NULL;
hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc);
if (FAILED(hr))
{
cerr << "Failed to create IWbemLocator object." << endl;
CoUninitialize();
return 1;
}
IWbemServices *pSvc = NULL;
hr = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
if (FAILED(hr))
{
cerr << "Failed to connect to IWbemServices." << endl;
pLoc->Release();
CoUninitialize();
return 1;
}
// 设置WMI查询语句
BSTR query = SysAllocString(L"SELECT * FROM Win32_DiskDrive");
IEnumWbemClassObject* pEnumerator = NULL;
hr = pSvc->ExecQuery(_bstr_t(L"WQL"), query, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
if (FAILED(hr))
{
cerr << "Failed to execute query." << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
return 1;
}
// 遍历查询结果
ULONG uReturn = 0;
while (pEnumerator)
{
IWbemClassObject *pclsObj = NULL;
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
if (0 == uReturn)
{
break;
}
VARIANT vtProp;
hr = pclsObj->Get(L"SerialNumber", 0, &vtProp, 0, 0);
if (FAILED(hr))
{
cerr << "Failed to get serial number." << endl;
pclsObj->Release();
continue;
}
wcout << "Serial number: " << vtProp.bstrVal << endl;
VariantClear(&vtProp);
pclsObj->Release();
}
// 释放资源
pEnumerator->Release();
pSvc->Release();
pLoc->Release();
CoUninitialize();
return 0;
}
```
该程序使用WMI查询语句"SELECT * FROM Win32_DiskDrive"获取所有硬盘的信息,然后遍历结果集,获取每个硬盘的序列号。请注意,该程序需要管理员权限才能读取硬盘信息。
阅读全文