hi i close my form and serial port with a button
private
void button1_Click(object sender, EventArgs e){
if (serialPort1.IsOpen) serialPort1.Close();Close();
}
and with the X button in form
private
void Form1_FormClosing(object sender, FormClosingEventArgs e){
if (serialPort1.IsOpen) serialPort1.Close(); Close();}
but some times have problem and i get System.StackOverflowException
i dont know why?
AlanPosted Sep 20, 2008, 9:01 AM
Well, the exception you're getting is, of course, usually a sign that a method is calling itself recursively without limit until the stack eventually oveflows.
For the life of me, I can't see why you should still occasionally get it when you remove the Close() statement which was causing the FormClosing eventhandler to call itself repeatedly.
However, I'd try moving the 'serialPort1.Close()' line to the FormClosed eventhandler instead. I'd also call serialPort1.Dispose() at that point as well.
georgePosted Sep 20, 2008, 8:40 AM
AlanPosted Sep 20, 2008, 8:39 AM
Just remove the Close() statement from the FormClosing eventhandler - you don't need it as the form is closing anyway. The other statement should be left in, just in case the serial port hasn't been previously closed.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen) serialPort1.Close();
}
georgePosted Sep 20, 2008, 8:20 AM
Posted Sep 20, 2008, 12:10 AM
Button gets clicked
close the serial port
close the form
form closing event gets handled
close the serial port // problem lies either here
close the form // or here
Your form is being closed twice, and so is the serial port.