我想要在控制台应用程序中打开一个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窗口?