摘要:[C#][Winform]控制CDROM托盤
因為之前買的機殼其設計不良導致無法按到光碟機的退出鈕,真的是有點難控制光碟機托盤的進出。網路上很少找得到有這樣單一功能的免費程式,不是功能太多太複雜要不就是shareware(不是freeware), 於是找了一些資料、自己寫了一個POC(Proof of Concept) 的程式。
01
//引用Windows API
02
[DllImport("kernel32", SetLastError = true)]
03
public static extern int GetDriveType(string driveLetter);
04
05 [DllImport("winmm.dll", EntryPoint = "mciSendStringA")]
06
public static extern void mciSendStringA(string lpstrCommand, string lpstrReturnString, Int32 uReturnLength, Int32 hwndCallback);
07
08 private List<string> DiscoverDrives()
09
{
10
List<string> lstCDROM = new List<string>();
11
//列出電腦上的所有磁碟代號
12
foreach (string drive in Environment.GetLogicalDrives())
13
{
14
if (GetDriveType(drive) == 5) //CDROM type
15
lstCDROM.Add(drive);
16
}
17
return lstCDROM;
18
}
19
20 //控制光碟機托盤
21
private void DoorControl(string driveLetter, bool open)
22
{
23
string strCmd = "set cdaudio!" + driveLetter;
24
strCmd += (open) ? " door open" : " door closed";
25
mciSendStringA(strCmd, "", 0, 0);
26
}
//引用Windows API02
[DllImport("kernel32", SetLastError = true)]03
public static extern int GetDriveType(string driveLetter);04

05 [DllImport("winmm.dll", EntryPoint = "mciSendStringA")]
06
public static extern void mciSendStringA(string lpstrCommand, string lpstrReturnString, Int32 uReturnLength, Int32 hwndCallback);07

08 private List<string> DiscoverDrives()
09
{10
List<string> lstCDROM = new List<string>();11
//列出電腦上的所有磁碟代號12
foreach (string drive in Environment.GetLogicalDrives())13
{14
if (GetDriveType(drive) == 5) //CDROM type15
lstCDROM.Add(drive);16
}17
return lstCDROM;18
}19

20 //控制光碟機托盤
21
private void DoorControl(string driveLetter, bool open)22
{23
string strCmd = "set cdaudio!" + driveLetter;24
strCmd += (open) ? " door open" : " door closed";25
mciSendStringA(strCmd, "", 0, 0);26
}範例檔案 KCDE.zip
