在wpf中移动一个没有边框的窗口

14

在我的C# WinForms应用程序中,我有一个主窗口,其中默认控件被隐藏。

因此,为了让它可以移动,我在主窗口中添加了以下内容:

private const int WM_NCHITTEST = 0x84;
private const int HTCLIENT = 0x1;
private const int HTCAPTION = 0x2;
private const int WM_NCLBUTTONDBLCLK = 0x00A3;

protected override void WndProc(ref Message message)
{
    if (message.Msg == WM_NCLBUTTONDBLCLK)
    {
        message.Result = IntPtr.Zero;
        return;
    }

    base.WndProc(ref message);

    //Allow window to move
    if (message.Msg == WM_NCHITTEST && (int)message.Result == HTCLIENT)
        message.Result = (IntPtr)HTCAPTION;
}

我有一个WPF应用程序,在其中我还隐藏了默认控件,我想做同样的事情。我看到主窗口派生自“Window”,因此上面的代码不起作用。在WPF中我该如何做到这一点?

3个回答

41
要实现这个功能,您需要将事件处理程序附加到窗口的MouseDown事件,检查左鼠标按钮是否按下,并在窗口上调用DragMove方法。
以下是具有此功能的窗口示例:
public partial class MyWindow : Window
{
    public MyWindow()
    {
        InitializeComponent();
        MouseDown += Window_MouseDown;
    }

    private void Window_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (e.ChangedButton == MouseButton.Left)
            DragMove();
    }
}

使用这个会导致我的标签不再被触发,这些标签是通过 MouseUp 或 PreviewMouseUp 调用的。 - The Muffin Man
@TheMuffinMan 如果可以的话,我建议你尝试使用 MouseUp 来处理标签,或者使用样式为标签的按钮并使用 click 事件。 - user1618236
1
可以被压缩为 protected override void OnMouseDown(MouseButtonEventArgs e){if (e.ChangedButton == MouseButton.Left) DragMove();} - Gray Programmerz

2
这很简单,就在这里:

只需按照以下步骤:

private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
{
    DragMove();
}

0
首先,您需要确保用户想要拖动窗口。因此,鼠标的左键应该是按下的,并且至少移动了一些像素。创建一个点属性来存储光标的准确位置,并向窗口本身添加两个事件:PreviewMouseLeftButtonDown和MouseMove。请查看下面的代码。
private void Window_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
  Position = e.GetPosition(null);
}



private void Window_MouseMove(object sender, MouseEventArgs e)
    {

        Point mousePos = e.GetPosition(null);
        Vector diff = Position - mousePos;

        if (e.LeftButton == MouseButtonState.Pressed &&
            (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
            Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))
        {
            DragMove();
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接