IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

API, COM et SDKs Delphi Discussion :

déconnection USB clef disque dure HUB WMI


Sujet :

API, COM et SDKs Delphi

Mode arborescent

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre émérite
    Avatar de ouiouioui
    Homme Profil pro
    Administrateur systèmes et réseaux
    Inscrit en
    Août 2006
    Messages
    991
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Administrateur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Août 2006
    Messages : 991
    Par défaut déconnection USB clef disque dure HUB WMI
    Bonjour, j'ai un programme qui affiche une fenêtre qui liste les périphériques USB de stockage les clés et disques durs. Cela permet de proposer de faire une sauvegarde, mais après la sauvegarde je voudrais proposer l'utilisateur de déconnecter son périphérique USB plutôt qu'il est à le faire manuellement en cliquant dans la barre des taches ce que certains ne font pas et ça cause des problèmes.

    J'ai lu des dizaines voire des centaines de sujets, notamment ici
    http://www.developpez.net/forums/d47...ique-usb-code/
    http://www.developpez.net/forums/d31...ection-disque/

    mais je bloque malgré tous les test de code ce qui fonctionne le mieux pour l'instant est ci-joint. L'éjection fonctionne avec les clés USB mais pas totalement elle reste affichée dans Windows mais est inutilisable, les disques durs cela ne fait rien. J'ai fait des essais avec le disque dur branché sur un port USB et une clé mémoire branchée sur un HUB.

    j'ai fait un projet démo pour vous montrer.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    Unit Unit1;
     
    Interface
     
    Uses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, StdCtrls, WMIListUSBDevice;
     
    Const
      DBT_DEVICEARRIVAL        = $8000;     // system detected a new device
      DBT_DEVICEREMOVECOMPLETE = $8004;     // device is gone
      DBT_DEVTYP_VOLUME        = $00000002; // device volume class
      WM_REFRESHUSBDRIVELIST   = WM_USER + 0;
     
    Type
      PDevBroadcastHdr    = ^DEV_BROADCAST_HDR;
      PDevBroadcastHeader = PDevBroadcastHdr;
     
      DEV_BROADCAST_HDR = Packed Record
        dbch_size:       DWORD;
        dbch_devicetype: DWORD;
        dbch_reserved:   DWORD;
      End;
     
      PDevBroadcastVolume = ^DEV_BROADCAST_VOLUME;
     
      DEV_BROADCAST_VOLUME = Packed Record
        dbch_size:       DWORD;
        dbch_devicetype: DWORD;
        dbch_reserved:   DWORD;
        dbcv_unitmask:   DWORD;
        dbcv_flags:      Word;
      End;
     
    Type
      TForm1 = Class(TForm)
        btGetUSBDriveList:    TButton;
        cbUSBDriveList:       TComboBox;
        btDisconnectUSBDrive: TButton;
        lSelectedUSBDrive:    TLabel;
        Procedure btGetUSBDriveListClick(Sender: TObject);
        Procedure cbUSBDriveListDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState);
        Procedure btDisconnectUSBDriveClick(Sender: TObject);
        Procedure cbUSBDriveListCloseUp(Sender: TObject);
      Private
        Procedure WMDeviceChange(Var Msg: TMessage); Message WM_DEVICECHANGE;
        Procedure WMRefreshUSBDriveList(Var Msg: TMessage); Message WM_REFRESHUSBDRIVELIST;
      Public
        { Déclarations publiques }
      End;
     
    Var
      Form1: TForm1;
     
    Implementation
     
    {$R *.dfm}
     
    Procedure TForm1.btDisconnectUSBDriveClick(Sender: TObject);
    Begin
      (Sender As TButton).Enabled := False;
      btGetUSBDriveList.Enabled   := False;
      Try
        USBDrive.EjectUSBDrive(cbUSBDriveList.ItemIndex);
      Finally
        btGetUSBDriveList.Enabled   := True;
        (Sender As TButton).Enabled := True;
      End;
    End;
     
    Procedure TForm1.btGetUSBDriveListClick(Sender: TObject);
    Begin
      (Sender As TButton).Enabled  := False;
      btDisconnectUSBDrive.Enabled := False;
      Try
        USBDrive.GetUSBLogicalDriveLetter(cbUSBDriveList);
        If cbUSBDriveList.Items.Count > 0 Then
        Begin
          cbUSBDriveList.DroppedDown   := True;
          btDisconnectUSBDrive.Enabled := True;
        End;
      Finally
        (Sender As TButton).Enabled := True;
      End;
    End;
     
    Procedure TForm1.cbUSBDriveListCloseUp(Sender: TObject);
    Begin
      If ((Sender As TComboBox).ItemIndex = -1) Or ((Sender As TComboBox).ItemIndex > USBDrive.DriveList.Count - 1) Then
        lSelectedUSBDrive.Caption := ''
      Else
        With USBDrive.DriveList.Items[(Sender As TComboBox).ItemIndex] Do
          lSelectedUSBDrive.Caption := Format('drive: %0:s - name: %1:s - disque physique: %4:s' + sLineBreak +
            'FreeSpace: %2:u - TotalSpace: %3:u - Index icône: %5:u', [Drive, VolumeName, FreeSpace, TotalSpace, DiskPhysique, IdxIcone]);
            End;
     
    Procedure TForm1.cbUSBDriveListDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState);
    Var
      Offset, I: Integer;
    Begin
      With Control As TComboBox Do
      Begin
        If Not Index In [0..Items.Count - 1] Then
          Exit;
        Offset := USBDrive.ImagesIconeUSBDrive.Width + 8;
        If USBDrive.ImagesIconeUSBDrive.Count > 0 Then
        Begin
          I := Integer(Items.Objects[Index]);
          USBDrive.ImagesIconeUSBDrive.Draw(Canvas, Rect.Left + 4, Rect.Top, I);
          Rect.Left  := Rect.Left + Offset;
          Rect.Right := Rect.Left + Canvas.TextWidth(Items[Index]) + 6;
        End;
        Canvas.FillRect(Rect);
        If odSelected In State Then
          Canvas.DrawFocusRect(Rect);
        Inc(Rect.Left, 3);
        Canvas.TextOut(Rect.Left, Rect.Top, Items[Index]);
      End;
    End;
     
    Procedure TForm1.WMDeviceChange(Var Msg: TMessage);
    Begin
      Inherited;
      Case Msg.WParam Of
        DBT_DEVICEARRIVAL, DBT_DEVICEREMOVECOMPLETE:
          PostMessage(self.Handle, WM_REFRESHUSBDRIVELIST, 0, 0);
      End;
    End;
     
    Procedure TForm1.WMRefreshUSBDriveList(Var Msg: TMessage);
    Begin
      USBDrive.GetUSBLogicalDriveLetter(cbUSBDriveList);
    End;
     
    End.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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.
    est-ce que quelqu'un a déjà réussi à le faire ici ? merci d'avance pour votre aide.
    Fichiers attachés Fichiers attachés

Discussions similaires

  1. Réponses: 2
    Dernier message: 11/05/2007, 23h27
  2. installation sur disque dure externe
    Par big1 dans le forum Composants
    Réponses: 17
    Dernier message: 26/01/2007, 12h32
  3. Ecrire la base de données dans le disque dure
    Par kherfi2006 dans le forum Bases de données
    Réponses: 3
    Dernier message: 25/12/2005, 14h45
  4. outils disque dure
    Par k_boy dans le forum Composants
    Réponses: 3
    Dernier message: 02/10/2005, 22h24
  5. copier la RAM sur le Disque dure
    Par azman0101 dans le forum Windows
    Réponses: 13
    Dernier message: 21/06/2004, 01h04

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo