C++ 弹出U盘

来源:互联网 发布:js设置元素display为'' 编辑:程序博客网 时间:2024/05/17 08:59


调研USB弹出,记录结果:

bool CUSBControl::RemoveUSB(CString csDisk){HANDLE hDevice; // handle to the drive to be examined BOOL bResult; // results flag DWORD junk; // discard results DWORD dwError; CString csVolume;int nPos = csDisk.Find('\\');//csDisk like "H:\"if ( -1 != nPos ){csDisk = csDisk.Left(nPos);}csVolume.Format(L"\\\\.\\%s", csDisk);// Open the volume hDevice = CreateFile(csVolume, // drive to open GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode NULL, // default security attributes OPEN_EXISTING, // disposition 0, // file attributes NULL); // don't copy any file's attributes if (hDevice == INVALID_HANDLE_VALUE) // can't open the drive { dwError = GetLastError(); return FALSE; } //Dismount the volume bResult = DeviceIoControl( hDevice, // handle to volume IOCTL_STORAGE_EJECT_MEDIA, //eject USBNULL, // lpInBuffer 0, // nInBufferSize NULL, // lpOutBuffer 0, // nOutBufferSize &junk, // discard count of bytes returned (LPOVERLAPPED) NULL); // synchronous I/O if (!bResult) // IOCTL failed { dwError = GetLastError(); } // Close the volume handle bResult = CloseHandle(hDevice); if (!bResult) { dwError = GetLastError(); } return FALSE;}


csDisk怎么来的呢?

BOOL CUSBControl::OnDeviceChange( UINT nEventType, DWORD dwData) { DEV_BROADCAST_DEVICEINTERFACE* dbd = (DEV_BROADCAST_DEVICEINTERFACE*) dwData;PDEV_BROADCAST_VOLUME pDevVolume = NULL;switch (nEventType)  {  case DBT_DEVICEARRIVAL: 
  pDevVolume = (PDEV_BROADCAST_VOLUME)dbd;      switch(pDevVolume->dbcv_flags)      {      case 0:       {        if(DBT_DEVICEARRIVAL == nEventType)     {     CString strDisk;      strDisk.Format(L"%c:\\",FirstDriveFromMask(pDevVolume->dbcv_unitmask));                                   RemoveUSB(strDisk);           }    }                  break;                }        break;} return TRUE;}


 

 

char CUSBControl::FirstDriveFromMask( ULONG unitmask ){char i;for (i = 0; i < 26; ++i){if (unitmask & 0x1)break;unitmask = unitmask >> 1;}return( i + 'A' );}


 

 

原创粉丝点击