我想从控制台应用程序中打开WPF窗口。在引用this post之后,它可以正常工作。

问题是:当用户(手动)关闭WPF窗口时,无法再从控制台重新打开它,并抛出异常消息:“在同一AppDomain中不能创建多个System.Windows.Application实例。”

这是代码:

class Program
    {
        static void Main(string[] args)
        {
            string input=null;
            while ((input = Console.ReadLine()) == "y")
            {
                //Works fine at the first iteration,
                //But failed at the second iteration.
                StartWpfThread();
            }
        }
        private static void OpenWindow()
        {
            //Exception(Cannot create more than one System.Windows.Application instance in the same AppDomain.)
            //is thrown at the second iteration.
            var app = new System.Windows.Application();
            var window = new System.Windows.Window();
            app.Run(window);
            //User  closes the opened window manually.
        }
        private static void StartWpfThread()
        {
            var thread = new Thread(() =>
            {
                OpenWindow();
            });
            thread.SetApartmentState(ApartmentState.STA);
            thread.IsBackground = false;
            thread.Start();
        }
    }

如何重新打开WPF窗口?

最佳答案

您不应该与窗口一起创建应用程序,而只能单独创建一次,还应通过分别设置ShutdownMode来确保关闭窗口后它不会退出,例如

class Program
{
    static Application app;
    static void Main(string[] args)
    {
        var appthread = new Thread(new ThreadStart(() =>
            {
                app = new Application();
                app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
                app.Run();
            }));
        appthread.SetApartmentState(ApartmentState.STA);
        appthread.Start();

        while (true)
        {
            var key =Console.ReadKey().Key;
            // Press 1 to create a window
            if (key == ConsoleKey.D1)
            {
                // Use of dispatcher necessary as this is a cross-thread operation
                DispatchToApp(() => new Window().Show());
            }
            // Press 2 to exit
            if (key == ConsoleKey.D2)
            {
                DispatchToApp(() => app.Shutdown());
                break;
            }
        }
    }

    static void DispatchToApp(Action action)
    {
        app.Dispatcher.Invoke(action);
    }
}

另外,如果您想重新打开同一个窗口,请确保它从未完全关闭过,为此,您可以处理Closing事件并使用e.Cancel = true;取消它,然后只需在窗口上调用Hide将其“关闭”,并将Show设置为稍后再次“打开”它。

关于c# - 从控制台应用程序重新打开WPF窗口,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8047610/

10-12 12:49
查看更多