重新打开WPF窗口从一个控制台应用程序 [英] Re-Open WPF Window from a Console application
问题描述
我想从一个控制台应用程序中打开一个WPF窗口。参照<一后href="http://stackoverflow.com/questions/4509714/how-to-start-the-wpf-window-from-console-programmatically">this帖子,它工作正常。
I want to open a WPF Window from a Console application. After referring to this post, it works fine.
现在的问题是:当用户关闭WPF窗口(手动),它可以没有长重开从控制台,抛出异常的消息:不能在同一个创建多个System.Windows.Application实例AppDomain中。
The problem is: When the user closed the WPF Window (manually), it can no long be re-opened from the Console, throwing the exception message: "Cannot create more than one System.Windows.Application instance in the same AppDomain."
下面是code:
Here is the code:
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窗口如何?
How can I re-open the WPF Window?
推荐答案
您不应该一起窗口中创建应用程序,但只有一次分开,也确保它不会退出后,该窗口通过设置<$关闭C $ C> ShutdownMode 分别,例如:
You should not create the application together with the window but only once separately, also make sure that it does not exit after the window is closed by setting the ShutdownMode
respectively, e.g.
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);
}
}
如果你想重新打开同样的窗口,确保它永远不会完全关闭,要做到这一点,你可以处理关闭
事件,并使用取消<还code> e.Cancel = TRUE; ,就可以致电隐藏
窗口关闭就可以和显示
来打开了它以后。
Also if you want to re-open the very same window make sure it is never closed completely, to do that you can handle the Closing
event and cancel it using e.Cancel = true;
, then just call Hide
on the window to "close" it and Show
to "open" it again later.
这篇关于重新打开WPF窗口从一个控制台应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!