Continuously updating label color

Viewed 35

I am showcasing whether someone's connected via Always-On VPN - green = connected, red = disconnected. However, this only works when the application has started and I would like for it to continuously update the color of the label, if it suddenly disconnects and when you connect it again

Here's the code:

public bool CheckForVPNInterface()
        {
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();

                foreach (NetworkInterface networkInterfaces in interfaces)
                {
                    if (networkInterfaces.Description.Contains("Always-On VPN") && networkInterfaces.OperationalStatus == OperationalStatus.Up)
                    {
                        Label_Connection.BackColor = Color.Green;
                        Button_ConnectVPN.Text = "Disconnect";
                        return true;
                    }
                    else
                    {
                        Label_Connection.BackColor = Color.Red;
                        Button_ConnectVPN.Text = "Connect";
                    }
                }
                
            }
            return false;    
        }

Thanks in advance!

1 Answers

Maybe this function is only called once when the application starts. It may be necessary to try this process within a certain time using the timer.

aTimer = new System.Timers.Timer();
aTimer.Interval = 500; //doing a check every half second
aTimer.Elapsed += CheckForVPNInterface;

aTimer.Elapsed += CheckForVPNInterface; this code will run automatically every half second.

But I would not recommend calling this operation async. There will be error. This will require changes in certain places in the code. For this you will need to Invoke where it should work in the UI widget.

Related