SoFunction
Updated on 2025-04-11

C# WPF realizes displaying the network communication status of the machine

Overview

Implementing an interface in WPF to display the status of the native network interface usually requires the following steps:

1. Obtain network interface information: Use the namespace to obtain the status of the network interface.

2. Create a WPF interface: Use XAML to design the user interface to display information about each network interface.

3. Bind data: Bind the obtained network interface information into the controls of the WPF interface.

Specific implementation

Here is a simple example showing how to implement this feature.

Step 1: Obtain network interface information

Use the NetworkInterface class to obtain the network interface information of the current machine. We will obtain the name of the network interface, the connection type, the IP address, and the current network reception rate. To get the reception rate, we can use the performance counter.

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
 
// Define the NetworkInterfaceInfo class to encapsulate the key information of the network interfacepublic class NetworkInterfaceInfo
{
    // The name of the network interface    public string Name { get; set; }
 
    // Description of network interface    public string Description { get; set; }
 
    // Network connection type (such as Ethernet, wireless, etc.)    public string ConnectionType { get; set; }
 
    // IP address of network interface    public string IPAddress { get; set; }
 
    // The data reception rate of the network interface    public string ReceiveRate { get; set; }
}
 
// Define the NetworkInfoProvider class to provide information about the network interfacepublic class NetworkInfoProvider
{
    // Mapping of storage network interface with its corresponding PerformanceCounter    private readonly Dictionary<string, PerformanceCounter> receiveCounters = new Dictionary<string, PerformanceCounter>();
 
    // Constructor, initialize the performance counter of the network interface    public NetworkInfoProvider()
    {
        // traverse all available network interfaces        foreach (var ni in ())
        {
            // Only handle running network interfaces            if ( == )
            {
                try
                {
                    // Create a PerformanceCounter to get the reception rate                    var counter = new PerformanceCounter("Network Interface", "Bytes Received/sec", );
                    
                    // Initialize the counter for the first read to avoid inaccurate data during the first read                    ();
                    
                    // Store the counter in the dictionary, using the interface description as a key                    receiveCounters[] = counter;
                }
                catch (InvalidOperationException ex)
                {
                    // Handle exceptions when initializing the counter                    ($"Error initializing counter for {}: {}");
                }
            }
        }
    }
 
    // Get information about all running network interfaces    public List<NetworkInterfaceInfo> GetNetworkInterfaces()
    {
        var interfaces = new List<NetworkInterfaceInfo>();
 
        // traverse all available network interfaces        foreach (var ni in ())
        {
            // Only handle running network interfaces            if ( == )
            {
                // Get the IP attributes of this interface                var ipProps = ();
 
                // Get the first IPv4 address                var ipAddress = 
                                       .Where(ip =>  == 
                                   )
                                       .Select(ip => ())
                                       .FirstOrDefault();
 
                // Get the reception rate and convert it to Kbps                string receiveRate = GetReceiveRate() + " Kbps";
 
                // Create a NetworkInterfaceInfo instance and add it to the list                (new NetworkInterfaceInfo
                {
                    Name = ,
                    Description = ,
                    ConnectionType = (),
                    IPAddress = ipAddress ?? "N/A",
                    ReceiveRate = receiveRate
                });
            }
        }
        return interfaces;
    }
 
    // Get the reception rate of the specified network interface    private string GetReceiveRate(string interfaceDescription)
    {
        // Check whether there is a counter for the specified interface in the dictionary        if ((interfaceDescription, out var counter))
        {
            // Convert bytes per second to kilobits per second (Kbps)            return (() * 8 / 1024).ToString("F2");
        }
        // If there is no counter, return 0.00        return "0.00";
    }
}

Code explanation:

NetworkInterfaceInfo class: Used to encapsulate information of a single network interface, including name, description, connection type, IP address, and reception rate. This allows easy display of interface information to the UI.

NetworkInfoProvider class: Responsible for initializing and managing performance counters for network interfaces and providing methods to obtain the currently active network interface and its related information.

Constructor: traverses all network interfaces and only processes interfaces that are active (). Create a PerformanceCounter for each interface to monitor the reception rate. The first call to NextValue() is to initialize the counter value.

