display message box only once

3k Views Asked by At

I am using the following code to display a message box when the charging level is reached

private void timer1_Tick(object sender, EventArgs e)
    {
        battery = Convert.ToInt32(power.BatteryLifePercent * 100);

        while (battery == 100)
        {
            MessageBox.Show("charging full disconnect the charger");
        }
    }

this code is working . but it is showing messagebox more than once. I just want to show it only once.

Thank you

2

There are 2 best solutions below

0
On

The condition associated with your while loop will never be reached the way it is coded. That is why the body of the loop will keep getting executed.

You need to embed code that changes or refreshes the condition. However, if you do this the program will draw much resources since the battery charging process is generally time consuming. What you would then need to do is probable do a thread.sleep for some duration or better yet use a timer.

This code example is doing something similar and is probably worth review in your case: BlackWasp-PowerStatusCheck.

2
On

Without more information it is hard to determine the actual problem. However, you can probably quickly fix the issue by using a variable to track whether you have displayed the message yet.

PowerStatus power = SystemInformation.PowerStatus;

int battery = 0;
bool battery_message_shown = false;

if( battery == 100 && battery_message_shown == false )
{
  battery_message_shown = true;
  MessageBox.Show("charging full");
}

Although, ideally, this code simply wouldn't be called unless it is time to show the message. I would need to see the larger picture to figure that out though.