Skip to content

Basic DeviceIO

A console snippet that opens a raw disk handle and issues an IOCTL_STORAGE_EJECT_MEDIA control code.

Published Mar 30, 1996

A minimal tour of the device-I/O path: CreateFile against a raw drive name gives you a handle to the volume itself rather than a file on it, and DeviceIoControl is how you talk storage commands to it. This example sends IOCTL_STORAGE_EJECT_MEDIA, which is handy for popping removable media from software. Use it as the skeleton for any custom IOCTL work - swap the control code and buffers for whatever your device expects.

/////////////////////////////////////////////////////////////////////

#include <Windows.H>
#include <WinIoCtl.H>
#include <WinBase.H>
#include <WindowsX.H>
#include <Wincon.h>
#include <ShellAPI.H>
#include <Stdio.H>
#include <Stdlib.H>

/////////////////////////////////////////////////////////////////////

int main()
{
    BOOL Result = 0;
    char *DiskName = "\\.\D:";

    HANDLE DiskHandle = NULL;

    DiskHandle = CreateFile( DiskName
        , GENERIC_READ | GENERIC_WRITE
        , FILE_SHARE_READ | FILE_SHARE_WRITE // share mode
        , NULL                               // default security attributes
        , OPEN_EXISTING
        , 0                                  // file attributes
        , NULL                               // don't copy any file's attributes
    );

    if(DiskHandle) printf("Open Success.\n");
    if(!DiskHandle)printf("Open Failure.\n");

    VOID  *InBuffer;
    DWORD InBufferSize = 0;

    VOID  *OutBuffer;
    DWORD OutBufferSize = 1024;

    OutBuffer = (VOID *) calloc(1024+1,1);

    DWORD BytesReturned;

    Result = DeviceIoControl(
        DiskHandle,	            // handle to device of interest
        IOCTL_STORAGE_EJECT_MEDIA,	// control code of operation to perform
        &InBuffer,	            // pointer to buffer to supply input data
        InBufferSize,	        // size of input buffer
        &OutBuffer,	            // pointer to buffer to receive output data
        OutBufferSize,	        // size of output buffer
        &BytesReturned,	        // pointer to variable to receive output byte count
        NULL 	                // pointer to structure for asynchronous operation
    );

    if(Result) printf("Control Success.\n");
    if(!Result)printf("Control Failure.\n");

    CloseHandle(DiskHandle);

    return 0;
}

/////////////////////////////////////////////////////////////////////
An unhandled error has occurred. Reload 🗙