Home > Blockchain >  How to control the SerialPort when program is force terminated?
How to control the SerialPort when program is force terminated?

Time:02-04

I am making a WinForm program that uses the SerialPort to control the amount of light. 100% for the first 10 minutes, 97% for the next 20 minutes, and 94% for the remaining 30 minutes.

The problem occur when I force close the program. I don't have a way to turn off the lights currenly working.

Is there any way to solve this?


Edit

Is it possible to create an event that occurs just before the program exits?

CodePudding user response:

Based on @Mong Zhu's answer, I solved it like this:

FormClosing  = (sender, e) =>
{
  if (serialPort.IsOpen)
  {
      serialPort.WriteBytes(Percent0); // turning off the light
      serialPort.Close();
  }
};

If you add a Form.Closing event, it will work not only when the form closes, but also when the process exits.

  • Related