Enhanced: Drag and move WinForms (without having a titlebar)

Yesterday my colleague Alexander Jung read the articel I posted yesterday about dragging WinForms. And he showed me a solution for dragging windows that is much smarter than the solution I posted.

So I don’t want to keep back that solution.

Instead of implementing a drag routine for the WinForm, we can fool the system so that Windows thinks that the hole WinForm is a Caption (TitleBar). This can be done by intercepting the Windows Message WM_NCHITTEST and returning HTCAPTION if the user tries to drag the window.

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

/// Handling the window messages
protected override void WndProc(ref Message message)
    base.WndProc(ref message);

    if (message.Msg == WM_NCHITTEST && (int)message.Result == HTCLIENT)
        message.Result = (IntPtr)HTCAPTION;

The example solution can be downloaded using the following link.
Enhanced: Drag and move WinForms (without having a titlebar)

4 Responses to “Enhanced: Drag and move WinForms (without having a titlebar)”

  1. mrcouthy Says:

    How to do it, if we want certain control in the form to act as title bar.

  2. purple (@ChromiumRainbow) Says:

    thanks so much, everything else I was trying didn’t work. This was too easy :)

  3. Zaid Pirwani Says:

    I am using your code in my C# app. THANKS for the snippet.

    BUT, when the user double clicks on the form, the form gets maximized, just as it would if the user double clicks on the title bar.

    My form has BorderStyle set to None and I dont want the form to maximize when double clicked, can you tell me what to do.

    The code you have given, although works, but to me, it is all some magic code which I do not udnerstand – but it works so why not. :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 108 other followers

%d bloggers like this: