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

耗尽温柔 提交于 2019-11-29 01:30:22

问题


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?


回答1:


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




回答2:


Bottom line: it is. We have pretty heavy application combining both WPF and winforms: windows, user controls, modal dialogs, you name it... and it's working in the medical market. We've got into some dark corners, one is the infamous EnableModelessKeyboardInterop, another is having the WPF window be the child of the Winforms window, which you can read Here




回答3:


It is really that simple. I can't think of any downside doing it this way.



来源:https://stackoverflow.com/questions/3870498/is-it-absolutely-safe-to-display-a-wpf-window-from-a-winforms-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!