参考:https://www.likecs.com/ask-10337653.html#sc=200
【解决方案1】
根目录下的App.xaml.cs
//设置界面宽高
#if WINDOWS
using Microsoft.UI;
using Microsoft.UI.Windowing;
using Windows.Graphics;
#endif

namespace MauiAppForWin
{
    public partial class App : Application
    {
        const int WindowWidth = 480;
        const int WindowHeight = 800;

        public App()
        {
            InitializeComponent();

            MainPage = new MainPage();

            //使用MainPage的页面配置
            //var width = (int)MainPage.WidthRequest;
            //var height = (int)MainPage.HeightRequest;

            Microsoft.Maui.Handlers.WindowHandler.Mapper.AppendToMapping(nameof(IWindow), (handler, view) =>
            {
                //设置界面宽高
#if WINDOWS
            var mauiWindow = handler.VirtualView;
            var nativeWindow = handler.PlatformView;
            nativeWindow.Activate();
            IntPtr windowHandle = WinRT.Interop.WindowNative.GetWindowHandle(nativeWindow);
            WindowId windowId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(windowHandle);
            AppWindow appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(windowId);
            appWindow.Resize(new SizeInt32(WindowWidth, WindowHeight));
#endif
            });

        }
    }
}

【解决方案2】
目录:Platforms/Windows/App.xaml.cs
重写OnLaunched

using Microsoft.UI.Xaml;
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
//设置界面宽高
using Microsoft.UI;
using Microsoft.UI.Windowing;
using Windows.Graphics;
using WinRT.Interop;

namespace MauiAppForWin.WinUI
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    public partial class App : MauiWinUIApplication
    {
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// 设置界面宽高
        /// </summary>
        /// <param name="args"></param>
        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            base.OnLaunched(args);
            var currentWindow = Application.Windows[0].Handler.PlatformView;
            IntPtr _windowHandle = WindowNative.GetWindowHandle(currentWindow);
            var windowId = Win32Interop.GetWindowIdFromWindow(_windowHandle);

            AppWindow appWindow = AppWindow.GetFromWindowId(windowId);
            appWindow.Resize(new SizeInt32(350, 600));
        }
        protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
    }
}

  

posted on 2022-12-29 17:52  邢帅杰  阅读(759)  评论(0编辑  收藏  举报