Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I re-open WPF window in the same pragrom/application?

Tags:

c#

wpf

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);
    }
like image 481
cindywmiao Avatar asked Nov 02 '22 01:11

cindywmiao


1 Answers

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);        
}
like image 154
Tobi Avatar answered Nov 14 '22 04:11

Tobi