GetNetworkInterfaces method: Returns the information list of the currently active network interface. For each interface, get its IPv4 address and receive rate.

GetReceiveRate method: Returns the reception rate of the specified interface and converts it to Kbps. If the interface has no counter, return "0.00".

Step 2: Create a WPF interface

Design a simple WPF interface to display information using ListView.

<Window x:Class=""
        xmlns="/winfx/2006/xaml/presentation"
        xmlns:x="/winfx/2006/xaml"
        Title="Network Status" Height="400" Width="600">
    <Grid>
        <ListView Name="NetworkInterfacesListView">
            <>
                <GridView>
                    <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="120" />
                    <GridViewColumn Header="Description" DisplayMemberBinding="{Binding Description}" Width="180" />
                    <GridViewColumn Header="Connection Type" DisplayMemberBinding="{Binding ConnectionType}" Width="100" />
                    <GridViewColumn Header="IP Address" DisplayMemberBinding="{Binding IPAddress}" Width="120" />
                    <GridViewColumn Header="Receive Rate (Kbps)" DisplayMemberBinding="{Binding ReceiveRate}" Width="120" />
                </GridView>
            </>
        </ListView>
    </Grid>
</Window>

Step 3: Bind the data

In , get the data from NetworkInfoProvider and bind to the ListView.

using ;
using ;
using ;
 
// Define the MainWindow class, inherited from WPF's Window classpublic partial class MainWindow : Window
{
    // Define a NetworkInfoProvider instance to obtain network interface information    private NetworkInfoProvider provider;
 
    // Define an observable collection to store and update network interface information    private ObservableCollection&lt;NetworkInterfaceInfo&gt; networkInterfaces;
 
    // MainWindow constructor    public MainWindow()
    {
        // Initialize the XAML interface component        InitializeComponent();
 
        // Initialize the ObservableCollection instance and bind it to the ListView control        networkInterfaces = new ObservableCollection&lt;NetworkInterfaceInfo&gt;();
         = networkInterfaces;
 
        // Perform asynchronous initialization using BackgroundWorker to avoid blocking UI threads        BackgroundWorker worker = new BackgroundWorker();
        
        // Register DoWork events for background thread execution         += (s, e) =&gt; InitializeNetworkProvider();
        
        // Register the RunWorkerCompleted event, used for execution after the background thread is completed         += (s, e) =&gt;
        {
            // After initialization is completed, update the interface immediately            UpdateNetworkInterfacesImmediately();
            
            // Start timed update network interface information            StartUpdating();
        };
        
        // Start the background operation        ();
    }
 
    // Initialize NetworkInfoProvider instance    private void InitializeNetworkProvider()
    {
        provider = new NetworkInfoProvider();
    }
 
    // Start timer, used to regularly update network interface information    private void StartUpdating()
    {
        // Create a scheduler        DispatcherTimer timer = new DispatcherTimer();
        
        // Set the time interval to 2 seconds         = (2);
        
        // Register the Tick event of the timer to trigger the update operation         += UpdateNetworkInterfaces;
        
        // Start the timer        ();
    }
 
    // Update the network interface information immediately and update to the interface    private void UpdateNetworkInterfacesImmediately()
    {
        // Clear the current network interface information        ();
        
        // Get the latest network interface information and add it to the collection        foreach (var ni in ())
        {
            (ni);
        }
    }
 
    // Methods to regularly update network interface information    private void UpdateNetworkInterfaces(object sender, EventArgs e)
    {
        // Clear the current network interface information        ();
        
        // Get the latest network interface information and add it to the collection        foreach (var ni in ())
        {
            (ni);
        }
    }
}

Things to note

Permissions: Some network interface information may require administrator permission to access.

Update interface status: If you need to update the network interface status dynamically, you can use a timer or event notification mechanism.

This example shows a basic implementation where we can further expand and beautify the UI according to our actual needs.

This is the article about C# WPF realization to display the network communication status of the native machine. For more related contents of WPF displaying the network communication status of the native machine, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!