I am trying to eject my cd Rom drive by clicking a button. When the button is pressed, the CD Rom drive was ejecting correctly before but now it is giving me an error: "0xC0000005: Access violation writing location 0x00000000." I'm not sure why I am getting this error. My code is shown below, where my CD Rom drive is the D-drive:
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#define BUTTON 3456
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
DWORD dwBytes;
HANDLE hCdRom;
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
{
HWND hwndButton = CreateWindow(
L"BUTTON", // Predefined class; Unicode assumed
L"EJECT", // Button text
WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // Styles
180, // x position
200, // y position
100, // Button width
100, // Button height
hWnd, // Parent window
(HMENU)BUTTON, // No menu.
(HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE),
NULL); // Pointer not needed.
}
case WM_COMMAND:
{
switch (LOWORD(wParam))
{
case BUTTON:
hCdRom = CreateFile(L"\\\\.\\D:",
GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hCdRom == INVALID_HANDLE_VALUE)
{
wsprintf(NULL, L"Error: %d", GetLastError()); //Getting error: Exception thrown at 0x746FFA6F (user32.dll) in Project.exe: 0xC0000005: Access violation writing location 0x00000000.
return 1;
}
DeviceIoControl(hCdRom, IOCTL_STORAGE_EJECT_MEDIA, NULL, 0, NULL, 0, &dwBytes, NULL);
if (hCdRom == 0)
{
wsprintfW(NULL, L"Error: %d", GetLastError());
return 1;
}
MessageBox(NULL, L"Please insert a CD ROM in the CD tray.", L"CD ROM Drive", 0);
CloseHandle(hCdRom);
break;
}
}
}
Has anyone come across this error and know how to fix it?