1

I am trying to start a WPF application using Win Forms application.

Here is my code

private void button2_Click(object sender, EventArgs e)
    {
        try
        {
            var app = new App();
            app.InitializeComponent();
            app.Run(new MainWindow());
        }
        catch (Exception ex)
        {

            MessageBox.Show(ex.ToString());
        }
    }

When i click the button it will load WPF app. Then if i close the WPF and click the button again then i get the following error

Cannot create more than one System.Windows.Application instance in the same AppDomain

4

1 回答 1

0

您不能在 App 类中启动多个实例。所以你可以使用一个 App 实例来解决这个问题。答案如下

 public partial class Form1 : Form
    {
        App app;

        public Form1()
        {
            InitializeComponent();
            app = new App();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                app.InitializeComponent();
                app.MainWindow = new MainWindow();
                app.ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown;
                app.MainWindow.Show();
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.ToString());
            }
        }
    }
于 2013-09-14T14:52:39.943 回答