Q in Nt/2000/xp, I would like to use VC to write applications to access hardware devices, such as the acquisition of disk parameters, read and write absolute sector data, testing the actual speed of the CD drive, where to start?
A in nt/2000/xp, an application can access the device via API function DeviceIoControl-get information, send commands, Exchange data, and so on. By using the interface function to send the correct control code and data to the specified device driver, and then analyze its response, we can achieve our goal.
DeviceIoControl 的函数原型为
BOOL DeviceIoControl(
HANDLE hDevice, // 设备句柄
DWORD dwIoControlCode, // 控制码
LPVOID lpInBuffer, // 输入 数据缓冲区指针
DWORD nInBufferSize, // 输入数据缓冲区长度
LPVOID lpOutBuffer, // 输出数据缓冲区指针
DWORD nOutBufferSize, // 输出数据缓冲区长度
LPDWORD lpBytesReturned, // 输出数据实际长度单元长度
LPOVERLAPPED lpOverlapped // 重叠操作结构 指针
);
The device handle identifies the device you are accessing.
Different control codes are sent to invoke different types of features of the device driver. In header file winioctl.h, predefined standard device control codes begin with IOCTL or fsctl. For example
Ioctl_disk_get_drive_geometry is the control code for the physical drive's structure parameters (type of media, number of cylinders, number of tracks per cylinder, number of sectors per track, and so on), Fsctl_lock_volume is the control code that locks the volume of a logical drive.
The input-output data buffer is required, what structure it is, and how much space it occupies, which is entirely determined by the different operating types of the different devices. In the header file winioctl.h, some input and output data structures have been predefined for standard devices. The overlapping action structure pointer is set to Null,deviceiocontrol to block calls, otherwise it should be designed as an asynchronous operation at programming time.
Q where is the device handle obtained?
A device handle can be obtained using API function CreateFile. It's prototype for
HANDLE CreateFile(
LPCTSTR lpFileName, // 文件名
DWORD dwDesiredAccess, // 访问方式 DWORD dwShareMode, // 共享方 式
LPSECURITY_ATTRIBUTES lpSecurityAttributes, // 安全描述符指针
DWORD dwCreationDisposition, // 创建方式
DWORD dwFlagsAndAttributes, // 文件属性及标志
HANDLE hTemplateFile // 模板文件的句柄
);CreateFile This function is very useful, here we use it "open" device driver, get the handle of the device. Close the device handle with CloseHandle when the operation is complete.
Unlike a normal file name, the device-driven "filename" form is fixed to "\\.\devicename" (note that the string is written "\\\\.\\devicename" in the C program) and devicename must match the device name specified in the device driver.
Generally, the access mode parameter is set to 0 or generic_read| when the call CreateFile gets the device handle Generic_write, the shared method parameter is set to
file_share_read| File_share_write, the Create method parameter is set to Open_existing, and the other parameters are set to 0 or NULL.