everyone,
I want one application that could control window open and close multi-time. For example, press 1, open a window; press 2, close the window.
And there is my code I found, which only could do this once.
Could somebody be nice to help me correct it? Thanks a lot.
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);
}
When you shutdown your app by calling app.Shutdown()
you would need to first run it again to open a windows of it.
You should save a reference to your window and close it instead of shutting down the whole app. In order to do that you need a dispatch method that is able to return the reference of the window:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With