检测CD驱动器何时关闭

所以我正在为自己做一个小项目。 我需要检测CD驱动器是否已关闭,如果是,则运行一个function。

这可能吗?

首先,您需要定义将打开磁盘托盘的function:

[DllImport("winmm.dll", EntryPoint = "mciSendString")] public static extern int mciSendStringA(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback); 

要关闭(或检查驱动器是否已关闭)磁盘驱动器,您需要发送两个命令字符串。

 mciSendStringA("open " + driveLetter + ": type CDaudio alias drive" + driveLetter, returnString, 0, 0); mciSendStringA("set drive" + driveLetter + " door closed", returnString, 0, 0); 

如果命令成功执行,则该函数返回0 ,否则返回错误代码。因此,您可以使用逻辑来检查该命令。

您可以查看该function的文档以及有用的链接以获取更多信息

结帐以下教程

检测CD-ROM插入

据我所知,问题是你想检测到驱动器侧面有一个磁盘正在运行,或者只是插入了一个磁盘。 如果是这样,这个片段会帮助你

 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(); } } 

[来源]( http://www.codeproject.com/Tips/295010/How-to-Detect-CD-ROM-is-loaded-in-the-CD-ROM-drive