大家,
我想要一个可以控制窗口打开和关闭多次的应用程序。例如,按1,打开一个窗口;按2,关闭窗口。
我发现了我的代码,只能执行一次。
有人可以帮我纠正吗?非常感谢。
public static void Main(string[] args)
{
var appthread = new Thread(new ThreadStart(() =>
{
app = new testWpf.App();
app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
app.Run();
}));
appthread.SetApartmentState(ApartmentState.STA);
appthread.Start();
while (true)
{
var key = Console.ReadKey().Key;
// press 1 to open
if (key == ConsoleKey.D1)
{
DispatchToApp(() => new Window().Show());
}
// Press 2 to exit
if (key == ConsoleKey.D2)
{
DispatchToApp(() => app.Shutdown());
}
}
}
static void DispatchToApp(Action action)
{
app.Dispatcher.Invoke(action);
}
答案 0 :(得分:2)
当您通过调用app.Shutdown()
关闭应用时,您需要先再次运行它以打开它的窗口。
您应该保存对窗口的引用并关闭它,而不是关闭整个应用程序。为此,您需要一个能够返回窗口引用的调度方法:
static void Main(string[] args)
{
var appthread = new Thread(new ThreadStart(() =>
{
app = new testWpf.App();
app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
app.Run();
}));
appthread.SetApartmentState(ApartmentState.STA);
appthread.Start();
Window win = new Window();
while (true)
{
var key = Console.ReadKey().Key;
// press 1 to open
if (key == ConsoleKey.D1)
{
win = DispatchToApp<Window>(() =>
{
var myWindow = new Window();
myWindow.Show();
return myWindow;
});
}
// Press 2 to exit
if (key == ConsoleKey.D2)
{
DispatchToApp(() => win.Close());
}
}
}
static TReturn DispatchToApp<TReturn>(Func<TReturn> action)
{
return app.Dispatcher.Invoke<TReturn>(action);
}
static void DispatchToApp(Action action)
{
app.Dispatcher.Invoke(action);
}