从 UserControl 访问 ParentForm

Accessing ParentForm from UserControl

我正在编写的程序包括一个控制台。我创建了一个名为 Console 的 UserControl。此控制台 class 有多个后台工作人员执行各种任务。我 运行 遇到的问题是,如果我将此控件放在窗体上然后关闭它,我偶尔会 运行 遇到 BackgroundWorker 线程正在调用已处理对象的问题。

基于this thread,我需要停止关闭表单并自行处理关闭请求。我已经成功编写了大部分内容,但我 运行 遇到的主要问题是订阅 ParentFormFormClosing 事件。

我一直在尝试使用 this.ParentForm,但我找不到 this 不为 null 的好地方。

当然,我不能在构造函数中这样做,因为它正在生成。

我也不能在 this thread 中提到的 ParentChanged 事件中使用它。触发时,this.Parent 不再为空,但那不是 this.ParentForm。我意识到有时它可能是这样,但是例如,我目前将它放在选项卡控件中,所以这不是我想要的。

然后我们还有 this suggestion 尝试连接到 this.Load 函数(我指的是第二个答案,而不是所选答案),但是 this.ParentForm 在这里是空的.和以前一样,this.Parent 有一个值,但它不是我想要的。

最后,当我遇到 this thread 建议重写 OnCreateControl 时,我以为我找到了解决问题的方法,但又一次......运气不好,两者都是空的。

加载表单后,我添加了一个可以按下的按钮,此时,我已经能够确定 this.ParentForm 实际上确实得到了正确填充。

我的问题 - 我在哪里可以获得 UserControlthis.ParentForm,它不是空的,所以我可以订阅它的事件?

编辑:根据 LarsTech 的要求添加我的一些代码:

这段代码的结果是:

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");
    }
}

您是否尝试过在 UserControl 的 Dispose() 方法中进行清理?这通常是一个更合乎逻辑的地方,因为窗体关闭后将释放其子控件。

不幸的是,自动生成的用户控件模板将 Dispose() 方法放在关联的 .Designer.cs 文件中。但是您可以将该方法移至您的主文件并对其进行修改以执行清理。