I need to run a new WPF window in parallel with the main one on button click. Another window should not open until the previous was closed. I found this answer to run a new window in separate thread and this answer to await the Closed event.
I tried to combine them using Task but encountered the following problem. A new window opens independently from the main one, but await task does not pause the function execution. In addition, when I close the main window, a new window remains.
Can anyone suggest me how to solve the problem?
bool signal = false;
private async void butHelp1_Click(object sender, RoutedEventArgs e)
{
// Check the global signal variable to not let a new window open
if (signal) return;
signal = true;
Task task = Task.Run(() =>
{
Thread thread = new(() =>
{
NewWindow window = new();
window.ShowDialog();
System.Windows.Threading.Dispatcher.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
});
// This line does not pause the function execution
await task;
signal = false;
}
>Solution :
If I understand correctly what you need, then look at this implementation:
private bool isClosedNewWindow = false;
private NewWindow? newWindow;
private void butHelp1_Click(object sender, RoutedEventArgs e)
{
if (isClosedNewWindow)
{
if (newWindow?.WindowState == WindowState.Minimized)
newWindow.WindowState = WindowState.Normal;
}
else
{
isClosedNewWindow = true;
newWindow = new NewWindow();
newWindow.Closed += delegate { isClosedNewWindow = false; };
newWindow.Show();
}
}