windows: How to get the tray status of an optical drive

Sometimes you would like to know if the tray of your CD/DVD/Bluray drive is open, closed and if a media is inserted. The following example shows how to archive that with C++. The return codes of the function GetDriveStatus() are:

And now the example:

We first check in line 57 with IOCTL_STORAGE_CHECK_VERIFY2 if we have a media in our drive. If this returns 1 we have a medium loaded and we can early return and save another call to DeviceIoControl().
In line 123 we finally request the tray status with a IOCTL_SCSI_PASS_THROUGH_DIRECT call.