You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让.NET MAUI的Windows和Android应用启动时窗口最大化?遇DllImport问题

.NET MAUI 实现Windows和Android启动时窗口最大化(解决DllImport找不到问题)

Windows平台问题修复与实现

你遇到的DllImport找不到问题,核心是缺少必要的命名空间,同时代码结构需要调整:

  • 必须添加System.Runtime.InteropServices命名空间才能使用DllImport特性
  • ShowWindow方法定义需放在类内部,建议用常量替代魔法数字提升可读性

修正后的Windows平台代码:

using System.Runtime.InteropServices;
using Microsoft.Maui;

namespace YourAppNamespace;

public partial class App : Application
{
    public App()
    {
        InitializeComponent();
        MainPage = new MainPage();

        // 注册窗口映射逻辑
        WindowHandler.Mapper.AppendToMapping(nameof(IWindow), (handler, view) =>
        {
#if WINDOWS
            var nativeWindow = handler.PlatformView;
            nativeWindow.Activate();
            IntPtr windowHandle = WinRT.Interop.WindowNative.GetWindowHandle(nativeWindow);
            ShowWindow(windowHandle, SW_MAXIMIZE);
#endif
        });
    }

#if WINDOWS
    private const int SW_MAXIMIZE = 3; // 最大化窗口的常量定义

    [DllImport("user32.dll")]
    private static extern bool ShowWindow(IntPtr hWnd, int cmdShow);
#endif
}

Android平台实现

Android端要实现启动时窗口最大化(占满屏幕),可通过修改MainActivity.cs设置窗口属性:

namespace YourAppNamespace;

[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
public class MainActivity : MauiAppCompatActivity
{
    protected override void OnCreate(Bundle? savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // 设置窗口占满屏幕(包含状态栏区域)
        Window.SetFlags(WindowManagerFlags.LayoutNoLimits, WindowManagerFlags.LayoutNoLimits);
        // 若需要隐藏状态栏,可添加以下行
        // Window.AddFlags(WindowManagerFlags.Fullscreen);
    }
}

注意事项

  • Windows平台:确保项目已引用Microsoft.Windows.SDK.Contracts包(MAUI默认集成,若缺失可手动添加)
  • Android平台:不同API级别对窗口属性的支持略有差异,需在目标版本中测试验证

内容的提问来源于stack exchange,提问作者Trey Balut

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 10:52:17