欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#检测pc光驱里是否插入了光盘的方法

程序员文章站 2023-11-20 21:53:40
本文实例讲述了c#检测pc光驱里是否插入了光盘的方法。分享给大家供大家参考。具体如下: c# 检测pc光驱里是否插入了光盘,需要添加system.management.d...

本文实例讲述了c#检测pc光驱里是否插入了光盘的方法。分享给大家供大家参考。具体如下:

c# 检测pc光驱里是否插入了光盘,需要添加system.management.dll 的引用

using system;
using system.management;
namespace cdrommanagement
{
 class wmievent
 {
  static void main(string[] args)
  {
   wmievent we = new wmievent();
   managementeventwatcher w = null;
   wqleventquery q;
   managementoperationobserver observer = new managementoperationobserver();
   // bind to local machine
   connectionoptions opt = new connectionoptions();
   opt.enableprivileges = true; //sets required privilege
   managementscope scope = new managementscope( "root\\cimv2", opt );
   try
   {
    q = new wqleventquery();
    q.eventclassname = "__instancemodificationevent";
    q.withininterval = new timespan( 0, 0, 1 );
    // drivetype - 5: cdrom
    q.condition = @"targetinstance isa 'win32_logicaldisk' and targetinstance.drivetype = 5";
    w = new managementeventwatcher( scope, q );
    // register async. event handler
    w.eventarrived += new eventarrivedeventhandler( we.cdreventarrived );
    w.start();
    // do something usefull,block thread for testing
    console.readline();
   }
   catch( exception e )
   {
    console.writeline( e.message );
   }
   finally
   {
    w.stop();
   }
  }
  // dump all properties
  public void cdreventarrived(object sender, eventarrivedeventargs e)
  {
   // get the event object and display it
   propertydata pd = e.newevent.properties["targetinstance"];
   if (pd != null)
   {
    managementbaseobject mbo = pd.value as managementbaseobject;
 
    // if cd removed volumename == null
    if (mbo.properties["volumename"].value != null)
    {
     console.writeline("cd has been inserted");
    }
    else
    {
     console.writeline("cd has been ejected");
    }
   }
  }
 }
}

希望本文所述对大家的c#程序设计有所帮助。