CreateFile打开U盘的方法2-逻辑方式

//需要引用头文件

#include "Setupapi.h"
#include <initguid.h>
#pragma comment(lib,"setupapi.lib")

#define INTERFACE_DETAIL_SIZE    1024
#define MAX_DRIVER_STRING_LENGHT 100


//判断U盘是否是要查找的U盘
BOOL GetUDisk(CString strUDisk)
{
TCHAR szBuf[300];
sprintf_s(szBuf, "\\\\?\\%c:", strUDisk[0]);

HANDLE hDevice;
hDevice = CreateFile(szBuf, GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);


if (hDevice != INVALID_HANDLE_VALUE)
{

PSTORAGE_DEVICE_DESCRIPTOR pDevDesc;
pDevDesc = (PSTORAGE_DEVICE_DESCRIPTOR)new BYTE[sizeof(STORAGE_DEVICE_DESCRIPTOR) + 512 - 1];


pDevDesc->Size = sizeof(STORAGE_DEVICE_DESCRIPTOR) + 512 - 1;


if(GetDisksProperty(hDevice, pDevDesc))
{

ShowMessage("\r\n找到U盘,名称:\r\n");
char *p= (char*)pDevDesc;
CString str = (pDevDesc->VendorIdOffset ? &p[pDevDesc->VendorIdOffset]:"(NULL)");

//此地可以根据取得的U盘名称取得该盘是否自己要修改的U盘

ShowMessage("\r\n产品ID:\r\n");
str=(pDevDesc->ProductIdOffset ? &p[pDevDesc->ProductIdOffset]:"(NULL)");
ShowMessage(str);
ShowMessage("\r\n产品版本:\r\n");
str = (pDevDesc->ProductRevisionOffset ? &p[pDevDesc->ProductRevisionOffset] : "(NULL)");
ShowMessage(str);
ShowMessage("\r\n序列号:\r\n");
str = (pDevDesc->SerialNumberOffset ? &p[pDevDesc->SerialNumberOffset] : "(NULL)");
ShowMessage(str);
}


delete pDevDesc;
CloseHandle(hDevice);
}
return FALSE;
}


//取得U盘的信息
BOOL GetDisksProperty(HANDLE hDevice, PSTORAGE_DEVICE_DESCRIPTOR pDevDesc)
{
STORAGE_PROPERTY_QUERY    Query;    
DWORD dwOutBytes;                
BOOL bResult;                    

Query.PropertyId = StorageDeviceProperty;
Query.QueryType = PropertyStandardQuery;

bResult = ::DeviceIoControl(hDevice,            
IOCTL_STORAGE_QUERY_PROPERTY,            
&Query, sizeof(STORAGE_PROPERTY_QUERY),    
pDevDesc, pDevDesc->Size,                
&dwOutBytes,                            
(LPOVERLAPPED)NULL);                    

return bResult;
}

展开阅读全文

没有更多推荐了,返回首页