How to find the network event change in windows using forms or windows service - c#?

Elanchezhiyan P 100 Reputation points
2023-02-20T11:48:33.5766667+00:00

Hi Team,

How to get the events when the network is changed or connected newly or disconnected in c# (windows system)? I have tried with the management event watcher. But it does not give expected output. The code I have used as below.
The disconnected network is { network name }. The connected network is { network name }. with this other details as MacAddress, Description, DNSHostName, DHCPServer, ServiceName, IpEnabled.

         WqlEventQuery query = new WqlEventQuery("__InstanceModificationEvent", new TimeSpan(0, 0, 2),  "TargetInstance isa 'Win32_NetworkAdapterConfiguration'");
         ManagementEventWatcher managementEventWatcher = new ManagementEventWatcher(query);
         managementEventWatcher.EventArrived += new EventArrivedEventHandler(NetworkAdapterEventWatcher_EventArrived);
         managementEventWatcher.Start();
Console.WriteLine("Press any key to exit.");
Console.ReadKey();

         // Stop the watcher         
managementEventWatcher.Stop();

      private static void NetworkAdapterEventWatcher_EventArrived(object sender, EventArrivedEventArgs e)
      {
         foreach (var item in e.NewEvent.Properties)
         {
            Console.WriteLine("Event " + item.Name + " --- " + item.Value);
         }
      }
Windows for business | Windows Client for IT Pros | User experience | Other
Developer technologies | .NET | Other
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 90,686 Reputation points
    2023-02-20T12:45:14.3366667+00:00

    INetworkListManagerEvents works fine for me

    (Network List Manager 1.0 Type Library)


1 additional answer

Sort by: Most helpful
  1. Rhea S 0 Reputation points
    2023-03-30T09:10:47.9766667+00:00

    The ManagementEventWatcher class should work for monitoring network connection changes in Windows. However, you may need to modify your WqlEventQuery to target the correct event.

    Here's an example query that should detect network connection changes:

    WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_NetworkAdapter WHERE AdapterTypeId = 0 OR AdapterTypeId = 9");
    
    

    This query will detect changes to the network adapter configuration, including new connections and disconnections.

    You can then use the EventArrived event to handle the network connection changes. Here's an updated version of your code that should work:

    
    WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_NetworkAdapter WHERE AdapterTypeId = 0 OR AdapterTypeId = 9");
    ManagementEventWatcher managementEventWatcher = new ManagementEventWatcher(query);
    managementEventWatcher.EventArrived += new EventArrivedEventHandler(NetworkAdapterEventWatcher_EventArrived);
    managementEventWatcher.Start();
    Console.WriteLine("Press any key to exit.");
    Console.ReadKey();
    managementEventWatcher.Stop();
    
    private static void NetworkAdapterEventWatcher_EventArrived(object sender, EventArrivedEventArgs e)
    {
        var networkAdapter = (ManagementBaseObject)e.NewEvent["TargetInstance"];
        var adapterType = (UInt16)networkAdapter["AdapterTypeId"];
        var adapterDescription = (string)networkAdapter["Description"];
        var adapterName = (string)networkAdapter["Name"];
        var adapterMacAddress = (string)networkAdapter["MACAddress"];
        var ipEnabled = (bool)networkAdapter["IPEnabled"];
    
        if (adapterType == 0 && ipEnabled)
        {
            Console.WriteLine($"Connected to network: {adapterDescription} ({adapterName})");
            Console.WriteLine($"MAC address: {adapterMacAddress}");
            Console.WriteLine($"DNS hostname: {Dns.GetHostName()}");
            Console.WriteLine($"DHCP server: {GetDhcpServer(adapterName)}");
            Console.WriteLine($"Service name: {GetServiceName(adapterName)}");
        }
        else if (adapterType == 9)
        {
            Console.WriteLine($"Disconnected from network: {adapterDescription} ({adapterName})");
        }
    }
    
    private static string GetDhcpServer(string adapterName)
    {
        using (var mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
        {
            using (var mos = mc.GetInstances())
            {
                foreach (ManagementObject mo in mos)
                {
                    if ((bool)mo["IPEnabled"] && mo["SettingID"].ToString().Contains(adapterName))
                    {
                        return (string)mo["DHCPServer"];
                    }
                }
            }
        }
        return null;
    }
    
    private static string GetServiceName(string adapterName)
    {
        using (var mc = new ManagementClass("Win32_NetworkAdapter"))
        {
            using (var mos = mc.GetInstances())
            {
                foreach (ManagementObject mo in mos)
                {
                    if ((bool)mo["NetEnabled"] && mo["Name"].ToString().Contains(adapterName))
                    {
                        return (string)mo["ServiceName"];
                    }
                }
            }
        }
        return null;
    }
    
    

    Note that the GetDhcpServer and GetServiceName methods are used to retrieve additional information about the network adapter. You can modify these methods to retrieve other information if needed.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.