Microsoft Docs

DeviceIoControl

The DeviceIoControl function sends a control code directly to a specified device driver, causing the corresponding driver to perform the associated operation.

Syntax

BOOL DeviceIoControl(
    HANDLE hDevice,
    DWORD dwIoControlCode,
    LPVOID lpInBuffer,
    DWORD nInBufferSize,
    LPVOID lpOutBuffer,
    DWORD nOutBufferSize,
    LPDWORD lpBytesReturned,
    LPOVERLAPPED lpOverlapped
);

Parameters

ParameterDescription
hDeviceHandle to the device on which the operation will be performed. Obtained by calling CreateFile.
dwIoControlCodeControl code of the operation to perform. Defined in the driver-specific header files.
lpInBufferPointer to the input buffer that contains the data required to perform the operation. Can be NULL if not needed.
nInBufferSizeSize of the input buffer, in bytes.
lpOutBufferPointer to the output buffer that receives the data returned by the device. Can be NULL if not needed.
nOutBufferSizeSize of the output buffer, in bytes.
lpBytesReturnedPointer to a variable that receives the size of the data stored in the output buffer.
lpOverlappedPointer to an OVERLAPPED structure for asynchronous operations. Can be NULL for synchronous calls.

Return value

Returns TRUE if the operation succeeds; otherwise FALSE. For extended error information, call GetLastError.

Remarks

DeviceIoControl is the primary way applications communicate with drivers. The control code defines the request and the expected input/output buffers. Drivers must validate all buffers and return appropriate status codes.

When performing I/O with removable media, ensure the device handle was opened with the FILE_FLAG_OVERLAPPED flag for asynchronous operations.

Example

#include <windows.h>
#include <stdio.h>

int main(void) {
    HANDLE hDevice = CreateFileA(
        "\\\\.\\PhysicalDrive0",
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        OPEN_EXISTING,
        0,
        NULL);

    if (hDevice == INVALID_HANDLE_VALUE) {
        printf("CreateFile failed: %lu\\n", GetLastError());
        return 1;
    }

    DWORD bytesReturned;
    BOOL result = DeviceIoControl(
        hDevice,
        IOCTL_DISK_GET_DRIVE_GEOMETRY,
        NULL,
        0,
        NULL,
        0,
        &bytesReturned,
        NULL);

    if (!result) {
        printf("DeviceIoControl failed: %lu\\n", GetLastError());
    } else {
        printf("IOCTL succeeded. Bytes returned: %lu\\n", bytesReturned);
    }

    CloseHandle(hDevice);
    return 0;
}

Related topics