Hi
I seem to have run in kind of a race condition. This is the very simplified version of the problem. (In reality there are several layers inbetween, the controls are no Buttons, but also inherited from Control etc.) I _need_ to remove and dispose my controls after e.g. a leave event as below.
If I click on button1 I get an ObjectDisposedException, because it needs to finish something. If I click on button2 it obviuously works.
How can I find out, when it is ready to be disposed? Or how can I force a Control to finish all it needs to do before disposing?
A possible solution should work for all inheritances of Control.
(My first maybe naive try was just to stop all messages as in code below. Nor helps an Application.DoEvents())
THANK YOU!
using System;
using System.Windows.Forms;
namespace Test
{
static class Program
{
static void Main()
{
Application.Run(new TestForm());
}
public class TestForm : Form
{
myButton button1;
myButton button2;
public TestForm()
{
TextBox tb = new TextBox();
Controls.Add(tb);
button1 = new myButton();
button1.Text = "button1";
button1.Location = new System.Drawing.Point(tb.Right, 0);
Controls.Add(button1);
button2 = new myButton();
button2.Text = "button2";
button2.Location = new System.Drawing.Point(button1.Right, 0);
Controls.Add(button2);
tb.Leave += new EventHandler(tb_Leave);
}
void tb_Leave(object sender, EventArgs e)
{
Controls.Remove(button1);
button1.WillBeDisposed = true;
button1.Dispose();
}
}
public class myButton : Button
{
internal bool WillBeDisposed = false;
protected override void WndProc(ref Message m)
{
if (WillBeDisposed) return; base.WndProc(ref m);
}
}
}
}