Find which drive the CD Rom Drive is on your using Win32 C++

321 views Asked by At

I created an "Eject" button on my Win32 C++ app that when I press, opens the CD Rom tray. Right now I have it hardcoded knowing that the D drive on my computer is the CD Rom drive. My question is, if I didn't know which drive the CD Rom drive is, or on a computer where the CD Rom drive is not the D Drive, how can I determine which drive on my computer the CD Rom drive is and open the CD Rom tray? My code is shown below.

#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <tchar.h>
#include <stdio.h>

#define IDC_BUTTON                  3456

static TCHAR szWindowClass[] = _T("CD_ROM_READER_APP");
static TCHAR szTitle[] = _T("CD Rom Reader App");
HINSTANCE hInst;

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

TCHAR CSCI_NO[60];
HWND TextBox;

DWORD dwBytes;
HANDLE hCdRom = CreateFile(_T("\\\\.\\D:"),     //This is where I set it so that the D drive is the drive ejected
    GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    PAINTSTRUCT ps;
    HDC hdc;
    TCHAR heading[] = _T("CD ROM READER");
    TCHAR CSCI_No_Inst[] = _T("Please enter the CSCI No below:");

    switch (message)
    {
    case WM_CREATE:
    {
        HWND hwndButton = CreateWindow(
            L"BUTTON", L"EJECT",   
            WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,  
            150, 200, 100, 100,        
            hWnd, (HMENU)IDC_BUTTON, (HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE), NULL);      
       return 0;
    }
    case WM_COMMAND:
    {
        switch (LOWORD(wParam))
        {
        case IDC_BUTTON:
            //Open CD Rom Tray when the Eject button is pressed
            if (hCdRom == INVALID_HANDLE_VALUE)
            {
                _tprintf(_T("Error: %x"), GetLastError());
                return 1;
            }
            // Open the door:  
            DeviceIoControl(hCdRom, IOCTL_STORAGE_EJECT_MEDIA, NULL, 0, NULL, 0, &dwBytes, NULL);
            MessageBox(NULL, L"Please insert a CD ROM in the CD tray.", L"CD ROM Drive", 0);
            break;
        }
    }
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
        break;
    }
    return 0;
}
1

There are 1 answers

0
Rita Han On

how can I determine which drive on my computer the CD Rom drive is

The following is an example based on @RemyLebeau's comment you can refer to:

WCHAR buf[BUF_SIZE];
LPWSTR pBuf = buf;
DWORD chrCopied = GetLogicalDriveStrings(BUF_SIZE - 1, buf);
while (chrCopied)
{
    if (DRIVE_CDROM == GetDriveType(pBuf))
    {
        MessageBox(NULL, pBuf, L"CD-ROM drive", 0);
    }
    size_t len = _tcslen(buf);
    chrCopied -= len + 1;
    pBuf += len + 1;
}

Result as below:

enter image description here