Detect when CD drive was closed

Total Post:70

Points:494
C# 
C#
 1189  View(s)
Ratings:
Rate this:

So I am making a little project for myself. I need to detect if the CD Drive was closed, and if it was, run a function.

Is this possible?
  1. Post:412

    Points:2888
    Re: Detect when CD drive was closed

    Hi Samuel,



    As far I understand the question is you want to detect there is a disk in side the drive and running or maybe just one inserted. if so this snippet will help you

    using System;
    using System.Management;
    class Application
    {
        public static void Main()
        {
            SelectQuery query = new SelectQuery( "select * from win32_logicaldisk where drivetype=5" );
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
            foreach( ManagementObject mo in searcher.Get() )
            {
              // If both properties are null I suppose there's no CD
                 if( ( mo["volumename"] != null ) || ( mo["volumeserialnumber"] != null ) )
                 {
                     Console.WriteLine( "CD is named: {0}", mo["volumename"] );
                     Console.WriteLine( "CD Serial Number: {0}", mo["volumeserialnumber"] );
                 }
                 else
                 {
                     Console.WriteLine( "No CD in Unit" ); // Here you can make sure there is no disk.
                 }
            }
            // Here to stop app from closing
            Console.WriteLine( "\nPress Return to exit." );
            Console.Read();
       }
    }

      Modified On Apr-04-2018 02:15:49 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!