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

.NET MAUI如何设置窗口始终置顶?

如何让.NET MAUI应用始终处于置顶状态

.NET MAUI没有内置类似WPF Topmost="True"的全局属性,需要通过平台特定代码实现窗口置顶效果,以下是各平台的具体实现方案:

Windows平台

通过Win32 API的SetWindowPos设置窗口为置顶状态,结合P/Invoke调用实现:

#if WINDOWS
using Microsoft.Maui.Platform;
using System.Runtime.InteropServices;
using WinRT.Interop;
#endif

// 在页面或App初始化时调用此方法
private void EnableWindowTopmost()
{
#if WINDOWS
    var mauiWindow = Application.Current.Windows.First().Handler.PlatformView as MauiWinUIWindow;
    if (mauiWindow == null) return;

    var windowHandle = WindowNative.GetWindowHandle(mauiWindow.Window);
    
    [DllImport("user32.dll")]
    static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

    const uint SWP_NOMOVE = 0x0002;
    const uint SWP_NOSIZE = 0x0001;
    var HWND_TOPMOST = new IntPtr(-1);

    SetWindowPos(windowHandle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
#endif
}

macOS(Mac Catalyst)平台

通过设置NSWindow的层级为状态栏之上,实现窗口置顶:

#if MACCATALYST
using AppKit;
using UIKit;
#endif

// 在页面或App初始化时调用此方法
private void EnableWindowTopmost()
{
#if MACCATALYST
    var keyWindow = UIApplication.SharedApplication.KeyWindow;
    var nsWindow = keyWindow?.WindowScene?.Window as NSWindow;
    nsWindow?.SetLevel(NSWindowLevel.StatusBar + 1);
#endif
}

关键说明

  • Android平台:Android系统无常规全局窗口置顶API,普通应用无法实现类似桌面应用的置顶效果(仅悬浮窗场景可实现,但需申请特殊权限,不属于常规应用范畴)。
  • 你之前尝试的UnFocused/Disappearing事件调用Focus()无效,因为Focus()是控件级别的焦点操作,无法控制窗口的系统层级置顶。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 02:25:43