我的机器上有两个网络适配器。例如适配器 A 和适配器 B。A 保持连接
我想监控适配器B的连接状态。我的意思是,连接或断开状态。
我尝试了 System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged
但它不起作用,因为适配器 A 已连接。
也许WMI有帮助,但我没有任何经验,也没有找到太多有用的文章。
谁能帮我看看
如何订阅适配器的WMI事件C#中的连接状态
我的机器上有两个网络适配器。例如适配器 A 和适配器 B。A 保持连接
我想监控适配器B的连接状态。我的意思是,连接或断开状态。
我尝试了 System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged
但它不起作用,因为适配器 A 已连接。
也许WMI有帮助,但我没有任何经验,也没有找到太多有用的文章。
谁能帮我看看
如何订阅适配器的WMI事件C#中的连接状态
您可以将Win32_NetworkAdapter
WMI 类和NetConnectionStatus
属性与__InstanceModificationEvent
事件一起使用。
WQL 语句看起来像这样
Select * From __InstanceModificationEvent Within 1 Where TargetInstance ISA 'Win32_NetworkAdapter' AND TargetInstance.Name='Network adapter name'
试试这个样本
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;
namespace GetWMI_Info
{
public class EventWatcherAsync
{
private void WmiEventHandler(object sender, EventArrivedEventArgs e)
{
Console.WriteLine("TargetInstance.Name : " + ((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)["Name"]);
//2 (0x2) Connected
//7 (0x7) Media disconnected
Console.WriteLine("TargetInstance.NetConnectionStatus : " + ((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)["NetConnectionStatus"]);
}
public EventWatcherAsync()
{
try
{
string ComputerName = "localhost";
string WmiQuery;
ManagementEventWatcher Watcher;
ManagementScope Scope;
if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
ConnectionOptions Conn = new ConnectionOptions();
Conn.Username = "";
Conn.Password = "";
Conn.Authority = "ntlmdomain:DOMAIN";
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn);
}
else
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
WmiQuery ="Select * From __InstanceModificationEvent Within 1 "+
"Where TargetInstance ISA 'Win32_NetworkAdapter' AND TargetInstance.Name='Tarjeta Mini de media altura WLAN Wireless-N DW1501' ";
Watcher = new ManagementEventWatcher(Scope, new EventQuery(WmiQuery));
Watcher.EventArrived += new EventArrivedEventHandler(this.WmiEventHandler);
Watcher.Start();
Console.Read();
Watcher.Stop();
}
catch (Exception e)
{
Console.WriteLine("Exception {0} Trace {1}", e.Message, e.StackTrace);
}
}
public static void Main(string[] args)
{
Console.WriteLine("Listening {0}", "__InstanceModificationEvent");
Console.WriteLine("Press Enter to exit");
EventWatcherAsync eventWatcher = new EventWatcherAsync();
Console.Read();
}
}
}