C#监控CD-ROM插入/弹出光盘(CDROM_Listener)
C#监控CD-ROM插入/弹出光盘(CDROM_Listener)
其实可以通过多种方式实现C#监控CD-ROM插入/弹出光盘.
用System.Management相关类实现可能是最简单的.
其实可以通过多种方式实现C#监控CD-ROM插入/弹出光盘.
用System.Management相关类实现可能是最简单的.
public class CDROM_Listener
{
public static void Test()
{
CDROM_Listener listener = new CDROM_Listener();
ManagementEventWatcher watcher = null;
WqlEventQuery query = null;//表示 WQL 格式的 WMI 事件查询。
ManagementOperationObserver observer = new ManagementOperationObserver(); //系统管理操作观察者
// 绑定本机机器
ConnectionOptions opt = new ConnectionOptions();
opt.EnablePrivileges = true; //是否需要为连接操作启用用户特权。
ManagementScope scope = new ManagementScope("root\\CIMV2", opt);//设置监控范围
try
{
query = new WqlEventQuery();
query.EventClassName = "__InstanceModificationEvent";
query.WithinInterval = new TimeSpan(0, 0, 1);
// DriveType - 5: CDROM
query.Condition = @"TargetInstance ISA ’Win32_LogicalDisk’ and TargetInstance.DriveType=5";
watcher = new ManagementEventWatcher(scope, query);
//绑定事件
watcher.EventArrived += new EventArrivedEventHandler(listener.CDREventArrived);
watcher.Start(); //开始监听...
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
// watcher.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)
{
MessageBox.Show("已经插入光盘");
}
else
{
MessageBox.Show("已经弹出光盘");
}
}
}
}
{
public static void Test()
{
CDROM_Listener listener = new CDROM_Listener();
ManagementEventWatcher watcher = null;
WqlEventQuery query = null;//表示 WQL 格式的 WMI 事件查询。
ManagementOperationObserver observer = new ManagementOperationObserver(); //系统管理操作观察者
// 绑定本机机器
ConnectionOptions opt = new ConnectionOptions();
opt.EnablePrivileges = true; //是否需要为连接操作启用用户特权。
ManagementScope scope = new ManagementScope("root\\CIMV2", opt);//设置监控范围
try
{
query = new WqlEventQuery();
query.EventClassName = "__InstanceModificationEvent";
query.WithinInterval = new TimeSpan(0, 0, 1);
// DriveType - 5: CDROM
query.Condition = @"TargetInstance ISA ’Win32_LogicalDisk’ and TargetInstance.DriveType=5";
watcher = new ManagementEventWatcher(scope, query);
//绑定事件
watcher.EventArrived += new EventArrivedEventHandler(listener.CDREventArrived);
watcher.Start(); //开始监听...
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
// watcher.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)
{
MessageBox.Show("已经插入光盘");
}
else
{
MessageBox.Show("已经弹出光盘");
}
}
}
}
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网