覆盖 WPF 中的最小化按钮

Override minimize button in WPF

在 WPF 中,当用户点击 Minimize 按钮时,我希望 window 状态仍然是正常状态。单击它时没有任何反应。但我不想禁用 Minimize 按钮,Minimize 按钮已启用且可见,点击时什么都不做。
我该怎么做?

您可以在 StateChanged 事件上实现。 在 XAML:

<Window x:Class="WpfApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    StateChanged="Window_StateChanged">

在代码中:

private void Window_StateChanged(object sender, EventArgs e)
{
    if (this.WindowState == WindowState.Minimized)
        this.WindowState = WindowState.Normal;
}

这是 this answer 的略微修改形式,由于不必要的调整大小,我将其视为不重复:

using System.Windows.Interop;

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        this.SourceInitialized += new EventHandler(OnSourceInitialized);
    }

    private void OnSourceInitialized(object sender, EventArgs e)
    {
        HwndSource source = (HwndSource)PresentationSource.FromVisual(this);
        source.AddHook(new HwndSourceHook(HandleMessages));
    }

    private IntPtr HandleMessages(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        // 0x0112 == WM_SYSCOMMAND, 'Window' command message.
        // 0xF020 == SC_MINIMIZE, command to minimize the window.
        if (msg == 0x0112 && ((int)wParam & 0xFFF0) == 0xF020)
        {
            // Cancel the minimize.
            handled = true;
        }

        return IntPtr.Zero;
    }
}