以编程方式在vb.net或c#中弹出和缩回CD驱动器

时间:2009-09-19 20:10:19

标签: c# vb.net drive

有没有办法这样做?我知道可以通过编程方式弹出/缩回CD驱动器SOMEHOW,因为当Roxio提示我插入磁盘时会这样做。

c#或vb.net更可取,但c和c ++也可以作为最后的手段。

我几乎肯定有一些方法可以做到这一点,我只是不知道要调用的方法。

我确实理解这是一个有点不同寻常的要求,因为当我搜索这些方法时Google几乎没有任何结果......

2 个答案:

答案 0 :(得分:10)

using System.Runtime.InteropServices;

[DllImport("winmm.dll")]
static extern Int32 mciSendString(String command, StringBuilder buffer, Int32 bufferSize, IntPtr hwndCallback);

// To open the door
mciSendString("set CDAudio door open", null, 0, IntPtr.Zero);

// To close the door
mciSendString("set CDAudio door closed", null, 0, IntPtr.Zero);

http://www.geekpedia.com/tutorial174_Opening-and-closing-the-CD-tray-in-.NET.html

答案 1 :(得分:10)

以下是已接受解决方案的替代解决方案,转换自VB.NET sample

using System;
using System.IO;
using System.Runtime.InteropServices;

class Test
{
    const int OPEN_EXISTING = 3;
    const uint GENERIC_READ = 0x80000000;
    const uint GENERIC_WRITE = 0x40000000;
    const uint IOCTL_STORAGE_EJECT_MEDIA = 2967560;

    [DllImport("kernel32")]
    private static extern IntPtr CreateFile
        (string filename, uint desiredAccess, 
         uint shareMode, IntPtr securityAttributes,
         int creationDisposition, int flagsAndAttributes, 
         IntPtr templateFile);

    [DllImport("kernel32")]
    private static extern int DeviceIoControl
        (IntPtr deviceHandle, uint ioControlCode, 
         IntPtr inBuffer, int inBufferSize,
         IntPtr outBuffer, int outBufferSize, 
         ref int bytesReturned, IntPtr overlapped);

    [DllImport("kernel32")]
    private static extern int CloseHandle(IntPtr handle);

    static void EjectMedia(char driveLetter)
    {
        string path = "\\\\.\\" + driveLetter + ":";
        IntPtr handle = CreateFile(path, GENERIC_READ | GENERIC_WRITE, 0, 
                                   IntPtr.Zero, OPEN_EXISTING, 0,
                                   IntPtr.Zero);
        if ((long) handle == -1)
        {
            throw new IOException("Unable to open drive " + driveLetter);
        }
        int dummy = 0;
        DeviceIoControl(handle, IOCTL_STORAGE_EJECT_MEDIA, IntPtr.Zero, 0, 
                        IntPtr.Zero, 0, ref dummy, IntPtr.Zero);
        CloseHandle(handle);
    }

    static void Main()
    {
        EjectMedia('f');
    }
}