Friday, March 16, 2012

Check If CD was inserted

In this post I want to explain, based upon the method from the previous post, how to spot, when a CD Rom is inserted.

As described in the previous post therefor we again use the WM_DEVICECHANGE event and the enumeration System.IO.DriveInfo.GetDrives().
During the check we now just have to determine whether the devices are of the type DriveType.CDRom and contain a readable CD, which is indicated by IsReady. In the WndProc() function the current value of the variable is compared to the previous and thus determined, whether the user inserted a CD (for multiple CD drives, the code has to be changed accordingly):

        const int WM_DEVICECHANGE = 0x219;
        bool CDInserted;

        private void CheckCD()
        {
            foreach (System.IO.DriveInfo d in System.IO.DriveInfo.GetDrives())
            {
                if (d.DriveType == System.IO.DriveType.CDRom && d.IsReady)
                    CDInserted = true;
            }
        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_DEVICECHANGE)
            {
                bool OldCD = CDInserted;
                CheckCD();
                if (!OldCD && CDInserted)
                    MessageBox.Show("CD inserted.");
            }

            base.WndProc(ref m);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            CheckCD();
        }

No comments:

Post a Comment