Thema: Delphi USB Stick erkennen

Einzelnen Beitrag anzeigen

Benutzerbild von RWarnecke
RWarnecke

Registriert seit: 31. Dez 2004
Ort: Stuttgart
4.408 Beiträge
 
Delphi XE8 Enterprise
 
#15

Re: USB Stick erkennen

  Alt 12. Nov 2008, 18:44
Ich benutze den Tipp von den Schweizern oder diesen Code, der nicht von mir ist :
Delphi-Quellcode:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Label1: TLabel;
  private
    { Private declarations }
  public
    procedure WMDeviceChange(var Msg: TMessage); message WM_DEVICECHANGE;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.WMDeviceChange(var Msg: TMessage);
type
  PDevBroadcastHdr = ^TDevBroadcastHdr;
  TDevBroadcastHdr = packed record
    dbcd_size, dbcd_devicetype, dbcd_reserved: DWORD;
  end;
  PDevBroadcastVolume = ^TDevBroadcastVolume;
  TDevBroadcastVolume = packed record
    dbcv_size, dbcv_devicetype, dbcv_reserved, dbcv_unitmask: DWORD;
    dbcv_flags: Word;
  end;

  function GetDrive(pDBVol: PDevBroadcastVolume): string;
  var
    i: Byte; Maske: DWORD;
  begin
    if (pDBVol^.dbcv_flags and $0001) = $0001 then
    begin
      Maske := pDBVol^.dbcv_unitmask;
      for i := 0 to 25 do
      begin
        if (Maske and 1) = 1 then
        Result := Char(i + Ord('A')) + ': ';
        Maske := Maske shr 1;
      end;
    end;
  end;

var
  Drive: String;
begin
  case Msg.wParam of
  $8000:
    if PDevBroadcastHdr(Msg.lParam)^.dbcd_devicetype = $0002 then
     Label1.Caption := 'Datenträger in Laufwerk '+GetDrive(PDevBroadcastVolume(Msg.lParam))+'eingelegt';
  $8004:
    if PDevBroadcastHdr(Msg.lParam)^.dbcd_devicetype = $0002 then
    begin
     Drive := GetDrive(PDevBroadcastVolume(Msg.lParam));
     Label1.Caption := 'Datenträger aus Laufwerk '+Drive+'entfernt';
     if not(Drive = '') and (Drive[1] = ExtractFilePath(ParamStr(0))[1]) then Close;
    end;
  end;
end;

end.
Funktioniert wunderbar mit USB-Sticks und USB-Festplatten.
Rolf Warnecke
App4Mission
  Mit Zitat antworten Zitat