Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open WinForm from WPF application?

Tags:

.net

winforms

wpf

I've created an WPF and WinForm Application, what i need to do is open the WinForm from the WPF application. Both are in the same solution but they're diferent projects.

I tried the following:

Dim newWinForm as New MainWindow
newWinForm.show()

I found a possible solution from here: Opening winform from wpf application programmatically

But i dont understand what exactly i have to do. I hope you could help me. Thanks!

like image 333
Emmanuel Santana Avatar asked May 16 '13 00:05

Emmanuel Santana


3 Answers

Generally you need to host your form in a WindowInteropHelper, like following in the WPF window Button.Click event handler:

C#:

private void button1_Click(object sender, RoutedEventArgs e) {
  Form1 form = new Form1();
  WindowInteropHelper wih = new WindowInteropHelper(this);
  wih.Owner = form.Handle;
  form.ShowDialog();
}

VB:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
    Dim form As New Form1()
    Dim wih As New WindowInteropHelper(Me)
    wih.Owner = Form.Handle
    form.ShowDialog()
End Sub

And of course you need to add reference/import of your project and System.Windows.Forms.dll

like image 184
terry Avatar answered Nov 18 '22 03:11

terry


Let's pretend that you the two projects are called WPFApp and WinFormApp.

Both of them declare a MainWindow class, which is the main application window.

In order to open the WinFormApp MainWindow from the WPFApp application, you simply need to perform the following on the WPFApp project:

  1. Add a reference to the WinFormApp project
  2. Add a reference to System.Windows.Forms
  3. Create a new WinFormApp.MainWindow object
  4. Call Show() on it
like image 41
gog Avatar answered Nov 18 '22 02:11

gog


The answer from Terry didn't work for me. I wanted to return to my WPF Window, but then I had to add the window's Handle as an argument to the ShowDialog() method. Which I could get fixed.

This solution from user dapi on a similar question worked better in my case:

var winForm = new MyFrm();
winForm.ShowDialog(new WpfWindowWrapper(Window.GetWindow(this)));

With a small helper class:

public class WpfWindowWrapper : System.Windows.Forms.IWin32Window
{
    public WpfWindowWrapper(Window wpfWindow)
    {
        Handle = new WindowInteropHelper(wpfWindow).Handle;
    }

    public IntPtr Handle { get; }
}
like image 1
ffonz Avatar answered Nov 18 '22 03:11

ffonz