当前位置: 移动技术网 > IT编程>开发语言>c# > C#检测pc光驱里是否插入了光盘的方法

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网