C#检测pc光驱里是否插入了光盘的方法
本文实例讲述了C#检测pc光驱里是否插入了光盘的方法。分享给大家供大家参考。具体如下:
C#检测pc光驱里是否插入了光盘,需要添加System.Management.dll的引用
usingSystem;
usingSystem.Management;
namespaceCDROMManagement
{
classWMIEvent
{
staticvoidMain(string[]args)
{
WMIEventwe=newWMIEvent();
ManagementEventWatcherw=null;
WqlEventQueryq;
ManagementOperationObserverobserver=newManagementOperationObserver();
//Bindtolocalmachine
ConnectionOptionsopt=newConnectionOptions();
opt.EnablePrivileges=true;//setsrequiredprivilege
ManagementScopescope=newManagementScope("root\\CIMV2",opt);
try
{
q=newWqlEventQuery();
q.EventClassName="__InstanceModificationEvent";
q.WithinInterval=newTimeSpan(0,0,1);
//DriveType-5:CDROM
q.Condition=@"TargetInstanceISA'Win32_LogicalDisk'andTargetInstance.DriveType=5";
w=newManagementEventWatcher(scope,q);
//registerasync.eventhandler
w.EventArrived+=newEventArrivedEventHandler(we.CDREventArrived);
w.Start();
//Dosomethingusefull,blockthreadfortesting
Console.ReadLine();
}
catch(Exceptione)
{
Console.WriteLine(e.Message);
}
finally
{
w.Stop();
}
}
//Dumpallproperties
publicvoidCDREventArrived(objectsender,EventArrivedEventArgse)
{
//GettheEventobjectanddisplayit
PropertyDatapd=e.NewEvent.Properties["TargetInstance"];
if(pd!=null)
{
ManagementBaseObjectmbo=pd.ValueasManagementBaseObject;
//ifCDremovedVolumeName==null
if(mbo.Properties["VolumeName"].Value!=null)
{
Console.WriteLine("CDhasbeeninserted");
}
else
{
Console.WriteLine("CDhasbeenejected");
}
}
}
}
}
希望本文所述对大家的C#程序设计有所帮助。