I am develop a new app for Windows 11 with WinUi 3 and I want when I open the app always open in the center of my screen/display. It is possible?
I am using PInvoke.User32 for set window size (if it helps).
Thank you!
I am develop a new app for Windows 11 with WinUi 3 and I want when I open the app always open in the center of my screen/display. It is possible?
I am using PInvoke.User32 for set window size (if it helps).
Thank you!
The following example code is simplistic but achieves what you are asking for.
Create a Windows App SDK project using the blank app template.
In the App.xaml.cs file, change the OnLaunched() method to the following:
m_window = new MainWindow();
var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(m_window);
Microsoft.UI.WindowId windowId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(hWnd);
Microsoft.UI.Windowing.AppWindow appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(windowId);
if (appWindow is not null)
{
Microsoft.UI.Windowing.DisplayArea displayArea = Microsoft.UI.Windowing.DisplayArea.GetFromWindowId(windowId, Microsoft.UI.Windowing.DisplayAreaFallback.Nearest);
if (displayArea is not null)
{
var CenteredPosition = appWindow.Position;
CenteredPosition.X = ((displayArea.WorkArea.Width - appWindow.Size.Width) / 2);
CenteredPosition.Y = ((displayArea.WorkArea.Height - appWindow.Size.Height) / 2);
appWindow.Move(CenteredPosition);
}
}
m_window.Activate();
When you run the app, its main window will be centered in the display.
Works Great!!! i just copy paste your funcion under a general file and call it from every screen
public MYWindowClass
{
this.InitializeComponent();
var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
FuncionesGenerales.CenterToScreen(hWnd);
}
Then in my general file
FuncionesGenerales.CenterToScreen(IntPtr hWnd)
{
Microsoft.UI.WindowId windowId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(hWnd);
Microsoft.UI.Windowing.AppWindow appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(windowId);
if (appWindow is not null)
{
Microsoft.UI.Windowing.DisplayArea displayArea = Microsoft.UI.Windowing.DisplayArea.GetFromWindowId(windowId, Microsoft.UI.Windowing.DisplayAreaFallback.Nearest);
if (displayArea is not null)
{
var CenteredPosition = appWindow.Position;
CenteredPosition.X = ((displayArea.WorkArea.Width - appWindow.Size.Width) / 2);
CenteredPosition.Y = ((displayArea.WorkArea.Height - appWindow.Size.Height) / 2);
appWindow.Move(CenteredPosition);
}
}
}
Thank You