WinUI 3:阻止 Title Bar 双击

发布: (2025年12月5日 GMT+8 12:01)
2 min read
原文: Dev.to

Source: Dev.to

目标

防止主窗口在标题栏双击时最大化,同时保持其他行为不变。

目标

Código completo

using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using System;
using System.Runtime.InteropServices;
using Windows.Graphics;
using WinRT.Interop;

namespace TestApp.WinUI3
{
    /// <summary>
    /// An empty window that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainWindow : Window
    {
        private readonly IntPtr _hwnd;
        private readonly IntPtr _oldWndProc;
        private delegate IntPtr WndProcDelegate(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
        private readonly WndProcDelegate _newWndProc;
        private const uint WM_NCLBUTTONDBLCLK = 0x00A3;
        private const int GWLP_WNDPROC = -4;

        public MainWindow()
        {
            InitializeComponent();
            AppWindow.TitleBar.PreferredTheme = TitleBarTheme.UseDefaultAppMode;
            ExtendsContentIntoTitleBar = true;
            SetTitleBar(titleBar);
            OverlappedPresenter? presenter = OverlappedPresenter.Create();
            presenter.IsResizable = false;
            presenter.IsMaximizable = false;
            presenter.SetBorderAndTitleBar(true, true);
            AppWindow.Resize(new SizeInt32(425, 600));
            AppWindow.SetPresenter(presenter);
            _hwnd = WindowNative.GetWindowHandle(this);
            _newWndProc = new WndProcDelegate(WndProc);
            _oldWndProc = SetWindowLongPtr(_hwnd, GWLP_WNDPROC, _newWndProc);
        }

        private IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
        {
            if (msg == WM_NCLBUTTONDBLCLK)
            {
                return IntPtr.Zero;
            }
            return CallWindowProc(_oldWndProc, hWnd, msg, wParam, lParam);
        }

        [DllImport("user32.dll", EntryPoint = "SetWindowLongPtrW")]
        private static extern IntPtr SetWindowLongPtr(IntPtr hWnd, int nIndex, WndProcDelegate newProc);

        [DllImport("user32.dll", EntryPoint = "CallWindowProc")]
        private static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
    }
}
Back to Blog

相关文章

阅读更多 »