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; //this will throw an ObjectDisposedException if the Leave event was caused by clicking on button1 //this will NOT throw an ObjectDisposedException if the Leave event was caused by clicking on button2 //How can I find out at which point of time the button (or any other Control) can be safely disposed, or how can I force button1 to finish all it needs to do? button1.Dispose(); } } public class myButton : Button { internal bool WillBeDisposed = false; protected override void WndProc(ref Message m) { if (WillBeDisposed) return; //doesn't help base.WndProc(ref m); } } } }
GC.SuppressDispose()
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)