[C#]wpf-允许窗口只有向上和向下移动

标签: Visual-Studio WPF C#
发布时间: 2017/2/24 1:02:22
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我想要锁定其左边缘的坐标。

这并不工作,我想因为有故障-忽隐忽现,因为窗口搬回左 = 0。像 LocationChanging,以防止它过移动左边或右边的事情更感兴趣 !

private void Window_LocationChanged(object sender, EventArgs e)
        {
            if (Left != 0) Left = 0;
        }

解决方法 1:

一个选项是赶上WM_MOVING窗口消息并操纵其 lParam。因为之前窗口移动来 WM_MOVING,您可以调整的下一个位置,如你所愿。

using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;

public partial class MainWindow : Window
{
    private const int WM_MOVING = 0x0216;

    [StructLayout(LayoutKind.Sequential)]
    private struct RECT
    {
        public int left;
        public int top;
        public int right;
        public int bottom;
    }

    private int _left;
    private int _width;

    public MainWindow()
    {
        InitializeComponent();
        this.Loaded += OnLoaded;
    }

    private void OnLoaded(object sender, RoutedEventArgs e)
    {
        _left = (int)this.Left;
        _width = (int)this.Width;

        var handle = new WindowInteropHelper(this).Handle;
        var source = HwndSource.FromHwnd(handle);
        source.AddHook(new HwndSourceHook(WndProc));
    }

    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        if (msg == WM_MOVING)
        {
            var position = Marshal.PtrToStructure<RECT>(lParam);
            position.left = _left;
            position.right = position.left + _width;
            Marshal.StructureToPtr(position, lParam, true);
        }
        return IntPtr.Zero;
    }
}
赞助商