用vb6.0 写几种 即时检测计算机是否插入U盘 或移动硬盘 的 较为精简代码,
时间: 2024-05-16 19:18:17 浏览: 102
检测u盘是否插入
以下是使用VB6.0编写的两种即时检测计算机是否插入U盘或移动硬盘的较为精简的代码:
方法一:使用WMI查询
首先需要在“引用”中添加“Microsoft WMI Scripting Library”。
```
Dim strComputer, strQuery, strDriveType, strDriveLetter
Dim objWMIService, colItems, objItem
strComputer = "."
strQuery = "SELECT * FROM Win32_LogicalDisk WHERE (DriveType = 2 OR DriveType = 3)"
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery(strQuery)
For Each objItem In colItems
strDriveType = objItem.DriveType
strDriveLetter = objItem.DeviceID
If strDriveType = 2 Or strDriveType = 3 Then
MsgBox "U盘或移动硬盘已插入:" & strDriveLetter
End If
Next
```
方法二:使用API调用
需要在模块中声明以下函数:
```
Public Declare Function GetDriveType Lib "kernel32" Alias "GetDriveTypeA" _
(ByVal nDrive As String) As Long
Public Declare Function GetLogicalDriveStrings Lib "kernel32" Alias "GetLogicalDriveStringsA" _
(ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
```
然后使用以下代码进行检测:
```
Dim strDrives, strDrive
Dim nDriveType
strDrives = Space(255)
Call GetLogicalDriveStrings(255, strDrives)
strDrives = Left(strDrives, InStr(1, strDrives, vbNullChar) - 1)
For Each strDrive In Split(strDrives, vbNullChar)
nDriveType = GetDriveType(strDrive)
If nDriveType = 2 Or nDriveType = 3 Then
MsgBox "U盘或移动硬盘已插入:" & strDrive
End If
Next
```
阅读全文