Way to make a Windowless WPF window draggable without getting InvalidOperationException

与世无争的帅哥 提交于 2019-11-30 09:16:51

The 'correct' way to make a borderless window movable is to return HTCAPTION in the WM_NCHITTEST message. The following code shows how to do that. Note that you will want to return HTCLIENT if the cursor is over certain of your Window's visual elements, so this code is just to get you started.

http://msdn.microsoft.com/en-us/library/ms645618(VS.85).aspx

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    protected override void OnSourceInitialized(EventArgs e)
    {
        HwndSource hwndSource = (HwndSource)HwndSource.FromVisual(this);
        hwndSource.AddHook(WndProcHook); 
        base.OnSourceInitialized(e);
    }

    private static IntPtr WndProcHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handeled)
    {
        if (msg == 0x0084) // WM_NCHITTEST
        {
            handeled = true;
            return (IntPtr)2; // HTCAPTION
        }
        return IntPtr.Zero;
    }
}
Web Developer

Set the MouseDown atrribute of the window or any other control you want to use:

<TextBlock Grid.Column="0" HorizontalAlignment="Stretch"  MouseLeftButtonDown="TextBlock_MouseLeftButtonDown" >Handy Dandy</TextBlock>

And implement it in the code behind like this:

private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
     this.DragMove();
}

From: http://www2.suddenelfilio.net/2007/01/19/wpf-draggable-windowless-windows/

There is a Microsoft project that handles all the "windowless" style and much more, and it is opensource, you might want to take a look at http://code.msdn.microsoft.com/WPFShell. I am using on a commercial financial application, and hasn't run into any issues on any version of windows yet.

you can override the original method:

 public new void DragMove()
     {
        if (this.WindowState == WindowState.Normal)
        {
            SendMessage(hs.Handle, WM_SYSCOMMAND, (IntPtr)0xf012, IntPtr.Zero);
            SendMessage(hs.Handle, WM_LBUTTONUP, IntPtr.Zero, IntPtr.Zero);
        }
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!