gpt4 book ai didi

WPF 窗口不应移动、调整大小并且应仅包含最小化、关闭按钮

转载 作者:行者123 更新时间:2023-12-01 11:42:22 36 4
gpt4 key购买 nike

我正在尝试设置 WPF 窗口。

  • 窗口应始终处于最大化状态
  • 窗口不能移动或调整大小
  • 它应该包含最小化和关闭按钮但不包含最大化按钮

我尝试了以下 XAML 代码

<Window x:Class="BasicImagingStandAlone"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:myUserControl="clr-namespace:WpfUserControlLibrary;assembly=WpfUserControlLibrary"
Title="BasicImagingStandAlone" Icon="desktopicon.png" MinWidth="600" MinHeight="350" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Height="600" Width="1200" WindowState="Maximized" WindowStyle="None" ResizeMode="NoResize">
</Window>

xaml 的输出是一个处于最大化状态的窗口,不能移动或调整大小,但没有按钮。 我怎样才能一次达到所有要求?

最佳答案

这个问题已经有将近 2 年的历史了,但以防万一有人有相同的要求。

在 WPF 中,您可以使用帮助器类 HwndSource 挂接到窗口过程,然后可以使用它来处理窗口消息。

因此在 XAML 中设置 WindowState="Maximized"ResizeMode="CanMinimize",并覆盖 SourceInitialized:

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
WindowState="Maximized" ResizeMode="CanMinimize" SourceInitialized="MainWindow_SourceInitialized">

以及代码隐藏(来自 an answer in this SO question 的修改):

private void MainWindow_SourceInitialized(object sender, EventArgs e)
{
WindowInteropHelper helper = new WindowInteropHelper(this);
HwndSource source = HwndSource.FromHwnd(helper.Handle);
source.AddHook(WndProc);
}

const int WM_SYSCOMMAND = 0x0112;
const int SC_MOVE = 0xF010;
const int SC_RESTORE = 0xF120;

private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
switch (msg)
{
case WM_SYSCOMMAND:
int command = wParam.ToInt32() & 0xfff0;
if (command == SC_MOVE)
{
// prevent user from moving the window
handled = true;
}
else if (command == SC_RESTORE && WindowState == WindowState.Maximized)
{
// prevent user from restoring the window while it is maximized
// (but allow restoring when it is minimized)
handled = true;
}
break;
default:
break;
}
return IntPtr.Zero;
}

不要忘记包括:using System.Windows.Interop;

这应该满足 OP 的 3 个要求:

  • 处于最大化状态的窗口
  • 窗口不能移动或调整大小(包括通过拖动或双击标题栏)
  • 窗口的最小化和关闭按钮已启用,但恢复/最大化按钮已禁用

关于WPF 窗口不应移动、调整大小并且应仅包含最小化、关闭按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18525463/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com