The program I am writing includes a console. I've created a UserControl called Console. This Console class has multiple background workers doing various tasks. The problem I have run into is that if I place this control on a form and then close it, I occasionally run into problems where the BackgroundWorker threads are making calls to disposed objects.
Based on this thread, I need to stop the form closing and handle the close request myself. I have most of this written successfully, but the major problem I'm running into is subscribing to the ParentForm's FormClosing event.
I've been trying to use this.ParentForm but I can't find a good place where this isn't null.
Of course, I can't do this in the constructor, as it is being generated at this point.
I also can't use this in the ParentChanged event as mentioned in this thread. When this fires, this.Parent is no longer null, but that's not this.ParentForm. I realize sometimes it could be, but for example, I currently have this sitting in a tab control so that's not quite what I want.
Then we also have this suggestion to try hooking into the this.Load function (I'm referencing the second answer, not the selected one) but again, this.ParentForm is null here. As before, this.Parent has a value but it's not quite what I want.
Finally, I thought I found the solution to my problem when I came across this thread suggesting to override OnCreateControl but yet again... no luck, both are null.
After the form is loaded, I have added a button that I can press, and at that point, I have been able to determine that this.ParentForm does in fact get populated correctly.
My question- where can I get the UserControl's this.ParentForm where it isn't null so I can subscribe to it's events?
Edit: Adding some of my code per LarsTech's request:
The result of this code is:
This.Parent has a value
This.ParentForm is null
private MyConsole(string COMPort)
{
// I do this so that the console window is created by the time I have started my Background Workers
this.CreateHandle();
// Generate the form
InitializeComponent();
// set the COM Port Name
_COMPort = COMPort;
ReadOnly = true;
ActiveCloseRequest = false;
// This just creates 1 or 2 background workers
StartBackgroundWorkers();
this.ParentChanged += MyConsole_ParentChanged;
}
void MyConsole_ParentChanged(object sender, EventArgs e)
{
if (this.Parent == null)
{
Console.WriteLine("This.Parent is null");
}
else
{
Console.WriteLine("This.Parent has a value");
}
if (this.ParentForm == null)
{
Console.WriteLine("This.ParentForm is null");
}
else
{
Console.WriteLine("This.ParentForm has a value");
}
}