DeviceIoControl Function
The DeviceIoControl function sends a control code directly to a specified device driver, causing the driver to perform the specified action.
BOOL DeviceIoControl(
HANDLE hDevice,
DWORD dwIoControlCode,
LPVOID lpInBuffer,
DWORD nInBufferSize,
LPVOID lpOutBuffer,
DWORD nOutBufferSize,
LPDWORD lpBytesReturned,
LPOVERLAPPED lpOverlapped
);
Parameters
-
hDeviceA handle to the device for which control operations are to be performed. This handle is obtained by calling the
CreateFilefunction. -
dwIoControlCodeThe driver-specified I/O control code (IOCTL) for the operation to perform. This parameter value identifies the specific operation to be performed.
-
lpInBufferA pointer to the buffer that contains data required by the driver to perform the specified operation. If this parameter is NULL and the
dwIoControlCodeparameter specifies an operation that does not require input data, this parameter can be NULL. -
nInBufferSizeThe size, in bytes, of the buffer pointed to by
lpInBuffer. -
lpOutBufferA pointer to the buffer that receives output from the specified operation. If this parameter is NULL and the
dwIoControlCodeparameter specifies an operation that does not produce output data, this parameter can be NULL. -
nOutBufferSizeThe size, in bytes, of the buffer pointed to by
lpOutBuffer. -
lpBytesReturnedA pointer to a
DWORDvalue that receives the size, in bytes, of the data written to the buffer pointed to bylpOutBuffer. IflpOutBufferis not NULL, this parameter can be NULL. IflpOutBufferis NULL, this parameter must be NULL. -
lpOverlappedA pointer to a
OVERLAPPEDstructure that is used for asynchronous operations. IfhDevicewas opened with theFILE_FLAG_OVERLAPPEDflag, this parameter is required. IfhDevicewas opened without theFILE_FLAG_OVERLAPPEDflag, this parameter can be NULL.
Return Value
If the operation completes successfully, DeviceIoControl returns a nonzero value.
If the operation fails, the return value is zero. To get extended error information, call GetLastError.
Remarks
The DeviceIoControl function is the primary mechanism for applications and services to communicate with device drivers. It allows for a wide range of custom interactions beyond standard file operations.
IOCTL codes are typically defined by the device driver developer. They are often structured using macros like CTL_CODE to specify device type, access method, and function code.
// Example of a common IOCTL definition
#define IOCTL_MY_DEVICE_GET_STATUS CTL_CODE(FILE_DEVICE_UNKNOWN, 0x0001, METHOD_BUFFERED, FILE_ANY_ACCESS)
For asynchronous operations, the OVERLAPPED structure must be properly initialized. The function will return immediately, and the operation's completion can be signaled via an event object or by calling GetOverlappedResult.
nInBufferSize and nOutBufferSize) are correctly specified to avoid buffer overflows or incomplete data transfers.