Delphi监视U盘的状态代码范例

其实系统中的任何事件都是有消息的,U盘的插拨也不例外,让程序去接收这些消息就能知道U盘的状态
此处我写了一个Demo程序,用来监视U盘插上或拨下。

主要的问题就在如何去接收消息,以及接收什么消息。
在DBT单元中,封装了与驱动有关的消息及API,我们只需要稍做研究,即可写出这个程序了。

一、接管消息

procedure TFormMain.WndProc(var Message: TMessage);
var
hdr: PDevBroadcastHdr;
vol: PDevBroadcastVolume;
begin
if Message.Msg = WM_DEVICECHANGE then
begin
     case Message.WParam of
       DBT_DEVICEARRIVAL:
         begin

           hdr := PDevBroadcastHdr(Message.LParam);
           if hdr.dbch_devicetype = DBT_DEVTYP_VOLUME then
           begin
             vol := PDevBroadcastVolume(Message.LParam);
             if vol.dbcv_flags = 0 then
               AddDisk;
           end; 

         end;
       DBT_DEVICEREMOVECOMPLETE:
         RemoveDisk;
     end;
end;

inherited;
end;

注意上面标红字的地方,这些就是我们需要的消息,接到这个消息就成功了一半了。
接下面,我们来实现AddDisk()和RemoveDisk()方法,这两个方法用于在程序界面上显示或移除设备。

二、显示已插上的U盘,除除已拨下的U盘

procedure TFormMain.AddDisk;
var
diskPath: string;
i: Integer;
begin
diskPath := 'C:\\';
for i:= $43 to $5A do
begin
     diskPath[1] := Char(i);
     if GetDriveType(PChar(diskPath)) = DRIVE_REMOVABLE then
     begin
       if lstUDisk.Items.IndexOf(Format(UDiskFmt, [diskPath[1]])) = -1 then
       begin
         lstUDisk.Items.Add(Format(UDiskFmt, [diskPath[1]]));
         Break;
       end;
     end;
end;
end;

procedure TFormMain.RemoveDisk;
var
diskPath: string;
i: Integer;
begin
diskPath := 'C:\\';
for i:= $43 to $5A do
begin
     diskPath[1] := Char(i);
     if GetDriveType(PChar(diskPath)) = DRIVE_NO_ROOT_DIR then
     begin
       if lstUDisk.Items.IndexOf(Format(UDiskFmt, [diskPath[1]])) > -1 then
       begin
         lstUDisk.Items.Delete(lstUDisk.Items.IndexOf(Format(UDiskFmt, [diskPath[1]])));
         Break;
       end;
     end;
end;
end;

在上面的代码中,需要注意的是设备的状态。因为从接到的消息来看,我们找不到U盘的盘符
只能够通过此方法进行设备的遍历。

posted @ 2013-04-28 15:26  小天1981  阅读(371)  评论(0编辑  收藏  举报