【问题标题】:wpf - allow window to move only up and downwpf - 只允许窗口上下移动
【发布时间】:2016-07-02 16:01:43
【问题描述】:

我想锁定它的左坐标。

这不能按我的意愿工作,因为存在故障 - 闪烁,因为窗口已移回 Left=0。我对诸如 LocationChanging 之类的东西更感兴趣,以防止它向左或向右移动。

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

【问题讨论】:

  • 我认为用户可能会发现窗口不能左右移动的事实有点不和谐。一个典型的例子是我有多个监视器并且想要将程序移动到不同的监视器。
  • 不,这是一个单一用途的应用程序,我需要这个功能。
  • 那么您可能必须编写自己的 MouseLeftButtonDown --> MouseMove 事件逻辑,在鼠标移动时更新窗口。这是SO question that is somewhat similar to get your started

标签: c# wpf visual-studio user-interface


【解决方案1】:

一种选择是捕获WM_MOVING 窗口消息并操作其lParam。由于 WM_MOVING 在 Window 移动之前出现,您可以根据需要调整下一个位置。

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;
    }
}

【讨论】:

  • 完美,这正是我想要的行为。
猜你喜欢
  • 2011-03-07
  • 1970-01-01
  • 2020-10-29
  • 2013-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
相关资源
最近更新 更多