




已阅读5页,还剩24页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
DELPHI编程捕获U盘插入或者拔出 翻了下老帖子,月亮写的,根据LS发的MSDN翻译的源地址:/u/20090628/16/96e73f9e-5e74-4bed-bb75-2f18a0e9cb02.htmlDelphi(Pascal) codefunction OpenVolume(ADrive: char): THandle;var RootName, VolumeName: string; AccessFlags: DWORD;begin RootName := ADrive + : + #134; / ADrive + : kills the syntax highlighting case GetDriveType(PChar(RootName) of DRIVE_REMOVABLE: AccessFlags := GENERIC_READ or GENERIC_WRITE; DRIVE_CDROM: AccessFlags := GENERIC_READ; else Result := INVALID_HANDLE_VALUE; exit; end; VolumeName := Format(.%s:, ADrive); Result := CreateFile(PChar(VolumeName), AccessFlags, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, 0, 0); if Result = INVALID_HANDLE_VALUE then RaiseLastWin32Error;end;function LockVolume(AVolumeHandle: THandle): boolean;const LOCK_TIMEOUT = 10 * 1000; / 10 Seconds LOCK_RETRIES = 20; LOCK_SLEEP = LOCK_TIMEOUT div LOCK_RETRIES;/ #define FSCTL_LOCK_VOLUME CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 6, METHOD_BUFFERED, FILE_ANY_ACCESS) FSCTL_LOCK_VOLUME = (9 shl 16) or (0 shl 14) or (6 shl 2) or 0;var Retries: integer; BytesReturned: Cardinal;begin for Retries := 1 to LOCK_RETRIES do begin Result := DeviceIoControl(AVolumeHandle, FSCTL_LOCK_VOLUME, nil, 0, nil, 0, BytesReturned, nil); if Result then break; Sleep(LOCK_SLEEP); end;end;function DismountVolume(AVolumeHandle: THandle): boolean;const/ #define FSCTL_DISMOUNT_VOLUME CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 8, METHOD_BUFFERED, FILE_ANY_ACCESS) FSCTL_DISMOUNT_VOLUME = (9 shl 16) or (0 shl 14) or (8 shl 2) or 0;var BytesReturned: Cardinal;begin Result := DeviceIoControl(AVolumeHandle, FSCTL_DISMOUNT_VOLUME, nil, 0, nil, 0, BytesReturned, nil); if not Result then RaiseLastWin32Error;end;function PreventRemovalOfVolume(AVolumeHandle: THandle; APreventRemoval: boolean): boolean;const/ #define IOCTL_STORAGE_MEDIA_REMOVAL CTL_CODE(IOCTL_STORAGE_BASE, 0x0201, METHOD_BUFFERED, FILE_READ_ACCESS) IOCTL_STORAGE_MEDIA_REMOVAL = ($2d shl 16) or (1 shl 14) or ($201 shl 2) or 0;type TPreventMediaRemoval = record PreventMediaRemoval: BOOL; end;var BytesReturned: Cardinal; PMRBuffer: TPreventMediaRemoval;begin PMRBuffer.PreventMediaRemoval := APreventRemoval; Result := DeviceIoControl(AVolumeHandle, IOCTL_STORAGE_MEDIA_REMOVAL, PMRBuffer, SizeOf(TPreventMediaRemoval), nil, 0, BytesReturned, nil); if not Result then RaiseLastWin32Error;end;function AutoEjectVolume(AVolumeHandle: THandle): boolean;const/ #define IOCTL_STORAGE_EJECT_MEDIA CTL_CODE(IOCTL_STORAGE_BASE, 0x0202, METHOD_BUFFERED, FILE_READ_ACCESS) IOCTL_STORAGE_EJECT_MEDIA = ($2d shl 16) or (1 shl 14) or ($202 shl 2) or 0;var BytesReturned: Cardinal;begin Result := DeviceIoControl(AVolumeHandle, IOCTL_STORAGE_EJECT_MEDIA, nil, 0, nil, 0, BytesReturned, nil); if not Result then RaiseLastWin32Error;end;function EjectVolume(ADrive: char): boolean;var VolumeHandle: THandle;begin Result := FALSE; / Open the volume VolumeHandle := OpenVolume(ADrive); if VolumeHandle = INVALID_HANDLE_VALUE then exit; try / Lock and dismount the volume if LockVolume(VolumeHandle) and DismountVolume(VolumeHandle) then begin / Set prevent removal to false and eject the volume if PreventRemovalOfVolume(VolumeHandle, FALSE) then AutoEjectVolume(VolumeHandle); end; finally / Close the volume so other processes can use the drive CloseHandle(VolumeHandle); end;end;2010-07-02 15:04在USB端口port被热插后,操作系统会向所有程式正式发布WM_DEVICECHANGE消息,所以只要捕获此消息即可呈现对U盘的监视。 1、新建工程; 2、在form1上放唯一Label; 3、定义唯一私有过程 procedure WMDeviceChange(var Msg: TMessage); message WM_DEVICECHANGE; 完整代码Code如下: unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, AppEvnts, ExtCtrls, StdCtrls; type TForm1 = class(TForm) Label1: TLabel; 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盘插入; Label1.Caption:=myMsg end; 32772: begin myMsg :=U盘拔出; Label1.Caption:=myMsg; end; end; end; End.此代码未经调试const CfgMgr32ModuleName = cfgmgr32.dll; SetupApiModuleName = SetupApi.dll; REGSTR_VAL_NODISPLAYCLASS = NoDisplayClass; CR_SUCCESS = $00000000; CR_REMOVE_VETOED = $00000017; DN_HAS_PROBLEM = $00000400; DN_DISABLEABLE = $00002000; DN_REMOVABLE = $00004000; DN_NO_SHOW_IN_DM = $40000000; CM_PROB_DISABLED = $00000016; CM_PROB_HARDWARE_DISABLED = $0000001D; type _PNP_VETO_TYPE = ( PNP_VetoTypeUnknown, PNP_VetoLegacyDevice, PNP_VetoPendingClose, PNP_VetoWindowsApp, PNP_VetoWindowsService, PNP_VetoOutstandingOpen, PNP_VetoDevice, PNP_VetoDriver, PNP_VetoIllegalDeviceRequest, PNP_VetoInsufficientPower, PNP_VetoNonDisableable, PNP_VetoLegacyDriver ); PNP_VETO_TYPE = _PNP_VETO_TYPE; PPNP_VETO_TYPE = _PNP_VETO_TYPE; TPNPVetoType = _PNP_VETO_TYPE; PPNPVetoType = PPNP_VETO_TYPE; function CM_Get_DevNode_Status(pulStatus: PULong; pulProblemNumber: PULong; dnDevInst: DWord; ulFlags: ULong): DWord; stdcall; external CfgMgr32ModuleName name CM_Get_DevNode_Status; function CM_Request_Device_Eject(dnDevInst: DWord; out pVetoType: TPNPVetoType; pszVetoName: PChar; ulNameLength: ULong; ulFlags: ULong): DWord; stdcall; external SetupApiModuleName name CM_Request_Device_EjectA; type TForm1 = class(TForm) TreeView: TTreeView; ImageList: TImageList; MainMenu1: TMainMenu; Eject1: TMenuItem; Exit1: TMenuItem; Change1: TMenuItem; ShowHidden1: TMenuItem; EjectDriver1: TMenuItem; Exit2: TMenuItem; procedure FormCreate(Sender: TObject); procedure ShowHidden1Click(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure EjectDriver1Click(Sender: TObject); procedure Exit2Click(Sender: TObject); procedure TreeViewClick(Sender: TObject); private DevInfo: hDevInfo; ClassImageListData: TSPClassImageListData; ShowHidden: Boolean; function EnumAddDevices(ShowHidden: Boolean; hwndTree: TTreeView; DevInfo: hDevInfo): Boolean; function IsClassHidden(ClassGuid: TGuid): Boolean; function GetRegistryProperty(PnPHandle: hDevInfo; DevData: TSPDevInfoData; Prop: DWord; Buffer: PChar; dwLength: DWord): Boolean; function ConstructDeviceName(DeviceInfoSet: hDevInfo; DeviceInfoData: TSPDevInfoData; Buffer: PChar; dwLength: DWord): Boolean; function GetClassImageIndex(ClassGuid: TGuid; Index: PInt): Boolean; function GetDevInfo(var hDevInfo: hDevInfo): boolean; Private declarations public Public declarations end; var Form1: TForm1; implementation $R *.dfm function TForm1.GetDevInfo(var hDevInfo: hDevInfo): boolean; begin if (assigned(DevInfo) then begin SetupDiDestroyDeviceInfoList(DevInfo); SetupDiDestroyClassImageList(ClassImageListData); end; / Get a handle to all devices in all classes present on system DevInfo := SetupDiGetClassDevs(nil, nil, 0, DIGCF_PRESENT or DIGCF_ALLCLASSES); if (DevInfo = Pointer(INVALID_HANDLE_VALUE) then begin ShowMessage(GetClassDevs); exit; end; / Get the Images for all classes, and bind to the TreeView ClassImageListData.cbSize := SizeOf(TSPClassImageListData); if (not SetupDiGetClassImageList(ClassImageListData) then begin ShowMessage(GetClassImageList); exit; end; ImageList.Handle := ClassImageListData.ImageList; TreeView.Images := ImageList; end; function TForm1.GetClassImageIndex(ClassGuid: TGuid; Index: PInt): Boolean; begin Result := SetupDiGetClassImageIndex(ClassImageListData, ClassGuid, Index); end; function TForm1.GetRegistryProperty(PnPHandle: hDevInfo; DevData: TSPDevInfoData; Prop: DWord; Buffer: PChar; dwLength: DWord): Boolean; var aBuffer: array0.256 of Char; begin dwLength := 0; aBuffer0 := #0; SetupDiGetDeviceRegistryProperty(PnPHandle, DevData, Prop, Prop, PBYTE(aBuffer0), SizeOf(aBuffer), dwLength); StrCopy(Buffer, aBuffer); Result := Buffer #0; end; -function TForm1.ConstructDeviceName(DeviceInfoSet: hDevInfo; DeviceInfoData: TSPDevInfoData; Buffer: PChar; dwLength: DWord): Boolean; const UnknownDevice = ; begin if (not GetRegistryProperty(DeviceInfoSet, DeviceInfoData, SPDRP_FRIENDLYNAME, Buffer, dwLength) then begin if (not GetRegistryProperty(DeviceInfoSet, DeviceInfoData, SPDRP_DEVICEDESC, Buffer, dwLength) then begin if (not GetRegistryProperty(DeviceInfoSet, DeviceInfoData, SPDRP_CLASS, Buffer, dwLength) then begin if (not GetRegistryProperty(DeviceInfoSet, DeviceInfoData, SPDRP_CLASSGUID, Buffer, dwLength) then begin dwLength := DWord(SizeOf(UnknownDevice); Buffer := Pointer(LocalAlloc(LPTR, Cardinal(dwLength); StrCopy(Buffer, UnknownDevice); end; end; end; end; Result := true; end; function TForm1.IsClassHidden(ClassGuid: TGuid): Boolean; var bHidden: Boolean; hKeyClass: HKey; begin bHidden := false; hKeyClass := SetupDiOpenClassRegKey(ClassGuid, KEY_READ); if (hKeyClass 0) then begin bHidden := (RegQueryValueEx(hKeyClass, REGSTR_VAL_NODISPLAYCLASS, nil, nil, nil, nil) = ERROR_SUCCESS); RegCloseKey(hKeyClass); end; Result := bHidden; end; function TForm1.EnumAddDevices(ShowHidden: Boolean; hwndTree: TTreeView; DevInfo: hDevInfo): Boolean; var i, Status, Problem: DWord; pszText: PChar; DeviceInfoData: TSPDevInfoData; iImage: Integer; begin TTreeView(hWndTree).Items.BeginUpdate; DeviceInfoData.cbSize := SizeOf(TSPDevInfoData); / Clean off all the items in a TreeView. TTreeView(hWndTree).Items.Clear; i := 0; / Enumerate though all the devices. while SetupDiEnumDeviceInfo(DevInfo, i, DeviceInfoData) do begin inc(i); / Should we display this device, or move onto the next one. if (CM_Get_DevNode_Status(Status, Problem, DeviceInfoData.DevInst, 0) CR_SUCCESS) then begin break; end; if (not (ShowHidden or not(Boolean(Status and DN_NO_SHOW_IN_DM) or IsClassHidden(DeviceInfoData.ClassGuid) then begin break; end; GetMem(pszText, 256); try / Get a friendly name for the device. ConstructDeviceName(DevInfo, DeviceInfoData, pszText, DWord(nil); / Try to get an icon index for this device. if (GetClassImageIndex(DeviceInfoData.ClassGuid, iImage) then begin with TTreeView(hWndTree).Items.AddObject(nil, pszText, nil) do begin TTreeView(hWndTree).Itemsi-1.ImageIndex := iImage; TTreeView(hWndTree).Itemsi-1.SelectedIndex := iImage; end; if (Problem = CM_PROB_DISABLED) then / red (X) begin TTreeView(hWndTree).Itemsi-1.OverlayIndex := IDI_DISABLED_OVL - IDI_CLASSICON_OVERLAYFIRST; end else begin if (Boolean(Problem) then / yellow (!) begin TTreeView(hWndTree).Itemsi-1.OverlayIndex := IDI_PROBLEM_OVL - IDI_CLASSICON_OVERLAYFIRST; end; end; if (Status and DN_NO_SHOW_IN_DM = DN_NO_SHOW_IN_DM) then / Greyed out begin TTreeView(hWndTree).Itemsi-1.Cut := true; end; end; finally FreeMem(pszText); end; end; TTreeView(hWndTree).Items.EndUpdate; Result := true; end; procedure TForm1.FormCreate(Sender: TObject); begin if (not LoadSetupAPI) then begin ShowMessage(Could not load SetupAPI.dll); exit; end; DevInfo := nil; ShowHidden := false; / Get a handle to all devices in all classes present on system if not GetDevInfo(DevInfo) then begin ShowMessage(GetClassDevs); exit; end; / Get the Images for all classes, and bind to the TreeView ClassImageListData.cbSize := SizeOf(TSPClassImageListData); if (not SetupDiGetClassImageList(ClassImageListData) then begin ShowMessage(GetClassImageList); exit; end; ImageList.Handle := ClassImageListData.ImageList; TreeView.Images := ImageList; / Add the devices to the TreeView window. EnumAddDevices(ShowHidden, TreeView, DevInfo); end; procedure TForm1.EjectDriver1Click(Sender: TObject); var DeviceInfoData: TSPDevInfoData; Status, Problem: DWord; VetoType: TPNPVetoType; VetoName: array0.256 of Char; begin DeviceInfoData.cbSize := SizeOf(TSPDevInfoData); / Get a handle to the Selected Item. if (not SetupDiEnumDeviceInfo(DevInfo, TreeView.Selected.Index, DeviceInfoData) then begin exit; end; if (CM_Get_DevNode_Status(Status, Problem, DeviceInfoData.DevInst, 0) CR_SUCCESS) then begin exit; end; VetoName0 := #0; case CM_Request_Device_Eject(DeviceInfoData.DevInst, VetoType, VetoName, SizeOf(VetoName), 0) of CR_SUCCESS: begin MessageBox(Handle, Successful to eject the Device, Done, MB_OK); if not GetDevInfo(DevInfo) then begin ShowMessage(GetClassDevs); end; EnumAddDevices(ShowHidden, TreeView, DevInfo); end; CR_REMOVE_VETOED: begin MessageBox(Handle, PChar(Failed to eject the Device (Veto: + VetoName + ), Vetoed, MB_OK); end; else begin MessageBox(Handle, PChar(Failed to eject the Device ( + SysErrorMessage(GetLastError) + ), Failure, MB_OK); end; end; end; procedure TForm1.ShowHidden1Click(Sender: TObject); begin ShowHidden := not ShowHidden; EnumAddDevices(ShowHidden, TreeView, DevInfo); end; procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin canclose:=application.MessageBox(你真的要退出吗?,系统提示,mb_yesno+MB_ICONQUESTION)=idyes ; if canclose then begin Application.Terminate; end; end; procedure TForm1.Exit2Click(Sender: TObject); begin Close; end; End.#include #pragma comment( lib, setupapi.lib ) #define DWORD_PTR DWORD #define ULONG_PTR DWORD DEFINE_GUID(GUID_DEVINTERFACE_USB_DEVICE, 0xA5DCBF10L, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED); #define GUID_CLASS_USB_DEVICE GUID_DEVINTERFACE_USB_DEVICE HDEVINFO hDevInfo; SP_DEVINFO_DATA DeviceInfoData; DWORD i; /- / 获取设备信息 hDevInfo = SetupDiGetClassDevs(LPGUID)&GUID_CLASS_USB_DEVICE, NULL, / Enumerator NULL, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE ); if(hDevInfo = INVALID_HANDLE_VALUE) / 查询信息失败 return; /- / 枚举每个USB设备 DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA); for (i=0;SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData);i+) ULONG len; CONFIGRET cr; PNP_VETO_TYPE pnpvietotype; CHAR vetonameMAX_PATH; ULONG ulStatus; ULONG ulProblemNumber; cr = CM_Get_DevNode_Status( &ulStatus, &ulProblemNumber, DeviceInfoData.DevInst, 0); if(CR_SUCCESS = cr) CString str; str.Format( OK - CM_Get_DevNode_Status()%drnOK - CM_Get_DevNode_Status() sts %xrnOK - CM_Get_DevNode_Status() pro %xrn ,cr,ulStatus,ul
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 二零二五年度互联网+创业合伙人战略合作框架协议
- 二零二五年度快递服务与客户全面合作协议书
- 二零二五年度房地产买卖代理合同范本(含维修责任)
- 2025版酒店客房清洁用品绿色环保采购协议
- 2025版智能家居灯光租赁个人住房合同
- 二零二五年木结构桥梁维护保养与检测合同
- 2025版医疗健康金融贷款合同范本
- 二零二五年度企业信息化系统升级服务承包合同
- 培训法律知识总结报告课件
- 二零二五年养老服务业承包劳务服务协议
- 慢性疾病管理与健康指导手册
- 2025年高中音乐教师招聘考试测试题及参考答案
- 主持人基础知识培训课件
- 2025年储能运维面试题及答案
- 2025年安徽演艺集团有限责任公司招聘20人笔试备考题库及答案详解(名师系列)
- 2025年事业单位考试医学基础知识真题及答案解析(医疗卫生系统)
- 建筑工地基孔肯雅热防控和应急方案
- 车间现场6S管理课件
- 计量基础知识培训课件
- 2025年新反洗钱知识竞赛题库(附含答案)
- 融媒体中心媒资管理办法
评论
0/150
提交评论