监控USB网卡插拔

 ManagementEventWatcher getEventWatcher = null;
            WqlEventQuery getEventQuery = null;
            ManagementOperationObserver getObserver = new ManagementOperationObserver();
            ManagementScope getScope = new ManagementScope("root\\CIMV2");
            getScope.Options.EnablePrivileges = true;

            try
            {
                getEventQuery = new WqlEventQuery();
                getEventQuery.EventClassName = "__InstanceOperationEvent";
                getEventQuery.WithinInterval = new TimeSpan(0, 0, 0, 1);//查询的频率
                getEventQuery.Condition = @"TargetInstance ISA 'Win32_NetworkAdapter'";//设置查询条件
                getEventWatcher = new ManagementEventWatcher(getEventQuery);
                getEventWatcher.EventArrived += new EventArrivedEventHandler(getEventWatcher_EventArrived);
                getEventWatcher.Start();//Start Watch Event

下面是 getEventWatcher_EventArrived

        void getEventWatcher_EventArrived(object sender, EventArrivedEventArgs e)
        {

            ManagementBaseObject getBaseObject = (ManagementBaseObject)e.NewEvent;
            if ((getBaseObject.ClassPath.ClassName == "__InstanceModificationEvent"))
            {
                NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();

                bool isContains = false;
                foreach (NetworkInterface adapter in adapters)
                {

                    if (adapter.Description.Contains("HUAWEI"))
                    {
                        isContains = true;
                        break;
                    }
                    else
                    {
                        isContains = false;
                    }
                }
                if (isContains)
                {
                    startDownload();
                }
                else
                {
                    pauseDownload();
                }

            }
        }
posted @ 2012-04-18 15:18  William Jiang  阅读(497)  评论(0编辑  收藏  举报