How to run a method until the return is true(true) ? Windows Forms C#

Asked

Viewed 30 times

1

I have a condition where the main FORM only opens when the charger is connected.

How do I keep updating the battery percentage in the main FORM ?

How do I keep monitoring if he removes the charger after going through the check ?

Method that searches the battery percentage:

 public static int GetPercentBattery() {
        int percent = 0;          

        try {

            ManagementObjectSearcher s2 = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Battery");
            foreach (ManagementObject mo in s2.Get()) {                   
                
                percent = Int32.Parse(mo["EstimatedChargeRemaining"].ToString().Trim());
            }               
        }
        catch (Exception e) {
            string mensagem = "Erro no teste da Bateria: " + e.Message;
            Console.WriteLine(mensagem);                
            throw new Exception("Erro no teste da Bateria");
        }

        return percent;
}

1 answer

0

Hello, I would try something recursive. Follow an untested example of how I would do, validate the idea and modify until you get the result you expect...

public static bool GetPercentBattery() 
{
    int percent = 0;          
    try {
        ManagementObjectSearcher s2 = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Battery");
        ManagementObject mo in s2.Get();                   
        percent = Int32.Parse(mo["EstimatedChargeRemaining"].ToString().Trim());
        if(percent == 100)
            return true;
        else
            GetPercentBattery();
    }
    catch (Exception e) {
        string mensagem = "Erro no teste da Bateria: " + e.Message;
        Console.WriteLine(mensagem);                
        throw new Exception("Erro no teste da Bateria");
    }
    return false;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.