在某个边界WPF内创建一个可拖动的窗口

时间:2011-02-07 20:30:43

标签: wpf wpf-controls

我有一个wpf子窗口,我允许使用DragMove()方法进行拖动。 但是,我需要允许仅在其父窗口控件的范围内拖动窗口。

有人可以建议一种方法来实现这一目标吗? 谢谢!

1 个答案:

答案 0 :(得分:5)

有两种方法可以做到这一点。

使用LocationEnded

如果您处理此事件,您可以将Top或Left更改为在所有者窗口的范围内。 例如

    private void Window_LocationChanged(object sender, EventArgs e)
    {

        if (this.Left < this.Owner.Left)
            this.Left = this.Owner.Left;

        //... also right top and bottom
        //
    }

这很容易编写,但它违反了Principle of least astonishment,因为它没有绑定拖动窗口,它只是在用户放开鼠标按钮时将窗口推回原位。

使用AddHook

正如Pieter在an answer中指出的类似问题,您可以与Windows消息传递互操作并阻止拖动窗口。这对绑定实际拖动窗口具有很好的影响。

以下是我为AddHook方法编写的一些示例代码

从加载的窗口开始添加钩子

  //In Window_Loaded the handle is there (earlier its null) so this is good time to add the handler 

   private void Window_Loaded(object sender, RoutedEventArgs e)
    {

        WindowInteropHelper helper = new WindowInteropHelper(this);
        HwndSource.FromHwnd(helper.Handle).AddHook(HwndSourceHookHandler);
    } 

在您的处理程序中,您只想查找移动或移动消息。然后你将读取lParam矩形并查看它是否超出范围。如果是,你需要更改lParam矩形的值并将其重新编号。请注意,为了简洁起见,我只做了左边。你仍然需要写出正确的,顶部和底部的案例。

 private IntPtr HwndSourceHookHandler(IntPtr hwnd, int msg, IntPtr wParam,
    IntPtr lParam, ref bool handled)
        {


const int WM_MOVING = 0x0216;
        const int WM_MOVE = 0x0003;


        switch (msg)
        {
            case WM_MOVING:
                {


                   //read the lparm ino a struct

                    MoveRectangle rectangle = (MoveRectangle)Marshal.PtrToStructure(
                      lParam, typeof(MoveRectangle));


                     //

                    if (rectangle.Left < this.Owner.Left)
                    {
                        rectangle.Left = (int)this.Owner.Left;
                        rectangle.Right = rectangle.Left + (int)this.Width;
                    }



                    Marshal.StructureToPtr(rectangle, lParam, true);

                    break;
                }
            case WM_MOVE:
                {
                   //Do the same thing as WM_MOVING You should probably enacapsulate that stuff so don'tn just copy and paste

                    break;
                }


        }

        return IntPtr.Zero;

    }

lParam的结构

  [StructLayout(LayoutKind.Sequential)]
    //Struct for Marshalling the lParam
    public struct MoveRectangle
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;

    }

最后要注意的是,如果允许子窗口大于父窗口,则需要弄清楚该怎么做。

相关问题