检测CD驱动器何时关闭

时间:2013-12-24 17:50:46

标签: c#

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

这可能吗?

3 个答案:

答案 0 :(得分:2)

按照教程

结帐

Detect CD-ROM Insertion

答案 1 :(得分:1)

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

[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,否则返回错误代码。所以你可以有一个逻辑来检查。

您可以查看documentation of the function以及有用的link了解详情

答案 2 :(得分:1)

据我所知,问题是您要检测驱动器侧面是否有磁盘或正在插入的磁盘。如果是这样,这个片段会帮助你

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