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 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
| (* Code Inspiré fortement du code source de ero-sennin, de sergiomaster...
http://www.developpez.net/forums/newreply.php?do=newreply&noquote=1&p=3412638
http://www.developpez.net/forums/showthread.php?t=316505&page=4
-----------------------------------------------------------------------------------------------------------------------------------
Version : 0.0.0.1
Auteur : RemiXtech (OnKeySoft)
-----------------------------------------------------------------------------------------------------------------------------------
Pour être compatible Win 2000 n'oubliez pas de modifié jediapilib.inc et définir la directive de compilation {$DEFINE WIN2000}
-----------------------------------------------------------------------------------------------------------------------------------
*)
unit Oks_USB;
interface
uses Windows, Messages, SysUtils, Classes, Dialogs;
const
DBT_DEVICEARRIVAL = $8000; // le système détecte un nouveau périphérique
DBT_DEVICEREMOVECOMPLETE = $8004; // le périphérique à été retiré
DBT_DEVTYP_VOLUME = $00000002; // type du périphérique
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; // Sert à récupérer la lettre du lecteur
dbcv_flags: WORD; // 0 = Affectation de la lecteur par le périphérique (clé USB)
// 1 = Lettre Changée Automatique (Lecteur de CD-ROM / DVD-ROM)
end;
TOks_USB_Storage = class;
// Taille en sortie
TTypeSizeOf = (tsoAutomatic, tsoByte, tsoKiloByte, tsoMegaByte, tsoGigabyte, tsoTeraByte);
TonConnect = procedure(sender: tOks_USB_Storage; nom, systeme: string; lettre: char; espace_libre, espace_occupe, espace: double) of object;
TonDisConnect = procedure(lettre: char) of object;
TOks_USB_Storage = class(TComponent)
private
FLettre_Periph, FLettre_Periph_deco: Char;
FNom_Volume: array[0..Max_Path] of Char;
FSysteme_Fichier: array[0..Max_Path] of Char;
FSerie_Volume: DWord;
FLongueur_max_Fichier: DWord;
FFlags_Fichier: DWord;
FEspaceLibre_Volume: double;
FEspace_Volume: double;
FEspaceOccup_Volume: double;
FWindowHandle: HWND;
//Evenements
FOnUSBConnect: TonConnect;
FOnUSBDisConnect: TonDisConnect;
procedure Recup_un_message(var Msg: TMessage);
function donner_nom_volume: string;
function donner_systeme_fichier: string;
protected
procedure WM_Gerer_DeviceChange(var Msg: TMessage); virtual;
public
{ Déclarations publiques }
// Protection des variables
property Nom_volume: string read donner_nom_volume;
property Systeme_fichier: string read donner_systeme_fichier;
property Serial: DWord read fserie_volume;
property Espace_libre: double read FEspaceLibre_Volume;
property Espace_occupe: double read FEspaceOccup_Volume;
property Espace: double read FEspace_Volume;
property Lettre_volume: char read FLettre_Periph;
property lettre_volume_deco: char read FLettre_Periph_deco;
// Fonctions utiles
function Recuperer_infos_media(lettre: Char): boolean;
function media_est_connecte(const lettre: Char): Boolean;
function retirer_de_maniere_securisee(Lettre: Char; Allow_PNP_Manager: Boolean = True): integer;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Nettoyer_variables;
published
//Evenements
property OnUSB_Storage_Connect: TonConnect read FOnUSBConnect write FOnUSBConnect;
property OnUSB_Storage_Disconnect: TonDisConnect read FOnUSBDisConnect write FOnUSBDisconnect;
end;
procedure Register;
implementation
uses variants, jwawinioctl, CfgMgr32, SetupApi, JwaWinBase, Cfg;
// REGISTER
procedure Register;
begin
RegisterComponents('OnKeySoft', [TOks_USB_Storage]);
end;
//---------------------
// CONSTRUCTEUR
//---------------------
constructor TOks_USB_Storage.Create(AOwner: TComponent);
begin
inherited;
FWindowHandle := Classes.AllocateHWnd(Recup_un_message); // Nous sommes une application sans fenêtre et nous voulons traiter les messages
end;
//---------------------
// DESTRUCTEUR
//---------------------
destructor TOks_USB_Storage.Destroy;
begin
// On libère le tout !
Classes.DeallocateHWnd(FWindowHandle);
inherited;
end;
//---------------------
// NOM DOS
//---------------------
function NomDos(Drive: string): string;
var
Nom: string[60];
begin
Nom := '';
QueryDosDevice(Pchar(Drive), @Nom, 60);
result := Copy(nom, 0, pos(#0, nom) - 1);
end;
//---------------------
// Donner_son_volume et donner_systeme_fichier
//---------------------
function TOks_USB_Storage.donner_nom_volume: string;
begin
result := FNom_Volume;
end;
function TOks_USB_Storage.donner_systeme_fichier: string;
begin
result := FSysteme_Fichier;
end;
//---------------------
// Nettoyer_variables
//---------------------
procedure TOks_USB_Storage.Nettoyer_variables;
begin
FLettre_Periph := chr(0);
FNom_Volume := '';
FSysteme_Fichier := '';
FSerie_Volume := 0;
FLongueur_max_Fichier := 0;
FFlags_Fichier := 0;
FEspaceLibre_Volume := 0;
FEspace_Volume := 0;
FEspaceOccup_Volume := 0;
end;
//------------------------------
// Le média lettre:\ est il connecté ?
//------------------------------
function TOks_USB_Storage.media_est_connecte(const lettre: Char): Boolean;
var
DrvNum: Byte;
EMode: Word;
begin
Result := False;
DrvNum := Ord(lettre);
try
if DrvNum >= Ord('a') then
Dec(DrvNum, $20);
EMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
if DiskSize(DrvNum - $40) <> -1 then
Result := True
finally
SetErrorMode(EMode);
end;
except
result := false;
end;
end;
//------------------------------
// On charge les informations ?
//------------------------------
function TOks_USB_Storage.Recuperer_infos_media(lettre: Char): boolean;
begin
result := false;
try
if pos('Harddisk',NomDos(lettre + ':')) <>0 then
begin
Nettoyer_variables;
FLettre_Periph := lettre;
if media_est_connecte(lettre) then
begin
if GetVolumeInformation(PChar(FLettre_Periph + ':\'), @FNom_Volume, Max_Path, @FSerie_Volume, FLongueur_max_Fichier, FFlags_Fichier, FSysteme_Fichier, Max_Path) then
begin
FEspace_Volume := DiskSize(Ord(FLettre_Periph) - 64);
FEspaceLibre_Volume := DiskFree(Ord(FLettre_Periph) - 64);
FEspaceOccup_Volume := FEspace_Volume - FEspaceLibre_Volume;
result := true;
end;
end;
end;
except
result := false;
end;
end;
//------------------------------
// Gestion des messages !
//------------------------------
procedure TOks_USB_Storage.Recup_un_message(var Msg: TMessage);
begin
if (Msg.Msg = WM_DEVICECHANGE) then // si le message nous interesse
begin
try
WM_Gerer_DeviceChange(Msg);
except
end;
end
else
Msg.Result := DefWindowProc(FWindowHandle, Msg.Msg, Msg.wParam, Msg.lParam); // Sinon on laisse couler
end;
//------------------------------
// Procédure de cinglé !
//------------------------------
function TOks_USB_Storage.retirer_de_maniere_securisee(Lettre: Char; Allow_PNP_Manager: Boolean): integer;
var
ident_volume, retf: Cardinal; // drivetype , drivenumber , retour de fonction
nom_dos: string; // nom dos du drive (permet de distinguer un floppy d'un USB)
DIParent: DEVINST; // identifient du parent
VetoType: PNP_VETO_TYPE;
VetoNamew: array[0..MAX_PATH] of wChar;
function Donner_ident_volume(lecteur: string): Cardinal;
var
R: LongBool; // retour de fonction
Handle_volume: THandle; // Hande du volume
num_de_serie: STORAGE_DEVICE_NUMBER; // n° du volume
dw: DWORD;
{Obtention du Handle du volume}
function GetHandleVolume(lecteur: string): THandle;
var
CheminVolume: string;
begin
CheminVolume := '\\.\' + lecteur;
Result := CreateFile(Pchar(CheminVolume), 0, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, 0, 0);
end;
begin
Handle_volume := GetHandleVolume(lecteur);
//DeviceIoControl function sends a control code directly to a specified device driver, causing the corresponding device to perform the corresponding operation
R := DeviceIoControl(Handle_volume, IOCTL_STORAGE_GET_DEVICE_NUMBER, nil, 0, @num_de_serie, sizeof(num_de_serie), @dw, nil);
if R then
Result := num_de_serie.DeviceNumber
else
begin
result := 0;
end;
CloseHandle(Handle_volume);
end;
function GetDrivesDevInstByDeviceNumber(DeviceNom: Cardinal; DriveName: string): DEVINST;
var
StorageGUID: TGUID;
PnPHandle: HDEVINFO;
DevData: TSPDevInfoData;
DeviceInterfaceData: TSPDeviceInterfaceData;
FunctionClassDeviceData: PSPDeviceInterfaceDetailData;
Success: LongBool;
Devn: Integer;
BytesReturned: Cardinal;
Hdrive: THandle;
sdn: STORAGE_DEVICE_NUMBER;
begin
StorageGuid := GUID_DEVINTERFACE_DISK;
Result := 0;
PnPHandle := SetupDiGetClassDevs(@StorageGUID, nil, 0, DIGCF_PRESENT or DIGCF_DEVICEINTERFACE);
if PnPHandle = Pointer(INVALID_HANDLE_VALUE) then
begin
result := 0;
exit;
end;
Devn := 0;
repeat
DeviceInterfaceData.cbSize := SizeOf(TSPDeviceInterfaceData);
Success := SetupDiEnumDeviceInterfaces(PnPHandle, nil, StorageGUID, Devn, DeviceInterfaceData);
if Success then
begin
DevData.cbSize := SizeOf(DevData);
BytesReturned := 0;
SetupDiGetDeviceInterfaceDetail(PnPHandle, @DeviceInterfaceData, nil, 0, BytesReturned, @DevData);
if (BytesReturned <> 0) and (GetLastError = ERROR_INSUFFICIENT_BUFFER) then
begin
FunctionClassDeviceData := AllocMem(BytesReturned);
try
FunctionClassDeviceData.cbSize := SizeOf(TSPDeviceInterfaceDetailData);
if SetupDiGetDeviceInterfaceDetail(PnPHandle, @DeviceInterfaceData,
FunctionClassDeviceData, BytesReturned, BytesReturned, @DevData) then
begin
// open the disk or cdrom or floppy
HDrive := CreateFile(FunctionClassDeviceData.DevicePath, 0, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, 0, 0);
if (HDrive <> INVALID_HANDLE_VALUE) then
begin
// get its device number
Success := DeviceIoControl(HDrive, IOCTL_STORAGE_GET_DEVICE_NUMBER, nil, 0, @sdn, sizeof(sdn), @BytesReturned, nil);
if Success and (DeviceNom = sdn.DeviceNumber) then
begin
// match the given device number with the one of the current device
Result := DevData.DevInst;
end;
CloseHandle(HDrive);
end;
end;
finally
FreeMem(FunctionClassDeviceData);
end;
end;
end;
Inc(Devn);
until not Success;
SetupDiDestroyDeviceInfoList(PnPHandle);
end;
begin
result := 4;
(*
0: Aucune erreur tout va bien :D
1: Impossible ce n'est pas un Volume correct
2: Pas de volume correct (par exemple disque dur non usb)
3:Impossible de terminer...
4:erreur inconnue;
*)
nom_dos := NomDos(lettre + ':');
if pos('Harddisk',Nom_dos) <>0 then
begin
ident_volume := Donner_ident_volume(lettre + ':');
if ident_volume <> 0 then
begin
LoadSetupApi;
LoadConfigManagerApi;
ident_volume := GetDrivesDevInstByDeviceNumber(ident_volume, nom_dos);
if ident_volume > 0 then
begin
//****** ici il doit certainement y avoir un test manquant
//****** car pour un CD pas de parent ???
// Obtenir le parent, i.e. USB bridge, port SATA, Canal IDE avec 2 lecteurs!
DIParent := 0;
CM_Get_Parent(DIParent, ident_volume, 0);
// for i := 1 to 3 do // au cas où cela ne marche pas du premier coup.
// begin
VetoType := PNP_VetoTypeUnknown;
VetoNamew[0] := #0;
if Allow_PNP_Manager then
retf := CM_Request_Device_EjectW(DIParent, nil, nil, 0, 0) // avec message (W2K, Vista) ou bulle (XP)
else
retf := CM_Request_Device_EjectW(DIParent, @VetoType, @VetoNamew[0], MAX_PATH, 0); // sans message (W2K, Vista) ou bulle (XP)
if retf = CR_SUCCESS then
result := 0
else
result := 3;
// end;
end;
UnloadConfigManagerApi;
UnloadSetupApi;
end
else
result := 2;
end
else
result := 1;
end;
procedure TOks_USB_Storage.WM_Gerer_DeviceChange(var Msg: TMessage);
var
Pinfo: PDevBroadcastHeader;
Pdonnees: PDevBroadcastVolume;
Index: Integer;
begin
Pinfo := PDevBroadcastHeader(Msg.lParam); //On recupere les en têtes du message
case Msg.WParam of
// -------------------------------
// INSERTION D'UN MEDIA
// -------------------------------
DBT_DEVICEARRIVAL:
begin
if (Pinfo^.dbch_devicetype = DBT_DEVTYP_VOLUME) then
begin
// C'est un volume
if (PDevBroadcastVolume(Msg.LParam)^.dbcv_flags = 0) then
begin
// On ne s'interesse ici qu'aux périphériques externes de type clé USB
Pdonnees := PDevBroadcastVolume(Msg.lParam); // On recupere les données du volume depuis le message
for Index := 0 to 25 do // Il y'a 26 lettres dispo pour les noms de lecteurs...
if ((Pdonnees^.dbcv_unitmask shr Index) = 1) then // Si bit
begin
FLettre_Periph := Chr(65 + Index); // La lettre du lecteur
break;
end;
// Récupération de diverses informations sur le média
if GetVolumeInformation(PChar(FLettre_Periph + ':\'), @FNom_Volume, Max_Path, @FSerie_Volume, FLongueur_max_Fichier, FFlags_Fichier, FSysteme_Fichier, Max_Path) then
begin
FEspace_Volume := DiskSize(Ord(FLettre_Periph) - 64);
FEspaceLibre_Volume := DiskFree(Ord(FLettre_Periph) - 64);
FEspaceOccup_Volume := FEspace_Volume - FEspaceLibre_Volume;
if pos('Harddisk',NomDos(FLettre_Periph + ':')) <>0 then
if Assigned(OnUSB_Storage_Connect) then
FOnUSBConnect(TOks_USB_Storage(self), self.Nom_volume, self.Systeme_fichier, self.Lettre_volume, self.Espace_libre, self.Espace_occupe, self.Espace);
end;
end;
end;
end;
// -------------------------------
// DECONNEXION D'UN MEDIA
// -------------------------------
DBT_DEVICEREMOVECOMPLETE:
begin
if (Pinfo^.dbch_devicetype = DBT_DEVTYP_VOLUME) then
begin
// C'est un volume
if (PDevBroadcastVolume(Msg.LParam)^.dbcv_flags = 0) then
begin
Pdonnees := PDevBroadcastVolume(Msg.lParam); // On recupere les données du volume depuis le message
for Index := 0 to 25 do // Idem qu'au dessus
if ((Pdonnees^.dbcv_unitmask shr Index) = 1) then
begin
FLettre_Periph_deco := Chr(65 + Index);
break;
end;
if Assigned(FOnUSBDisconnect) then
FOnUSBDisconnect(self.lettre_volume_deco);
end;
end;
end;
end;
end;
end. |
Partager