禁用WPF窗口的最大化按钮,保持缩放功能完好缩放、完好、按钮、窗口

2023-09-04 02:35:25 作者:许是一心人复唸

所以,WPF窗口只有四张ResizeMode选择:NoResize,CanMinimize,CanResize和CanResizeWithGrip。不幸的是,还启用调整的选项,最大化的窗口,那些不都是对我没用。 是否有一个选项来禁用最大化按钮,同时保持调整大小功能?

So WPF windows only have four ResizeMode options: NoResize, CanMinimize, CanResize and CanResizeWithGrip. Unfortunately, the options that enable resizing also enable maximizing the window, and those that don't are useless to me. Is there an option to disable the maximize button while keeping the resize feature?

我preFER的解决方案,不涉及WinAPI的东西。

I'd prefer solutions that don't involve WinAPI stuff.

推荐答案

WPF不必单独禁用最大化按钮,你可以做的WinForms本机的能力。你需要求助于WinAPI的电话。这不是可怕的:

WPF does not have the native capability to disable the Maximize button alone, as you can do with WinForms. You will need to resort to a WinAPI call. It's not scary:

[DllImport("user32.dll")]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

private const int GWL_STYLE = -16;
private const int WS_MAXIMIZEBOX = 0x10000;

private void Window_SourceInitialized(object sender, EventArgs e)
{
    var hwnd = new WindowInteropHelper((Window)sender).Handle;
    var value = GetWindowLong(hwnd, GWL_STYLE);
    SetWindowLong(hwnd, GWL_STYLE, (int)(value & ~WS_MAXIMIZEBOX));
}