Hi friend, I hope you're having a nice day.
In WinUI 3 for a C++ desktop application, if you want to close all windows at once without terminating the event loop, you need to manage the list of windows yourself, as there is no built-in equivalent to Win32's EnumWindowsProc
in WinUI 3. However, you can achieve this by maintaining a list of window references and closing them programmatically.
Here’s how you can approach this:
Step-by-Step Approach
- Maintain a List of Window References:
- Store references to all your windows in a list or vector when you create them.
- Close All Windows:
- Iterate through the list and close each window when needed.
Example Implementation
Below is an example to illustrate this approach:
- Header File (
App.h
):
#pragma once
#include "App.xaml.g.h"
#include <vector>
class App : public winrt::implementation::AppT<App>
{
public:
App();
void OnLaunched(winrt::Microsoft::UI::Xaml::LaunchActivatedEventArgs const&);
void CloseAllWindows();
private:
std::vector<winrt::Microsoft::UI::Xaml::Window> m_windows;
winrt::Microsoft::UI::Xaml::Window m_invisibleWindow;
};
- Source File (
App.cpp
):
#include "pch.h"
#include "App.h"
#include "MainWindow.h"
App::App()
{
InitializeComponent();
}
void App::OnLaunched(winrt::Microsoft::UI::Xaml::LaunchActivatedEventArgs const&)
{
m_invisibleWindow = winrt::Microsoft::UI::Xaml::Window();
m_invisibleWindow.Title(L"Invisible Window");
m_invisibleWindow.Visibility(winrt::Microsoft::UI::Xaml::Visibility::Collapsed);
m_invisibleWindow.Activate();
auto mainWindow = winrt::make<MainWindow>();
m_windows.push_back(mainWindow);
mainWindow.Activate();
}
void App::CloseAllWindows()
{
for (auto& window : m_windows)
{
window.Close();
}
m_windows.clear();
}
- Main Window (
MainWindow.xaml.cpp
):
#include "pch.h"
#include "MainWindow.xaml.h"
MainWindow::MainWindow()
{
InitializeComponent();
}
Usage
When you need to close all windows, you can call the CloseAllWindows
method from the App
class.
Invisible Window
To keep the event loop running, the invisible window is created in the OnLaunched
method. It is kept hidden by setting its visibility to Collapsed
. This window will prevent the event loop from exiting when all other windows are closed.
I hope this helps you. Have a nice day!!