【发布时间】:2011-12-24 06:13:39
【问题描述】:
我想从控制台应用程序打开 WPF 窗口。参考this post后,效果很好。
问题是:当用户(手动)关闭 WPF 窗口时,无法再从控制台重新打开,抛出异常消息:“Cannot create more than one System.Windows.Application instance in the same应用程序域。”
代码如下:
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 窗口?
【问题讨论】:
标签: c# .net wpf winforms console-application