Delphi自动检测U盘插入、拔出及获取U盘盘符


unit Unit1;
interface
uses
   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
   Dialogs, AppEvnts, ExtCtrls, StdCtrls;
type
    TForm1 = class(TForm)
     procedure Button1Click(Sender: TObject);
   
   private
{ Private declarations }
   procedure WMDeviceChange(var Msg: TMessage); message WM_DEVICECHANGE;
   public
{ Public declarations }
   end;
var
   Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.WMDeviceChange (var Msg: TMessage);
var
   myMsg : String;
begin
   Case Msg.WParam of
   32768:
begin
   myMsg :='U盘插入';
   MessageBox(0,'注意!U盘已插入!!!','AutoCopy Information',MB_ICONASTERISK and MB_ICONINFORMATION);
   end;
   32772:
begin
   myMsg :='U盘拔出';
   MessageBox(0,'注意!U盘已取走!!!','AutoCopy Information',MB_ICONASTERISK and MB_ICONINFORMATION);
end;
   end;
end;

===========================================

// 取U盘盘符代码

使用delphi程序实现U盘盘符的获取其实不是很难,不过对于新手来说可能有点困难,把代码贴出来,供大家学习

============================================
procedure TForm1.Button1Click(Sender: TObject);

var
    buf:array [0..MAX_PATH-1] of char;
    m_Result:Integer;
    i:Integer;
    str_temp:string;
begin
m_Result:=GetLogicalDriveStrings(MAX_PATH,buf);
for i:=0 to (m_Result div 4) do
begin
        str_temp:=string(buf[i*4]+buf[i*4+1]+buf[i*4+2]);
         if GetDriveType(pchar(str_temp)) = DRIVE_REMOVABLE then
         begin
            ShowMessage(str_temp+'盘为U盘');
            ListBox1.Items.Add(str_temp);
        end;
end;
end;

=========================================//磁盘类型常量参考

DRIVE_UNKNOWN = 0;
{$EXTERNALSYM DRIVE_UNKNOWN}
DRIVE_NO_ROOT_DIR = 1;
{$EXTERNALSYM DRIVE_NO_ROOT_DIR}
DRIVE_REMOVABLE = 2;
{$EXTERNALSYM DRIVE_REMOVABLE}
DRIVE_FIXED = 3;
{$EXTERNALSYM DRIVE_FIXED}
DRIVE_REMOTE = 4;
{$EXTERNALSYM DRIVE_REMOTE}
DRIVE_CDROM = 5;
{$EXTERNALSYM DRIVE_CDROM}
DRIVE_RAMDISK = 6;



联系电话:
020-00000000
联系电话:
020-00000000
联系电话:
020-12345678