当驱动器被安装或变更状态(WM_DEVICECHANGE为WPF)检测? [英] Detect when drive is mounted or changes state (WM_DEVICECHANGE for WPF)?

查看:444
本文介绍了当驱动器被安装或变更状态(WM_DEVICECHANGE为WPF)检测?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的目录中选择控制WPF中,我想添加/删除从目录树中的驱动器,当它被安装或卸载,或当其准备好或没有准备好(如用户插入或删除CD )。我在寻找类似 WM_DEVICECHANGE 的系统事件。

I am writing a directory selector control for WPF, and I would like to add/remove a drive from the directory tree when it gets mounted or unmounted or when it becomes ready or not ready (e.g. the user inserts or removes a CD). I am looking for a system event similar to WM_DEVICECHANGE.

康斯坦丁

推荐答案

我用WMI实现这样的事情(在他的回答像理查德说)

I used WMI to implement something like this (like Richard stated in his answer)

using System.Management; 
using System;

...

private void SubscribeToCDInsertion()
{
    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);

    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";
    var w = new ManagementEventWatcher(scope, q);
    try
    {

       // register async. event handler
       w.EventArrived += new EventArrivedEventHandler(driveInsertEvent);
       w.Start();

    }
    catch (Exception e)
    {
        w.Stop();
    }

}

void driveInsertEvent(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)
        {
            //do something
        }
    }
}

编辑:我并没有发明Ç自己的$ C $,我想从我的这里

这篇关于当驱动器被安装或变更状态(WM_DEVICECHANGE为WPF)检测?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