WPF窗口最大化,具有固定/有限宽度

时间:2013-07-31 06:25:58

标签: wpf windows-8 maximize

在我的WPF窗口中,我已设置

Width="300" MinWidth="300" MaxWidth="300"

当我最大化此窗口时,它会停靠在左边的屏幕边框上,但是窗口的底部部分是Windows 8任务栏的UNDERNEATH。

我试过了

public MainWindow()
{
    ...
    this.MaxHeight = System.Windows.SystemParameters.WorkArea.Height;
}

,但这导致任务栏和我的应用之间有一些像素的可用空间。

我想

  • 有一个固定宽度的窗口
  • 将其停靠在最大化
  • 的右边框上
  • 没有覆盖/进入最大化状态的任务栏

1 个答案:

答案 0 :(得分:5)

不幸的是,使用MinWidth,MaxWidth和WindowState似乎无法实现您的三个要求。

但无论如何,它仍然可以实现类似的目标。您需要做的是模仿窗口的最大化状态。您需要将窗口移动到正确的位置,获得正确的高度,并使其不可移动。 前两部分很简单,最后一部分需要更高级的东西。

从您拥有的窗口开始,将Width,MaxWidth和MinWidth设置为300,并向StateChanged添加事件处理程序。

Width="300" MinWidth="300" MaxWidth="300" StateChanged="MainWindow_OnStateChanged"

事件处理程序和辅助方法:

private bool isMaximized;
private Rect normalBounds;
private void MainWindow_OnStateChanged(object sender, EventArgs e)
{
    if (WindowState == WindowState.Maximized && !isMaximized)
    {
        WindowState = WindowState.Normal;
        isMaximized = true;

        normalBounds = RestoreBounds;

        Height = SystemParameters.WorkArea.Height;
        MaxHeight = Height;
        MinHeight = Height;
        Top = 0;
        Left = SystemParameters.WorkArea.Right - Width;
        SetMovable(false);
    }
    else if(WindowState == WindowState.Maximized && isMaximized)
    {
        WindowState = WindowState.Normal;
        isMaximized = false;

        MaxHeight = Double.PositiveInfinity;
        MinHeight = 0;

        Top = normalBounds.Top;
        Left = normalBounds.Left;
        Width = normalBounds.Width;
        Height = normalBounds.Height;
        SetMovable(true);
    }
}

private void SetMovable(bool enable)
{
    HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);

    if(enable)
        source.RemoveHook(WndProc);
    else
        source.AddHook(WndProc);
}

private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    const int WM_SYSCOMMAND = 0x0112;
    const int SC_MOVE = 0xF010;

    switch (msg)
    {
        case WM_SYSCOMMAND:
            int command = wParam.ToInt32() & 0xfff0;
            if (command == SC_MOVE)
                handled = true;
            break;
    }

    return IntPtr.Zero;
}
相关问题