Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it absolutely safe to display a WPF window from a WinForms form?

I would like to display a WPF window from a windows forms application (.NET 3.5).

This code seems to work without any problem in a sample project:

public partial class WinFormsForm1 : Form
{
    public WinFormsForm1() {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e) {
      WpfWindow1 w = new WpfWindow1();
      w.Show();
    }
}

The form is started from Main() as a normal Winforms form:

Application.Run(new WinFormsForm1());

This seems to me too easy to be true. Are there any shortcomings in this? Is this safe to do?

like image 482
Marek Avatar asked Oct 06 '10 08:10

Marek


1 Answers

It has one serious shortcoming: the modeless WPF window would not get keyboard input.

The EnableModelessKeyboardInterop method call needs to be added before the WPF window is shown:

  WpfWindow1 w = new WpfWindow1();
  System.Windows.Forms.Integration.ElementHost.EnableModelessKeyboardInterop(w);
  w.Show();

ElementHost resides in WindowsFormsIntegration.dll.

Further reading: http://msdn.microsoft.com/en-us/library/aa348549.aspx

like image 103
Marek Avatar answered Oct 12 '22 05:10

Marek