gpt4 book ai didi

c# - WPF 只能打开一个窗口?

转载 作者:行者123 更新时间:2023-11-30 19:35:00 25 4
gpt4 key购买 nike

假设有两个项目,一个 WinForms 项目和一个 WPF 项目,在 WinForms 项目中,将以下代码放在 Main() 中并删除 Application.Run 没有问题:

        while (true)
{
Thread.Sleep(1000);
Form1 window = new Form1();
window.Show();
Thread.Sleep(1000);
window.Close();
}

但是,在 WPF 应用程序中,删除 StartupUri="Window1.xaml"然后创建:

    public App()
{
while (true)
{
Thread.Sleep(1000);
Window window = new Window();
window.Show();
Thread.Sleep(1000);
window.Close();
}
}

程序无限循环,但窗口只打开一次?

最佳答案

您需要像这样更改 ShutdownMode

public App()
{
this.ShutdownMode = ShutdownMode.OnExplicitShutdown;
while (true)
{
Thread.Sleep(1000);
Window window = new Window();
window.Show();
Thread.Sleep(1000);
window.Close();
}
//Will never get here with this sample code,
//but this would be how you close the app.
this.Shutdown();

}

否则 WPF 会将关闭第一个打开的窗口视为关闭应用程序。虽然循环中的代码会继续运行。

The lifetime of some applications may not be dependent on when the main window or last window is closed, or may not be dependent on windows at all. For these scenarios you need to set the ShutdownMode property to OnExplicitShutdown, which requires an explicit Shutdown method call to stop the application. Otherwise, the application continues running in the background.

MSDN:ShutdownMode Property

关于c# - WPF 只能打开一个窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/663942/

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