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
-
hDevice
A handle to the device for which control operations are to be performed. This handle is obtained by calling the
CreateFile
function. -
dwIoControlCode
The driver-specified I/O control code (IOCTL) for the operation to perform. This parameter value identifies the specific operation to be performed.
-
lpInBuffer
A pointer to the buffer that contains data required by the driver to perform the specified operation. If this parameter is NULL and the
dwIoControlCode
parameter specifies an operation that does not require input data, this parameter can be NULL. -
nInBufferSize
The size, in bytes, of the buffer pointed to by
lpInBuffer
. -
lpOutBuffer
A pointer to the buffer that receives output from the specified operation. If this parameter is NULL and the
dwIoControlCode
parameter specifies an operation that does not produce output data, this parameter can be NULL. -
nOutBufferSize
The size, in bytes, of the buffer pointed to by
lpOutBuffer
. -
lpBytesReturned
A pointer to a
DWORD
value that receives the size, in bytes, of the data written to the buffer pointed to bylpOutBuffer
. IflpOutBuffer
is not NULL, this parameter can be NULL. IflpOutBuffer
is NULL, this parameter must be NULL. -
lpOverlapped
A pointer to a
OVERLAPPED
structure that is used for asynchronous operations. IfhDevice
was opened with theFILE_FLAG_OVERLAPPED
flag, this parameter is required. IfhDevice
was opened without theFILE_FLAG_OVERLAPPED
flag, 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.