Hello,
if window is open already, just bring it to the front, so don't open a new instance.
For windows, Microsoft.Maui.Controls.Window do not have Activate() method in MAUI.
When you create a window events.AddWindows(windows => windows.OnWindowCreated will be execute. And you can get the MauiWinUIWindow from the window. MauiWinUIWindow have Activate method. You can get the needed window by the title. Then set it the public static MauiWinUIWindow secondWindow, here is my MauiProgram.cs code.
#if WINDOWS
public static MauiWinUIWindow secondWindow;
#endif
public static MauiApp CreateMauiApp()
{
builder
.UseMauiApp<App>()
.ConfigureLifecycleEvents(events =>
{
#if WINDOWS
events.AddWindows(windows => windows.OnWindowCreated(window => {
var mauiWinUIWindow = window as MauiWinUIWindow;
if(mauiWinUIWindow.Title== "newWIndow") {
secondWindow= mauiWinUIWindow;
}
}));
#endif
})
}
You need to add a Title for your newWindow
.
var SecondWindowPage = new Window()
{
Title ="newWIndow",
Page = view,
Height = height,
Width = width,
X = x,
Y = y,
};
Then, you need to add a flag to mark whether the window is open. If you want to make the window to the front, you can call MauiProgram.secondWindow.Activate();
directly.
if (SecondWindowCreated == false)
{
SecondWindow = SecondWindowPage;
SecondWindow.Created += (s, e) => { SecondWindowCreated = true; };
SecondWindow.Destroying += (s, e) => { SecondWindowCreated = false; };
Application.Current.OpenWindow(SecondWindow);
}
else
{
#if WINDOWS
MauiProgram.secondWindow.Activate();
#endif
}
Best Regards,
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.