[.net] moving a form by dragging in the client area

This topic is 5169 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

how would one go about moving a form by dragging the mouse in the client area of said form in c#? what i am looking for is the same behavior as when the user clicks and drags the form around by the caption bar. i've done this in other langages, but i'm still learning the .NET way. thanks in advance! EDIT: i should add that i have tried to add the difference between the current and previous mouse position, but i can see tearing artifacts when it moves, and it doesn't "keep up" with the mouse. [Edited by - krez on August 26, 2005 7:15:26 AM]

Share on other sites
http://www.yoraispage.com/articles/20040903.asp

The trick is quite simple, handle the WM_NCHITTEST message (look it up in MSDN, basically Windows uses it to know in which area of the control you clicked) to make Windows believe that the client region is the caption bar region.

You have to use interop for that, since .NET (at least 1.1) doesn't expose messages relative to the non-client (NC) area.

Hope it helps,
jods

Share on other sites
Instead of tracking the difference between current and previous positions, just determine an offset to apply (during a MouseMove event) at the MouseDown event. The following works fine (for me at least [smile])
    private int offsetx=-1, offsety=-1;    private void MainForm_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)    {        if((e.Button&System.Windows.Forms.MouseButtons.Left)!=0)        {           offsetx = Location.X-MousePosition.X;           offsety = Location.Y-MousePosition.Y;        }    }    private void MainForm_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)    {        if((e.Button&System.Windows.Forms.MouseButtons.Left)!=0)        Location = new Point(offsetx+MousePosition.X, offsety+MousePosition.Y);    }

This however won't capture any drags from within children. If this is necessary you may need to capture the non-client area Win32 messages, but keep in mind this could cause things like buttons not being clickable.

Share on other sites
bah, it was a typo that i overlooked repeatedly.

thanks anyway though!

• Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 11
• 15
• 21
• 26
• 11