#include <codecvt>
#include <windows.h>
#include <comdef.h>
#include <shlobj.h>
#pragma comment(lib, "wbemuuid.lib")
#pragma comment(lib, "ws2_32.lib")
#define GET_DEVICE_INFO_ERROR -1
#define GET_DEVICE_INFO_OK 0
int QueryDiskSerialNumber(std::string& strSerialNumber)
{
const char* drive = "\\\\.\\PHYSICALDRIVE0"; // 要获取序列号的硬盘
HANDLE hDevice = CreateFileA(drive, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (hDevice == INVALID_HANDLE_VALUE)
{
return GET_DEVICE_INFO_ERROR;
}
STORAGE_PROPERTY_QUERY storagePropertyQuery;
ZeroMemory(&storagePropertyQuery, sizeof(STORAGE_PROPERTY_QUERY));
storagePropertyQuery.PropertyId = StorageDeviceProperty;
storagePropertyQuery.QueryType = PropertyStandardQuery;
DWORD dwBytesReturned = 0;
STORAGE_DESCRIPTOR_HEADER storageDescriptorHeader;
ZeroMemory(&storageDescriptorHeader, sizeof(STORAGE_DESCRIPTOR_HEADER));
if (!DeviceIoControl(hDevice, IOCTL_STORAGE_QUERY_PROPERTY, &storagePropertyQuery, sizeof(STORAGE_PROPERTY_QUERY),
&storageDescriptorHeader, sizeof(STORAGE_DESCRIPTOR_HEADER), &dwBytesReturned, NULL))
{
CloseHandle(hDevice);
return GET_DEVICE_INFO_ERROR;
}
DWORD dwOutBytes;
BYTE* pOutBuffer = new BYTE[storageDescriptorHeader.Size];
if (!DeviceIoControl(hDevice, IOCTL_STORAGE_QUERY_PROPERTY, &storagePropertyQuery, sizeof(STORAGE_PROPERTY_QUERY),
pOutBuffer, storageDescriptorHeader.Size, &dwOutBytes, NULL))
{
CloseHandle(hDevice);
delete[] pOutBuffer;
return GET_DEVICE_INFO_ERROR;
}
STORAGE_DEVICE_DESCRIPTOR* pDeviceDescriptor = (STORAGE_DEVICE_DESCRIPTOR*)pOutBuffer;
char* serialNumber = new char[pDeviceDescriptor->SerialNumberOffset + 1];
memcpy(serialNumber, pOutBuffer + pDeviceDescriptor->SerialNumberOffset, pDeviceDescriptor->SerialNumberOffset);
serialNumber[pDeviceDescriptor->SerialNumberOffset] = 0;
strSerialNumber = serialNumber;
delete[] pOutBuffer;
delete[] serialNumber;
CloseHandle(hDevice);
return GET_DEVICE_INFO_OK;
}
windows获取硬盘序列号
最新推荐文章于 2024-09-19 09:22:03 发布