gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:37:21 28 4
gpt4 key购买 nike

我想从控制台应用程序打开 WPF 窗口。引用this post后, 它工作正常。

问题是:当用户关闭 WPF 窗口(手动)时,它无法再从控制台重新打开,并抛出异常消息:“无法在同一个系统中创建多个 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 以稍后再次“打开”它。

关于c# - 从控制台应用程序重新打开 WPF 窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8047610/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com