WPF的行为就像任务栏

时间:2018-08-31 13:56:01

标签: c# wpf

我有一个工作需要WPF类似股票行情自动收录器的应用程序。 我当时想以此作为起点:http://www.jarloo.com/rumormill4

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

Example of Visual studio obscured by toolbar

1 个答案:

答案 0 :(得分:0)

将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的this answer的最后一部分。

结果是一个漂亮的顶部停靠的窗口,具有完整的宽度