[C#] C# 检测pc光驱里插入了光盘 →→→→→进入此内容的聊天室

来自 , 2020-10-24, 写在 C#, 查看 107 次.
URL http://www.code666.cn/view/0f1436a9
  1. using System;
  2. using System.Management;
  3.  
  4. namespace CDROMManagement
  5. {
  6.   class WMIEvent
  7.   {
  8.     static void Main(string[] args)
  9.     {
  10.       WMIEvent we = new WMIEvent();
  11.       ManagementEventWatcher w = null;
  12.       WqlEventQuery q;
  13.       ManagementOperationObserver observer = new
  14.           ManagementOperationObserver();
  15.  
  16.       // Bind to local machine
  17.       ConnectionOptions opt = new ConnectionOptions();
  18.       opt.EnablePrivileges = true; //sets required privilege
  19.       ManagementScope scope = new ManagementScope( "root\\CIMV2", opt );
  20.  
  21.       try
  22.       {
  23.         q = new WqlEventQuery();
  24.         q.EventClassName = "__InstanceModificationEvent";
  25.         q.WithinInterval = new TimeSpan( 0, 0, 1 );
  26.  
  27.         // DriveType - 5: CDROM
  28.         q.Condition = @"TargetInstance ISA 'Win32_LogicalDisk' and
  29.            TargetInstance.DriveType = 5";
  30.         w = new ManagementEventWatcher( scope, q );
  31.  
  32.         // register async. event handler
  33.         w.EventArrived += new EventArrivedEventHandler( we.CDREventArrived );
  34.         w.Start();
  35.  
  36.         // Do something usefull,block thread for testing
  37.         Console.ReadLine();
  38.       }
  39.       catch( Exception e )
  40.       {
  41.         Console.WriteLine( e.Message );
  42.       }
  43.       finally
  44.       {
  45.         w.Stop();
  46.       }
  47.     }
  48.  
  49.     // Dump all properties
  50.     public void CDREventArrived(object sender, EventArrivedEventArgs e)
  51.     {
  52.       // Get the Event object and display it
  53.       PropertyData pd = e.NewEvent.Properties["TargetInstance"];
  54.  
  55.       if (pd != null)
  56.       {
  57.         ManagementBaseObject mbo = pd.Value as ManagementBaseObject;
  58.  
  59.         // if CD removed VolumeName == null
  60.         if (mbo.Properties["VolumeName"].Value != null)
  61.         {
  62.           Console.WriteLine("CD has been inserted");
  63.         }
  64.         else
  65.         {
  66.           Console.WriteLine("CD has been ejected");
  67.         }
  68.       }
  69.     }
  70.   }
  71. }
  72. //csharp/4213

回复 "C# 检测pc光驱里插入了光盘"

这儿你可以回复上面这条便签

captcha