Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to make a Windowless WPF window draggable without getting InvalidOperationException

Tags:

wpf

windowless

I have a borderless WPF main window. I'm trying to make it so that the end user can drag the window.

I've added the following to the Window's constructor:

this.MouseLeftButtonDown += delegate { DragMove(); };

The problem is, I have a dialog box that opens up with two buttons. When I click one of these buttons, I get an InvalidOperationException unhandled with the message "Can only call DragMove when the primary mouse button is down."

This poses a few questions: Why would a mousedown event in a dialog have anything to do with this? How can I do this without this exception?

Thanks!

like image 883
rsteckly Avatar asked Jul 18 '10 02:07

rsteckly


1 Answers

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;
    }
}
like image 187
Tergiver Avatar answered Sep 20 '22 12:09

Tergiver