WinForm里面的WPF窗口让应用程序挂起

时间:2017-03-10 12:06:33

标签: c# .net wpf winforms

当我在WinForms-Application中打开一个WPF窗口时,整个应用程序在MainForm关闭且Main-Method离开后挂起。只有Environment.Exit(0)有帮助。但这是一个黑客解决方案。我错过了另一个技巧吗?

在Application.Run-Loop中启动MainForm

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
        // Environment.Exit(0); -> only this helps.
    }

MainForm Button1:显示HostedWpfForm和纯WpfWindow

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

    private void button1_Click(object sender, EventArgs e)
    {
        // this hosted wpf control inside winform window causes no problems
        // new HostedWpfForm(new WpfUserControl()).Show();

        // this pure wpf window hangs after closing MainForm and exit Main
        // only Environment.Exit(0) at the end of Program.Main helps to close!
        WpfWindow wpfwnd = new WpfWindow();
        ElementHost.EnableModelessKeyboardInterop(wpfwnd);
        wpfwnd.Show();
    }
}

HostedWpfForm看起来像这样并且没有问题

public partial class HostedWpfForm : Form
{
    public HostedWpfForm(UIElement uiElement)
    {
        InitializeComponent();

        ElementHost host = new ElementHost();
        host.Dock = DockStyle.Fill;
        host.Child = uiElement;
        Controls.Add(host);
    }
}

WpfUserControl

public partial class WpfUserControl : UserControl
{
    public WpfUserControl()
    {
        InitializeComponent();
    }
}

导致问题的WpfWindow

public partial class WpfWindow : Window
{
    public WpfWindow()
    {
        InitializeComponent();
    }
}

顺便说一句:我添加了这些ProjectTypeGuids,以便能够在项目中添加Wpf-Window。

<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

有人知道,为什么纯粹的wpf窗口会导致这些悬挂问题?

0 个答案:

没有答案