Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start two windows in sequence from App.xaml.cs WPF

I want to let the user login before the MainWindow shows up.

The first window shows up, works fine and after closing all other WindowName.ShowDialog() calls do not work.

My code: In app.xaml I removed StartupUri and replaced it with

Startup="Application_Startup"

Which looks like this (App.xaml.cs):

private void Application_Startup(object sender, StartupEventArgs e)
{
    Window1 window1 = new Window1();
    window1.ShowDialog();

    MainWindow window2 = new MainWindow();
    window2.ShowDialog();
}

I have two completly untouched windows (besides the title) second one looks the same:

<Window x:Class="Delete_Me.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Delete_Me"
        mc:Ignorable="d"
        Title="First window" Height="300" Width="300">
    <Grid>

    </Grid>
</Window>

Code behind is also untouched.

Question How can I start two windows from App.xaml.cs in sequence? Or what would be a better way to do this?

My approaches I tried to swap out the two windows, which didn't change anything.

Of course I could start the LoginForm in the contructor / OnLoaded from the MainWindow, but that does not seem to be a beautiful solution to the problem.

I would like to not even start the MainWindow, if the authentication fails.

Any suggestions? Thank you.

like image 859
Luchspeter Avatar asked Feb 14 '26 23:02

Luchspeter


1 Answers

A WPF application quits if no more window is existing. This means your application is stopped after closing the first window before the second window is created.

To solve your problem you need to create the second window before closing the first one. Just change your code to

Window1 window1 = new Window1();
MainWindow window2 = new MainWindow();

window1.ShowDialog();
window2.ShowDialog();

to fix it.

like image 101
Fruchtzwerg Avatar answered Feb 16 '26 11:02

Fruchtzwerg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!