c# – Programatically close optical drive tray


I really liked the close tray program that CD-ROM drivers programs used to include in MS-DOS days.
Since I live in a place where even getting an internship is impossible, I’ve decided to learn by myself.

I implemented this “Hello World” C# script to do that with a twist.
It will check the optical drive status and if open, it will close it, otherwise it will tell you that a disk is present.

Note, I went through stackoverflow and couldn’t find a way to programatically find if the tray is open.
Another note, it will not close the tray on most laptops where such mechanism does not exist.

And finally, I used an online code beautifier for indentation.

using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Management;

class Program { 
(DllImport("winmm.dll")) protected static extern int mciSendString(string Cmd, StringBuilder StrReturn, int ReturnLength, IntPtr HwndCallback);

  static void Main(string() args) {

  ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT MediaLoaded FROM Win32_CDROMDrive");
  ManagementObjectCollection moc = searcher.Get();
  var enumerator = moc.GetEnumerator();
  if (!enumerator.MoveNext()) throw new Exception("No elements");
  ManagementObject obj = (ManagementObject) enumerator.Current;
  bool status = (bool) obj("MediaLoaded");

  if (!status) {
    MessageBox.Show("The drive is either open or empty", "Optical Drive Status");
    mciSendString("set cdaudio door closed", null, 0, IntPtr.Zero);
  }
  else MessageBox.Show("The drive is closed and contains an optical media", "Optical Drive Status");
 }
}