user5447339
user5447339

Reputation:

Detect an ethernet cable in WMI?

I have setup WMI code creator on my computer which I have installed from here.

I am wondering what Namespace and Classes(dynamic or static) do I need to select from WMI code creator application as shown below in an image in order to get a call back in WMI when an ethernet cable is connected to computer.

After selecting a proper namespace and class, I will use C# code from the code creator and run it on my computer to detect network changes on computer.

enter image description here

Upvotes: 1

Views: 1034

Answers (1)

lesscode
lesscode

Reputation: 6361

Something like this should get you started:

    var q = new WqlEventQuery("SELECT * FROM __InstanceModificationEvent WITHIN 10 WHERE TargetInstance ISA 'Win32_NetworkAdapter'");

    var hostInstanceWatcher = new ManagementEventWatcher(new ManagementScope(@"\\.\root\CIMV2"), q);
    hostInstanceWatcher.EventArrived += (sender, eventArgs) =>
    {
        var adapter = (ManagementBaseObject) eventArgs.NewEvent.GetPropertyValue("TargetInstance");
        var status = (ushort) adapter.GetPropertyValue("NetConnectionStatus");
        switch (status)
        {
            case 2: Console.WriteLine("Connected");
                break;
            case 7: Console.WriteLine("Disconnected");
                break;
        }
    };
    hostInstanceWatcher.Start();
    Console.WriteLine("Press any key to quit");
    Console.ReadKey();

Upvotes: 1

Related Questions