从控制台应用程序重新打开WPF窗口
本文关键字:WPF 窗口 新打开 控制台 应用程序 | 更新日期: 2023-09-27 18:13:53
我想从控制台应用程序打开一个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();
}
}
如何重新打开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
来"打开"它。
当你把window作为参数添加到app. run时,你就把你的应用的生命周期和你的window联系起来了。不要那样做:
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.Show();
//User closes the opened window manually.
}
我没有机会自己测试,但是在阅读了你的错误之后,我发现了一些信息。基本上,听起来您正在运行的AppDomain
在每个应用程序中只能使用一次-因此,每次想要重新创建应用程序时,可能需要创建一个新的AppDomain
。关于这方面的更多信息,请看这里。
或者,您可以使用System.Diagnostics.Process.Start(...)
来正确启动应用程序。参考这里的Process
类文档。
最后,如果您只是希望允许用户从命令行运行应用程序,那么编写命令脚本并从命令行执行可能会更简单。