1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
| Unit WMIListUSBDevice;
Interface
Uses
Windows, SysUtils, Classes, ComObj, ActiveX, UrlMon, ShellAPI, Controls,
ImgList, Graphics, StdCtrls;
Type
TDrive = Class
Drive: Char;
DiskPhysique, VolumeName: String;
FreeSpace, TotalSpace: Int64;
IdxIcone: Integer;
Public
Constructor Create(ADrive: Char; ADiskPhysique, AVolumeName: String; AFreeSpace, ATotalSpace: Int64; AIdxIcone: Integer);
End;
TDriveList = Class(TList)
Private
Function GetItem(Index: Integer): TDrive;
Public
Destructor Destroy; Override;
Function AddDrive(ADrive: Char; ADiskPhysique, AVolumeName: String; AFreeSpace, ATotalSpace: Int64; AIdxIcone: Integer): Integer;
Procedure Clear; Override;
Procedure Delete(Index: Integer);
Property Items[Index: Integer]: TDrive Read GetItem;
End;
TUSBDrive = Class
Private
FSmall: Integer;
Function EjectVolume(ADrive: Char): Boolean;
Function AutoEjectVolume(AVolumeHandle: THandle): Boolean;
Function DismountVolume(AVolumeHandle: THandle): Boolean;
Function FormatSize(FreeSpace, Size: String): String;
Function LockVolume(AVolumeHandle: THandle): Boolean;
Function OpenVolume(ADrive: Char): THandle;
Function PreventRemovalOfVolume(AVolumeHandle: THandle; APreventRemoval: Boolean): Boolean;
Function SizeToStr(Size: Int64): String;
Function FileIconInit(FullInit: Boolean): Boolean; Stdcall;
Public
ImagesIconeUSBDrive: TImageList;
DriveList: TDriveList;
Function EjectUSBDrive(Index: Integer): Boolean;
Procedure GetUSBLogicalDriveLetter(cb: TComboBox);
Constructor Create;
Destructor Destroy; Override;
End;
Var
USBDrive: TUSBDrive;
Implementation
{ TUSBDrive }
Constructor TUSBDrive.Create;
Begin
FSmall := GetSystemMetrics(SM_CXSMICON);
ImagesIconeUSBDrive := TImageList.CreateSize(FSmall, FSmall);
ImagesIconeUSBDrive.DrawingStyle := dsTransparent;
ImagesIconeUSBDrive.ShareImages := True;
DriveList := TDriveList.Create;
End;
Destructor TUSBDrive.Destroy;
Begin
ImagesIconeUSBDrive.Free;
DriveList.Free;
Inherited;
End;
//foxi
Function TUSBDrive.SizeToStr(Size: Int64): String;
Begin
If Size < $000000000400 Then
Result := format('%d bytes', [Size])
Else
If Size < $000000100000 Then
Result := format('%.1f Kb', [Size / $000000000400])
Else
If Size < $000040000000 Then
Result := format('%.1f Mb', [Size / $000000100000])
Else
If Size < $010000000000 Then
Result := format('%.2f Gb', [Size / $000040000000])
Else
Result := format('%.2f Tb', [Size / $010000000000]);
End;
Function TUSBDrive.FormatSize(FreeSpace, Size: String): String;
Begin
Result := format(' (libre : %0:s, total : %1:s)', [SizeToStr(StrToInt64(FreeSpace)), SizeToStr(StrToInt64(Size))]);
End;
//déconnecter un lecteur par sa lettre
//http://support.microsoft.com/kb/165721/fr
//http://efreedom.com/Question/1-434688/Can-Remove-USB-Flash-Disk-Programmatically-Using-Delphi
//http://stackoverflow.com/questions/434688/how-can-i-remove-a-usb-flash-disk-programmatically-using-delphi
Function TUSBDrive.OpenVolume(ADrive: Char): THandle;
Var
RootName, VolumeName: String;
AccessFlags: DWORD;
Begin
RootName := ADrive + ':\\'; // ADrive + ':\' kills the syntax highlighting
Case GetDriveType(PChar(RootName)) Of
DRIVE_REMOVABLE, DRIVE_FIXED: // DRIVE_FIXED needed for usb hardrive
AccessFlags := GENERIC_READ Or GENERIC_WRITE;
DRIVE_CDROM:
AccessFlags := GENERIC_READ;
Else
Result := INVALID_HANDLE_VALUE;
exit;
End;
VolumeName := Format('\\.\%s:', [ADrive]);
Result := CreateFile(PChar(VolumeName), AccessFlags, FILE_SHARE_READ Or FILE_SHARE_WRITE, NIL, OPEN_EXISTING, 0, 0);
If Result = INVALID_HANDLE_VALUE Then
RaiseLastOSError;
End;
Function TUSBDrive.LockVolume(AVolumeHandle: THandle): Boolean;
Const
LOCK_TIMEOUT = 10 * 1000; // 10 Seconds
LOCK_RETRIES = 20;
LOCK_SLEEP = LOCK_TIMEOUT Div LOCK_RETRIES;
// #define FSCTL_LOCK_VOLUME CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 6, METHOD_BUFFERED, FILE_ANY_ACCESS)
FSCTL_LOCK_VOLUME = (9 Shl 16) Or (0 Shl 14) Or (6 Shl 2) Or 0;
Var
Retries: Integer;
BytesReturned: Cardinal;
Begin
For Retries := 1 To LOCK_RETRIES Do
Begin
Result := DeviceIoControl(AVolumeHandle, FSCTL_LOCK_VOLUME, NIL, 0, NIL, 0, BytesReturned, NIL);
If Result Then
break;
Sleep(LOCK_SLEEP);
End;
End;
Function TUSBDrive.DismountVolume(AVolumeHandle: THandle): Boolean;
Const
// #define FSCTL_DISMOUNT_VOLUME CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 8, METHOD_BUFFERED, FILE_ANY_ACCESS)
FSCTL_DISMOUNT_VOLUME = (9 Shl 16) Or (0 Shl 14) Or (8 Shl 2) Or 0;
Var
BytesReturned: Cardinal;
Begin
Result := DeviceIoControl(AVolumeHandle, FSCTL_DISMOUNT_VOLUME, NIL, 0, NIL, 0, BytesReturned, NIL);
If Not Result Then
RaiseLastOSError;
End;
Function TUSBDrive.PreventRemovalOfVolume(AVolumeHandle: THandle; APreventRemoval: Boolean): Boolean;
Const
// #define IOCTL_STORAGE_MEDIA_REMOVAL CTL_CODE(IOCTL_STORAGE_BASE, 0x0201, METHOD_BUFFERED, FILE_READ_ACCESS)
IOCTL_STORAGE_MEDIA_REMOVAL = ($2d Shl 16) Or (1 Shl 14) Or ($201 Shl 2) Or 0;
Type
TPreventMediaRemoval = Record
PreventMediaRemoval: BOOL;
End;
Var
BytesReturned: Cardinal;
PMRBuffer: TPreventMediaRemoval;
Begin
PMRBuffer.PreventMediaRemoval := APreventRemoval;
Result := DeviceIoControl(AVolumeHandle, IOCTL_STORAGE_MEDIA_REMOVAL, @PMRBuffer,
SizeOf(TPreventMediaRemoval), NIL, 0, BytesReturned, NIL);
If Not Result Then
RaiseLastOSError;
End;
Function TUSBDrive.AutoEjectVolume(AVolumeHandle: THandle): Boolean;
Const
// #define IOCTL_STORAGE_EJECT_MEDIA CTL_CODE(IOCTL_STORAGE_BASE, 0x0202, METHOD_BUFFERED, FILE_READ_ACCESS)
IOCTL_STORAGE_EJECT_MEDIA = ($2d Shl 16) Or (1 Shl 14) Or ($202 Shl 2) Or 0;
Var
BytesReturned: Cardinal;
Begin
Result := DeviceIoControl(AVolumeHandle, IOCTL_STORAGE_EJECT_MEDIA, NIL, 0, NIL, 0, BytesReturned, NIL);
If Not Result Then
RaiseLastOSError;
End;
Function TUSBDrive.EjectVolume(ADrive: Char): Boolean;
Var
VolumeHandle: THandle;
Begin
Result := False;
// Open the volume
VolumeHandle := OpenVolume(ADrive);
If VolumeHandle = INVALID_HANDLE_VALUE Then
exit;
Try
// Lock and dismount the volume
If LockVolume(VolumeHandle) And DismountVolume(VolumeHandle) Then
Begin
// Set prevent removal to false and eject the volume
If PreventRemovalOfVolume(VolumeHandle, False) Then
AutoEjectVolume(VolumeHandle);
End;
Finally
// Close the volume so other processes can use the dr
CloseHandle(VolumeHandle);
End;
End;
Function TUSBDrive.FileIconInit(FullInit: Boolean): Boolean; Stdcall;
Type
TFileIconInit = Function(FullInit: Boolean): Boolean; Stdcall;
Var
ShellDLL: HMODULE;
PFileIconInit: TFileIconInit;
Begin
Result := False;
If (Win32Platform = VER_PLATFORM_WIN32_NT) Then
Begin
ShellDLL := LoadLibrary(PChar('shell32.dll'));
PFileIconInit := GetProcAddress(ShellDLL, PChar(660));
If (Assigned(PFileIconInit)) Then
Result := PFileIconInit(FullInit);
End;
End;
Function TUSBDrive.EjectUSBDrive(Index: Integer): Boolean;
Begin
If Not Index In [0..DriveList.Count - 1] Then
Raise Exception.Create('Index not found in DriveList');
Result := EjectVolume(DriveList.Items[Index].Drive);
End;
// récuperer liste lecteur USB clef et disque dure
// ==============================================================================
// == Eric Boisvert http://www.developpez.net/forums/u18010/eric-boisvert/
// ==
// == Obtien la lettre associée d'un Numéro de disque physique via WMI
// == source des requêtes WMI dans cette fonction
// == http://msdn2.microsoft.com/en-us/library/aa394592.aspx
// == L'avantage d'utilisé OLE Atomation avec WMI, c'est que la syntax
// == Delphi devient semblable à du VBScript...
// == et il exsite beaucoup d'exemple en VBScript.
// ==
// == use urlMon,ActiveX,ComObj
// ==============================================================================
Procedure TUSBDrive.GetUSBLogicalDriveLetter(cb: TComboBox);
Var
// == Moniker stuff ==
hr: HResult;
wsWMIConnectionStr: WideString;
oBindCtx: IBindCtx; // BindContext
oIMoniker: IMoniker; // IMoniker interface
oIDispatch: IDispatch; // WMI connection
oleWMI: Olevariant;
oDisks, oDisk: Olevariant; // Objet Disks (physique)
oPartitions, oPartition: Olevariant; // Objets Partitions
oLogicalDisks, oLogicalDisk: Olevariant; // Objets LogicalDisk
oEnumDisk, oEnumPart, oEnumVolume: IEnumvariant; // Ennumerations
ulParsed: ULONG;
sDiskPhysique: String;
sPartition: String;
sDiskLogique: String;
query: String;
Info: TSHFileInfo;
sLogicalDiskID: String;
Begin
// == Utilise WMI a travers OLE et une Session Moniker...
// == Source http://msdn2.microsoft.com/en-us/library/aa383539.aspx
// == http://msdn2.microsoft.com/en-us/library/aa389763.aspx
// == http://msdn2.microsoft.com/en-us/library/ms221192.aspx
// == Initialise les objets COM ==
CoInitialize(NIL);
sDiskLogique := '';
cb.Items.Clear;
DriveList.Clear;
Try
// == on récupère les icônes
FileIconInit(True);
ImagesIconeUSBDrive.Handle := SHGetFileInfo('', 0, Info, SizeOf(TSHFileInfo), SHGFI_SYSICONINDEX Or SHGFI_SMALLICON);
ImagesIconeUSBDrive.ShareImages := True;
// == DEBUT Equivalent à GetObject de VBScript via OLE ==
// == voir: http://support.microsoft.com/kb/122288 ==
// == Obtient un bind Context ==
hr := CreateBindCtx(0, oBindCtx);
If hr <> 0 Then
OleCheck(hr);
// == Obtient IMoniker interface ==
wsWMIConnectionStr := 'winmgmts:\\.\root\cimv2';
hr := MkParseDisplayNameEx(oBindCtx, PWideChar(wsWMIConnectionStr), ulParsed, oIMoniker);
If hr <> 0 Then
OleCheck(hr);
// == Obtient un objet WMI ==
hr := oIMoniker.BindToObject(oBindCtx, NIL, IUnknown, oIDispatch);
If hr <> 0 Then
OleCheck(hr);
oleWMI := oIDispatch;
// == FIN Equivalent à GetObject de VBScript ==
// == Trouve tous les disques Physiques branché en USB ==
query := 'SELECT DeviceID FROM Win32_DiskDrive WHERE InterfaceType = ''USB''';
oDisks := oleWMI.ExecQuery(query);
oEnumDisk := IUnknown(oDisks._NewEnum) As IEnumvariant;
While oEnumDisk.Next(1, oDisk, ulParsed) = 0 Do
Begin
sDiskPhysique := oDisk.DeviceID;
// == Pour chaque disque, trouve toutes les partitions ==
query := 'ASSOCIATORS OF {Win32_DiskDrive.DeviceID=''';
query := query + sDiskPhysique;
query := query + '''} WHERE AssocClass = Win32_DiskDriveToDiskPartition';
oPartitions := oleWMI.ExecQuery(query);
oEnumPart := IUnknown(oPartitions._NewEnum) As IEnumvariant;
While oEnumPart.Next(1, oPartition, ulParsed) = 0 Do
Begin
sPartition := oPartition.DeviceID;
// == Pour chaque partition, Trouve les Disques Logiques (lettre) ==
query := 'ASSOCIATORS OF {Win32_DiskPartition.DeviceID="';
query := query + sPartition;
query := query + '"} WHERE AssocClass = Win32_LogicalDiskToPartition';
oLogicalDisks := oleWMI.ExecQuery(query);
oEnumVolume := IUnknown(oLogicalDisks._NewEnum) As IEnumvariant;
While oEnumVolume.Next(1, oLogicalDisk, ulParsed) = 0 Do
Begin
// == Accumule les index d'icônes, lettres, nom, taille associées au disque logique ==
sLogicalDiskID := String(oLogicalDisk.DeviceID) + '\';
SHGetFileInfo(PChar(sLogicalDiskID), 0, Info, SizeOf(TSHFileInfo), SHGFI_SYSICONINDEX Or SHGFI_SMALLICON);
cb.Items.AddObject('(' + oLogicalDisk.DeviceID + ') ' + oLogicalDisk.VolumeName + FormatSize(
oLogicalDisk.FreeSpace, oLogicalDisk.Size), TObject(Info.iIcon));
// == rempli notre liste
DriveList.AddDrive(sLogicalDiskID[1], sDiskPhysique, oLogicalDisk.VolumeName,
StrToInt64(oLogicalDisk.FreeSpace), StrToInt64(oLogicalDisk.Size), Info.iIcon);
End;
End;
End;
Finally
// == Liberatrion des objets COM ==
CoUninitialize();
End;
End;
{ TDrive }
Constructor TDrive.Create(ADrive: Char; ADiskPhysique, AVolumeName: String; AFreeSpace, ATotalSpace: Int64; AIdxIcone: Integer);
Begin
Drive := ADrive;
DiskPhysique := ADiskPhysique;
VolumeName := AVolumeName;
FreeSpace := AFreeSpace;
TotalSpace := ATotalSpace;
IdxIcone := AIdxIcone;
End;
{ TDriveList }
Function TDriveList.AddDrive(ADrive: Char; ADiskPhysique, AVolumeName: String; AFreeSpace, ATotalSpace: Int64; AIdxIcone: Integer): Integer;
Begin
Result := Inherited Add(TDrive.Create(ADrive, ADiskPhysique, AVolumeName, AFreeSpace, ATotalSpace, AIdxIcone));
End;
Procedure TDriveList.Clear;
Begin
While Inherited Count > 0 Do
Delete(0);
Inherited;
End;
Procedure TDriveList.Delete(Index: Integer);
Begin
If Not Index In [0..Count - 1] Then
Exit;
Items[Index].Free;
Inherited Delete(Index);
End;
Destructor TDriveList.Destroy;
Begin
Try
Clear;
Finally
Inherited;
End;
End;
Function TDriveList.GetItem(Index: Integer): TDrive;
Begin
Result := TDrive(Inherited Items[Index]);
End;
Initialization
USBDrive := TUSBDrive.Create;
Finalization
USBDrive.Free;
End. |
Partager