Jasa pembuatan Aplikasi dan website

header ads

Mendeteksi USB Menggunakan Delphi + Source Code

unit Unit1;

interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Label1: TLabel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
protected
procedure   WMDEVICECHANGE(var Msg: TMessage); message WM_DEVICECHANGE;
public
{ Public declarations }
end;
var
Form1: TForm1;

// Device constants
const
DBT_DEVICEARRIVAL          =  $00008000;
DBT_DEVICEREMOVECOMPLETE   =  $00008004;
DBT_DEVTYP_VOLUME          =  $00000002;
// Device structs
type
  _DEV_BROADCAST_HDR         =  packed record
     dbch_size:              DWORD;
     dbch_devicetype:        DWORD;
     dbch_reserved:          DWORD;
  end;
  DEV_BROADCAST_HDR          =  _DEV_BROADCAST_HDR;
  TDevBroadcastHeader        =  DEV_BROADCAST_HDR;
  PDevBroadcastHeader        =  ^TDevBroadcastHeader;
type
  _DEV_BROADCAST_VOLUME      =  packed record
     dbch_size:              DWORD;
     dbch_devicetype:        DWORD;
     dbch_reserved:          DWORD;
     dbcv_unitmask:          DWORD;
     dbcv_flags:             WORD;
  end;

  DEV_BROADCAST_VOLUME       =  _DEV_BROADCAST_VOLUME;
  TDevBroadcastVolume        =  DEV_BROADCAST_VOLUME;

  PDevBroadcastVolume        =  ^TDevBroadcastVolume;
implementation
{$R *.dfm}
procedure TForm1.WMDEVICECHANGE(var Msg: TMessage);
var  lpdbhHeader:   PDevBroadcastHeader;
     lpdbvData:     PDevBroadcastVolume;
     dwIndex:       Integer;
     lpszDrive:      String;
begin
 // Perform inherited
  inherited;
  // Get the device notification header
 lpdbhHeader:=PDevBroadcastHeader(Msg.lParam);
 // Handle the message
lpszDrive:='Drive ';
 case Msg.WParam of
    DBT_DEVICEARRIVAL       :    {a USB drive was connected}
     begin
        if (lpdbhHeader^.dbch_devicetype = DBT_DEVTYP_VOLUME) then
        begin
           lpdbvData:=PDevBroadcastVolume(Msg.lParam);
           for dwIndex :=0 to 25 do
           begin
              if ((lpdbvData^.dbcv_unitmask shr dwIndex) = 1) then
              begin
                 lpszDrive:=lpszDrive+Chr(65+dwIndex)+':';
                 break;
              end;
           end;
           Label1.Caption:=lpszDrive + ' connected';

      end;

   end;
     DBT_DEVICEREMOVECOMPLETE:    {a USB drive was removed}

   begin

       if (lpdbhHeader^.dbch_devicetype = DBT_DEVTYP_VOLUME) then

      begin

           lpdbvData:=PDevBroadcastVolume(Msg.lParam);

          for dwIndex:=0 to 25 do

           begin

             if ((lpdbvData^.dbcv_unitmask shr dwIndex) = 1) then
              begin

                lpszDrive:=lpszDrive+Chr(65+dwIndex)+':';
                 break;

              end;

           end;

          Label1.Caption:=lpszDrive + ' removed';
        end;

     end;
  end;

end;
procedure TForm1.FormCreate(Sender: TObject);

begin

Label1.Caption:='';

end;


end.

Post a Comment

0 Comments