Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to close window form which is hosting WPF user control from within a WPF user control

Tags:

c#

winforms

wpf

I want to close a window form that is hosting a WPF user control. Something like this as used while closing a current form in window application. But for WPF application I am not able to get reference to user controls parent

How to get Form which is hosting this control so that I can close my form

this.Close()

like image 882
Shantanu Gupta Avatar asked Dec 07 '22 00:12

Shantanu Gupta


1 Answers

Add to your WpfControl property

public Form FormsWindow { get; set; }

In your WinForm add event handler for ElementHost's event ChildChanged:

using System.Windows.Forms.Integration; 

public MyForm() {
    InitializeComponent();
    elementHost.ChildChanged += ElementHost_ChildChanged;
}
void ElementHost_ChildChanged(object sender, ChildChangedEventArgs e) {
    var ctr = (elementHost.Child as UserControl1);
    if (ctr != null)
        ctr.FormsWindow = this;
}

After that you can use the FormsWindow property of your WpfControl to manipulate window. Example:

this.FormsWindow.Close();
like image 150
The Smallest Avatar answered Dec 11 '22 07:12

The Smallest