0%

WinUI3修改默认窗口大小

WinUI3修改默认窗口大小

基于PInvoke.User32.GetDpiForWindow(hwnd),可以适应不同的DPI

首先需要通过NuGet添加包:PInvoke.User32

然后在App.xaml.cs中定义函数:

1
2
3
4
5
6
7
8
9
10
11
private void SetWindowSize(IntPtr hwnd, int width, int height)
{
var dpi = PInvoke.User32.GetDpiForWindow(hwnd);
float scalingFactor = (float)dpi / 96;
width = (int)(width * scalingFactor);
height = (int)(height * scalingFactor);

PInvoke.User32.SetWindowPos(hwnd, PInvoke.User32.SpecialWindowHandles.HWND_TOP,
0, 0, width, height,
PInvoke.User32.SetWindowPosFlags.SWP_NOMOVE);
}

然后在App.xaml.csOnLaunched下使用:

1
2
IntPtr hwnd = WinRT.Interop.WindowNative.GetWindowHandle(window);
SetWindowSize(hwnd, 480, 800)

基于appWindow.Resize,无法适应不同的DPI

只需要在App.xaml.csOnLaunched下使用:

1
2
3
4
// Use 'this' rather than 'window' as variable if this is about the current window.
IntPtr hWnd = WinRT.Interop.WindowNative.GetWindowHandle(window);
var windowId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(hWnd);
var appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(windowId);

然后即可对窗口默认大小进行设定:

1
appWindow.Resize(new Windows.Graphics.SizeInt32 { Width = 480, Height = 800 });

AppWindow对象还有其他几个功能,如MoveAndResizeShowHide和修改标题栏的功能。


最后吐槽一下Microsoft Doc是个什么垃圾玩意。

参考资料

1、c# - WINUI 3.0 - Reunion 0.5 window size/// - Stack Overflow