想设置最小尺寸为1000*100像素怎么做?
一、问gpt
csharp
using Microsoft.UI.ViewManagement;
using Windows.UI.ViewManagement;
// 在应用程序启动时设置最小缩放尺寸
ApplicationView.PreferredLaunchViewSize = new Size { Width = 800, Height = 600 };
ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize;
结果:没有效果。
csharp
Application.Current.Window.SetPreferredMinSize(new Size(800, 600));
代码报错跑不了。
二、参考网站1
使用SetWindowSubclass函数钩住WM_GETMINMAXINFO并设置min大小,没有给出代码。
三、https://github.com/microsoft/microsoft-ui-xaml/issues/2945
问题:如何设置最小窗口大小(桌面)
给出的解决方案:
-
ApplicationView.GetForCurrentView().SetPreferredMinSize(new Size(800, 600));
直接跑不起来了,报错:System.Runtime.InteropServices.COMException:"找不到元素。 (0x80070490)"
-
Desktop WinUI 3在Window类上还没有MinSize或MaxSize属性,对于开发人员来说,这样做并不简单。在Win32中执行此操作的方法是侦听消息WM_GETMINMAXINFO,但您需要首先访问在Windows中获取消息的过程(WindowProc)。不幸的是,WinUI 3 Desktop没有公开它,所以解决方案是子类化。子类允许在WindowProc之前拦截和处理发送到窗口的消息。
但是PInvoke一直报错。
四、https://github.com/unoplatform/uno/discussions/9092
膜拜大佬,用最简单的方法解决问题
appwindow尺寸改变时,写在函数里,当尺寸小于最小的宽高时resize当前最小宽高。
原文代码:
csharp
/// <summary>
/// Sets the size of the Application Window when running in Windows.
/// </summary>
/// <param name="window"></param>o
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns></returns>
public static bool Resize(Window window, int width, int height)
{
try
{
#if NET7_0_WINDOWS10_0_18362
// Use 'this' rather than 'window' as variable if this is about the current window.
IntPtr hWnd = WinRT.Interop.WindowNative.GetWindowHandle(window);
Microsoft.UI.WindowId windowId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(hWnd);
AppWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(windowId);
AppWindow.Resize(new Windows.Graphics.SizeInt32 { Width = width, Height = height });
AppWindow.Changed += AppWindow_Changed;
#else
_ = Log.Warn($"{nameof(WindowHelper)}.{nameof(Resize)}() is not currently supported on this platform.");
#endif
return true;
}
catch (Exception ex)
{
_ = Log.Error(ex);
}
return false;
}
private static void AppWindow_Changed(Microsoft.UI.Windowing.AppWindow sender, Microsoft.UI.Windowing.AppWindowChangedEventArgs args)
{
try
{
#if NET7_0_WINDOWS10_0_18362
if (AppWindow == null)
return;
if (AppWindow.Size.Height < MinHeight && AppWindow.Size.Width < MinWidth)
AppWindow.Resize(new Windows.Graphics.SizeInt32 { Width = MinWidth, Height = MinHeight });
else if (AppWindow.Size.Height < MinHeight)
AppWindow.Resize(new Windows.Graphics.SizeInt32 { Width = AppWindow.Size.Width, Height = MinHeight });
else if (AppWindow.Size.Width < MinWidth)
AppWindow.Resize(new Windows.Graphics.SizeInt32 { Width = MinWidth, Height = AppWindow.Size.Height });
#endif
}
catch (Exception ex)
{
_ = Log.Error(ex);
}
}