从控制台应用程序重新打开WPF窗口

Tom*_*aps 11 .net c# wpf console-application winforms

我想从Console应用程序打开一个WPF窗口.在提到这篇文章后,它运作正常.

问题是:当用户关闭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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

如何重新打开WPF窗口?

H.B*_*.B. 22

您不应该与窗口一起创建应用程序,而只能单独创建一次,同时通过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);
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,如果你想重新打开同一个窗口,确保它永远不会完全关闭,为此你可以处理Closing事件并取消它e.Cancel = true;,然后只需调用Hide窗口"关闭"它并Show"打开"它稍后再试.