【DeviceIOControl】 一、通过API访问设备驱动程序
在NT/2000/XP中,如果想用VC编写应用程序访问硬件设备,如获取磁盘参数、读写绝对扇区数据、测试光驱实际速度等,该从哪里入手呢?
在NT/2000/XP中,应用程序可以通过API函数DeviceIoControl来实现对设备的访问—获取信息,发送命令,交换数据等。利用该接口函数向指定的设备驱动发送正确的控制码及数据,然后分析它的响应,就可以达到我们的目的。
DeviceIoControl的函数原型为
BOOL DeviceIoControl( HANDLE hDevice, // 设备句柄 DWORD dwIoControlCode, // 控制码 LPVOID lpInBuffer, // 输入数据缓冲区指针 DWORD nInBufferSize, // 输入数据缓冲区长度 LPVOID lpOutBuffer, // 输出数据缓冲区指针 DWORD nOutBufferSize, // 输出数据缓冲区长度 LPDWORD lpBytesReturned, // 输出数据实际长度单元长度 LPOVERLAPPED lpOverlapped // 重叠操作结构指针);
HANDLE CreateFile( LPCTSTR lpFileName, // 文件名 DWORD dwDesiredAccess, // 访问方式 DWORD dwShareMode, // 共享方式 LPSECURITY_ATTRIBUTES lpSecurityAttributes, // 安全描述符指针 DWORD dwCreationDisposition, // 创建方式 DWORD dwFlagsAndAttributes, // 文件属性及标志 HANDLE hTemplateFile // 模板文件的句柄);
软盘驱动器 A:, B:逻辑驱动器 C:, D:, E:, ……物理驱动器 PHYSICALDRIVExCD-ROM, DVD/ROM CDROMx磁带机 TAPEx
/* The code of interest is in the subroutine GetDriveGeometry. The code in main shows how to interpret the results of the IOCTL call. */#include <windows.h>#include <winioctl.h>BOOL GetDriveGeometry(DISK_GEOMETRY *pdg){ HANDLE hDevice; // handle to the drive to be examined BOOL bResult; // results flag DWORD junk; // discard results hDevice = CreateFile("\\\\.\\PhysicalDrive0", // drive to open 0, // no access to the drive FILE_SHARE_READ | // share mode FILE_SHARE_WRITE, NULL, // default security attributes OPEN_EXISTING, // disposition 0, // file attributes NULL); // do not copy file attributes if (hDevice == INVALID_HANDLE_VALUE) // cannot open the drive { return (FALSE); } bResult = DeviceIoControl(hDevice, // device to be queried IOCTL_DISK_GET_DRIVE_GEOMETRY, // operation to perform NULL, 0, // no input buffer pdg, sizeof(*pdg), // output buffer &junk, // # bytes returned (LPOVERLAPPED) NULL); // synchronous I/O CloseHandle(hDevice); return (bResult);}int main(int argc, char *argv[]){ DISK_GEOMETRY pdg; // disk drive geometry structure BOOL bResult; // generic results flag ULONGLONG DiskSize; // size of the drive, in bytes bResult = GetDriveGeometry (&pdg); if (bResult) { printf("Cylinders = %I64d\n", pdg.Cylinders); printf("Tracks per cylinder = %ld\n", (ULONG) pdg.TracksPerCylinder); printf("Sectors per track = %ld\n", (ULONG) pdg.SectorsPerTrack); printf("Bytes per sector = %ld\n", (ULONG) pdg.BytesPerSector); DiskSize = pdg.Cylinders.QuadPart * (ULONG)pdg.TracksPerCylinder * (ULONG)pdg.SectorsPerTrack * (ULONG)pdg.BytesPerSector; printf("Disk size = %I64d (Bytes) = %I64d (Mb)\n", DiskSize, DiskSize / (1024 * 1024)); } else { printf ("GetDriveGeometry failed. Error %ld.\n", GetLastError ()); } return ((int)bResult);}