改变 Windows.MaxHeight 不改变高度

Changing Windows.MaxHeight don't change height

我正在开发一个应用程序 c# WPF。我有自己的标题栏,并且编写了函数关闭、最小化和最大化的代码。我在有 2 个屏幕的 PC 上工作,当我最大化 window 时遇到问题。在主屏幕上,如果我设置 WindowState = WindowState.Maximized 任务栏(来自 windows 7 的栏)被隐藏。我添加了一个函数来根据屏幕设置 MaxHeight,但是当我更改 MaxHeight 时,ActualHeight 不会改变。具体来说,当我最大化 window 时,window 会全屏显示。第二次最大化,高度正确,任务栏没有隐藏。

更改 MaxHeight 时如何刷新高度?

这是我的代码:

    protected override void OnStateChanged(EventArgs e)
    {
        base.OnStateChanged(e);
        if (WindowState == WindowState.Maximized)
        {
            var hwnd = new System.Windows.Interop.WindowInteropHelper(this).EnsureHandle();
            var currentMonitor = NativeMethods.MonitorFromWindow(hwnd, NativeMethods.MONITOR_DEFAULTTONEAREST);
            var primaryMonitor = NativeMethods.MonitorFromWindow(IntPtr.Zero, NativeMethods.MONITOR_DEFAULTTOPRIMERTY);
            var isInPrimary = currentMonitor == primaryMonitor;

            if (isInPrimary)
                this.MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight;
            else
                this.MaxHeight = Double.PositiveInfinity;
#if DEBUG
            var aH = this.ActualHeight;
            var h = this.Height;
            var mH = this.MaxHeight;
            if (aH != h || aH > mH)
            {
                System.Diagnostics.Debugger.Break();
                this.Height = this.MaxHeight;
            }               
#endif
        }
    }

我不是 C# 方面的专家,但在 Pascal/Delphi 中遇到了这个问题。 我必须像这样手动指定表单的大小:

procedure MinMax; 
begin
    if Form.WindowState=wsNormal then
    begin
        Form.WindowState:=wsMaximized;
        with Screen.WorkAreaRect do
          Form.SetBounds(Left, Top, Right - Left, Bottom - Top);
    end
    else
    begin
         Form1.WindowState:=wsNormal;
    end;
end;

Screen.WorkAreaRect 给出了没有任务栏区域的实际矩形,可以放置 top/left/bottom/right。

希望对您有所帮助。