首页 > 解决方案 > WPF 的行为类似于任务栏

问题描述

我在工作中需要类似 WPF 股票行情的应用程序。我想以此为起点:http ://www.jarloo.com/rumormill4

但它没有做的一件事是停靠在桌面窗口的顶部 - 并且 - 按下任何其他窗口,最大化或以其他方式。这个应用程序必须在屏幕顶部拥有一小块垂直空间,全宽。我搜索了 WPF 帖子,但找不到示例。我见过第三方解决方案,所以我知道这是可能的。Window.Topmost 几乎实现了这种行为,但只是覆盖/掩盖了它下面的任何东西。有什么建议么?下图演示了当前行为。WPF 窗口位于 VS 之上,这是个问题。

被工具栏遮挡的 Visual Studio 示例

标签: c#wpf

解决方案


将您的 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"
        WindowStartupLocation="Manual"
        Title="MainWindow" SizeToContent="Height" ResizeMode="NoResize" Topmost="True"
        WindowState="Maximized">
    <Grid>
        <TextBlock Text="Hi there!" FontSize="36"/>
    </Grid>
</Window>

我们设置SizeToContent = Height来实现高度自动效果。WindowState=Maximized实现窗口的全宽。

然后在代码隐藏中使用以下代码来避免用户移动窗口:

public partial class MainWindow
    {
        const int WM_SYSCOMMAND = 0x0112;
        const int SC_MOVE = 0xF010;

        public MainWindow()
        {
            InitializeComponent();

            SourceInitialized += OnSourceInitialized;
            Left = 0;
            Top = 0;
        }

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

        private static 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)
                    {
                        handled = true;
                    }
                    break;
                default:
                    break;
            }
            return IntPtr.Zero;
        }
    }

我必须说我从@Thomas Levesque的这个答案中得到了最后一部分。

结果是一个漂亮的顶部停靠窗口,全宽


推荐阅读