windows获取硬盘序列号

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值