Delphi 自动检测U盘插入、拔出及获取U盘盘符!
u盘的 插入和删除windows会给所有的程序发出WM_DEVICECHANGE 信息
//这句放在private里面
procedure WMDeviceChange(var Msg: TMessage); message WM_DEVICECHANGE;
procedure TForm1.WMDeviceChange (var Msg: TMessage);
var
myMsg : String;
begin
Case Msg.WParam of
32768:
begin
myMsg :='U盘插入';
Label1.Caption:=myMsg
end;
32772:
begin
myMsg :='U盘拔出';
Label1.Caption:=myMsg;
end;
end;
end;
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;
//完整源码
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Label1: TLabel;
Button1: TButton;
ListBox1: TListBox;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
//u盘的 插入和删除windows会给所有的程序发出WM_DEVICECHANGE 信息
procedure WMDeviceChange(var Msg: TMessage); message WM_DEVICECHANGE;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
// u盘的 插入和删除windows会给所有的程序发出WM_DEVICECHANGE 信息
procedure TForm1.WMDeviceChange (var Msg: TMessage);
var
myMsg : String;
begin
Case Msg.WParam of
32768:
begin
myMsg :='U盘插入';
Label1.Caption:=myMsg
end;
32772:
begin
myMsg :='U盘拔出';
Label1.Caption:=myMsg;
end;
end;
end;
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;
end.
end;