VB 高手请进

2024-12-15 21:24:40
推荐回答(1个)
回答1:

你没有理解GetDiskFreeSpace函数的用法,这个函数的返回值,并非是剩余字节数,而是一个表示函数是否执行成功的Long型变量,如果不成功则返回0,否则为非零值。你直接调用,自然出错。

仔细看函数的参数,各参数意义如下:
参数 类型及说明
lpRootPathName String,不包括卷名的一个磁盘根路径
lpSectorsPerCluster Long,用于装载一个簇内扇区数的变量
lpBytesPerSector Long,用于装载一个扇区内字节数的变量
lpNumberOfFreeClusters Long,用于装载磁盘上剩余簇数的变量
lpTtoalNumberOfClusters Long,用于装载磁盘上总簇数的变量

也就是说,当执行完这个函数后,函数将得到的磁盘信息分别存在了lpSectorsPerCluster、lpBytesPerSector、lpNumberOfFreeClusters、lpTtoalNumberOfClusters四个参数名称对应的变量中,并将执行是否成功的情况作为返回值。具体的空间数需要根据四个参数的值来计算.

范例:

Option Explicit
Private Declare Function GetDiskFreeSpace Lib "kernel32" Alias "GetDiskFreeSpaceA" (ByVal lpRootPathName As String, lpSectorsPerCluster As Long, lpBytesPerSector As Long, lpNumberOfFreeClusters As Long, lpTotalNumberOfClusters As Long) As Long

Private Sub Form_Load()
Dim SectorsPerCluster As Long '一个簇内扇区数
Dim BytesPerSector As Long '一个扇区内字节数
Dim NumberOfFreeClusters As Long '剩余簇数
Dim TotalNumberOfClusters As Long '总簇数
Dim FreeKBytes As Long '剩余KB数
Dim TotalKBytes As Long '总KB数
Dim Result
Result = GetDiskFreeSpace("F:\", SectorsPerCluster, BytesPerSector, NumberOfFreeClusters, TotalNumberOfClusters)
FreeKBytes = (NumberOfFreeClusters / 1024) * SectorsPerCluster * BytesPerSector
TotalKBytes = (TotalNumberOfClusters / 1024) * SectorsPerCluster * BytesPerSector
Text1.Text = FreeKBytes
Text2.text = TotalKBytes
End Sub

----------------------------------------------------

另外,再告诉你一种简便的方法,在“引用”中添加“Microsoft Scripting Runtime”后,可直接调用FSO对象来实现你要的功能:

Private Sub Form_Load()
Dim objFso As New FileSystemObject, Drv As Drive
Set objDrv = objFso.GetDrive("f:\")
If objDrv.IsReady Then
TotalSpace = Format(objDrv.TotalSize / (2 ^ 20), "0.00")
Else
TotalSpace = 0
End If
Set objFso = Nothing
Set objDrv = Nothing
Text1.Text = TotalSpace & " M"
End Sub