I have a Form that throws this when I close it:
"Invoke or BeginInvoke cannot be called on a control until the window handle has been created."

This seems to be the offending code, running in a child thread:

this.Invoke(new someDelegate(someMethod));

I figured that if I could capture the user clicking on the X in the window chrome I could stop this thread before it tries calling the (already closed) Main thread. I'm not finding anything useful by googling, which keywords should I be searching for? What am I doing wrong? Should I just wrap it in a try{}?


You can use an even FormClosing. Create this event on form creation, and when you will try to exit form, the event formClosing will be rised:

public Form1()
            this.FormClosing+=new FormClosingEventHandler(Form1_FormClosing);

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
            //here you do the code!

btw, for which control do you use delegate for invoke it? If you wont salve the problem, please feel free to paste some of the code in here - so I can be in a bigger help.

Thank you Mitja, that is just what I need. The delegate is just to some TCP handler, nothing that will get clobbered by closing uncleanly.

Have a great day!