资源描述:
《DELPHI编程捕获U盘插入或者拔出》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、DELPHI编程捕获U盘插入或者拔出翻了下老帖子,月亮写的,根据LS发的MSDN翻译的源地址:http://topic.csdn.net/u/20090628/16/96e73f9e-5e74-4bed-bb75-2f18a0e9cb02.htmlDelphi(Pascal)codefunctionOpenVolume(ADrive:char):THandle;varRootName,VolumeName:string;AccessFlags:DWORD;beginRootName:=ADrive+':'+#134;//ADrive+':'kil
2、lsthesyntaxhighlightingcaseGetDriveType(PChar(RootName))ofDRIVE_REMOVABLE:AccessFlags:=GENERIC_READorGENERIC_WRITE;DRIVE_CDROM:AccessFlags:=GENERIC_READ;elseResult:=INVALID_HANDLE_VALUE;exit;end;VolumeName:=Format('\.%s:',[ADrive]);Result:=CreateFile(PChar(VolumeName),Access
3、Flags,FILE_SHARE_READorFILE_SHARE_WRITE,nil,OPEN_EXISTING,0,0);ifResult=INVALID_HANDLE_VALUEthenRaiseLastWin32Error;end;functionLockVolume(AVolumeHandle:THandle):boolean;constLOCK_TIMEOUT=10*1000;//10SecondsLOCK_RETRIES=20;LOCK_SLEEP=LOCK_TIMEOUTdivLOCK_RETRIES;//#defineFSCTL_
4、LOCK_VOLUMECTL_CODE(FILE_DEVICE_FILE_SYSTEM,6,METHOD_BUFFERED,FILE_ANY_ACCESS)FSCTL_LOCK_VOLUME=(9shl16)or(0shl14)or(6shl2)or0;varRetries:integer;BytesReturned:Cardinal;beginforRetries:=1toLOCK_RETRIESdobeginResult:=DeviceIoControl(AVolumeHandle,FSCTL_LOCK_VOLUME,nil,0,nil,0,B
5、ytesReturned,nil);ifResultthenbreak;Sleep(LOCK_SLEEP);end;end;functionDismountVolume(AVolumeHandle:THandle):boolean;const//#defineFSCTL_DISMOUNT_VOLUMECTL_CODE(FILE_DEVICE_FILE_SYSTEM,8,METHOD_BUFFERED,FILE_ANY_ACCESS)FSCTL_DISMOUNT_VOLUME=(9shl16)or(0shl14)or(8shl2)or0;varByt
6、esReturned:Cardinal;beginResult:=DeviceIoControl(AVolumeHandle,FSCTL_DISMOUNT_VOLUME,nil,0,nil,0,BytesReturned,nil);ifnotResultthenRaiseLastWin32Error;end;functionPreventRemovalOfVolume(AVolumeHandle:THandle;APreventRemoval:boolean):boolean;const//#defineIOCTL_STORAGE_MEDIA_RE
7、MOVALCTL_CODE(IOCTL_STORAGE_BASE,0x0201,METHOD_BUFFERED,FILE_READ_ACCESS)IOCTL_STORAGE_MEDIA_REMOVAL=($2dshl16)or(1shl14)or($201shl2)or0;typeTPreventMediaRemoval=recordPreventMediaRemoval:BOOL;end;varBytesReturned:Cardinal;PMRBuffer:TPreventMediaRemoval;beginPMRBuffer.PreventM
8、ediaRemoval:=APreventRemoval;Result:=DeviceIoControl(AVolumeH