WinUI3 視窗置頂 示範

在 App.xaml.cs 加入以下程式碼:
把原本的 m_window 改為 static ,並建立靜態方法,讓外部可以存取自訂的 SetWindowTopmost 和 SetWindowCancelTopmost,使用 user32.dll 的 SetWindowPos 函式來達成置頂和取消置頂的功能
    
using System.Runtime.InteropServices;
using WinRT.Interop;


private static Window m_window;

// 設定視窗置頂
public static void SetWindowTopmost()
{
    IntPtr hwnd = WindowNative.GetWindowHandle(m_window);
    SetWindowPos(hwnd, HWndTopmost, 0, 0, 0, 0, SwpNoMove | SwpNoSize);
}

// 設定視窗非置頂
public static void SetWindowCancelTopmost()
{
    IntPtr hwnd = WindowNative.GetWindowHandle(m_window);
    SetWindowPos(hwnd, HWndCancelTopmost, 0, 0, 0, 0, SwpNoMove | SwpNoSize);
}

[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);


private static readonly IntPtr HWndTopmost = new IntPtr(-1);
private static readonly IntPtr HWndCancelTopmost = new IntPtr(-2);
const uint SwpNoSize = 0x0001;
const uint SwpNoMove = 0x0002;
    

這樣在其他地方例如 MainWindow 中就可以很簡單的使用下面的程式碼來將是裝置頂或取消置頂
    
// 將視窗置頂
App.SetWindowTopmost();

// 將視窗取消置頂
App.SetWindowCancelTopmost();
    

留言