將開發(fā)過程經(jīng)常用的一些代碼段做個備份,如下代碼段是關(guān)于C# 檢測pc光驅(qū)里插入了光盤的代碼,應(yīng)該能對碼農(nóng)們也有好處。
using System;
using System.Management;
10年積累的成都網(wǎng)站設(shè)計、成都網(wǎng)站制作經(jīng)驗(yàn),可以快速應(yīng)對客戶對網(wǎng)站的新想法和需求。提供各種問題對應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識你,你也不認(rèn)識我。但先做網(wǎng)站后付款的網(wǎng)站建設(shè)流程,更有射洪免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
namespace CDROMManagement
{
class WMIEvent
{
static void Main(string[] args)
{
WMIEvent we = new WMIEvent();
ManagementEventWatcher w = null;
WqlEventQuery q;
ManagementOperationObserver observer = new
ManagementOperationObserver();
ConnectionOptions opt = new ConnectionOptions();
ManagementScope scope = new ManagementScope( "root\CIMV2", opt );
try
{
q = new WqlEventQuery();
q.EventClassName = "__InstanceModificationEvent";
q.WithinInterval = new TimeSpan( 0, 0, 1 );
q.Condition = @"TargetInstance ISA 'Win32_LogicalDisk' and
TargetInstance.DriveType = 5";
w = new ManagementEventWatcher( scope, q );
w.EventArrived += new EventArrivedEventHandler( we.CDREventArrived );
w.Start();
Console.ReadLine();
}
catch( Exception e )
{
Console.WriteLine( e.Message );
}
finally
{
w.Stop();
}
}
public void CDREventArrived(object sender, EventArrivedEventArgs e)
{
PropertyData pd = e.NewEvent.Properties["TargetInstance"];
if (pd != null)
{
ManagementBaseObject mbo = pd.Value as ManagementBaseObject;
if (mbo.Properties["VolumeName"].Value != null)
{
Console.WriteLine("CD has been inserted");
}
else
{
Console.WriteLine("CD has been ejected");
}
}
}
}
}