Click here to Skip to main content
15,891,859 members
Articles / Desktop Programming / Windows Forms

How to Move a Windows Form By Dragging

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
10 Jan 2014CPOL 10.4K   1  
How to move a Windows forms by dragging

Today, I was working on a desktop application where I was required to drag a form by Mouse left click as we do in normal drag and drop operations. The only difference in this scenario was that I needed to drag the entire form and the form was not supposed to be dropped anywhere else.

I found a very easy way to implement this. This can be achieved using 2 ways – Handling Mouse Events of the form or by using Interop assemblies. Using Mouse Events to handle the drag operation is a bit messy and does not work to 100% perfection. In this post, we will see how we can add this feature to our Windows Form. To do this, we will follow the below steps. Let’s assume the form name is Form1.

C#
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;

[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
C#
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
            }
}
  • Set the FormBorderStyle of the form to None.
  • Include the Assembly System.Runtime.InteropServices on Form1.cs page.
  • Declare the below variables.
  • Handle the MouseDown event of the form.
  • Write the below code in the Event Handler.

You’re done! Run the code and you will able to drag a form easily with your mouse left click. Hope you like this post! Cheers!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Rebin Infotech
India India
A passionate developer with over 10 years of experience and building my software company code by code. Experience withMS Technologies like .Net | MVC | Xamarin | Sharepoint | MS Project Server and PhP along with open source CMS Systems like Wordpress/DotNetNuke etc.

Love to debug problems and solve them. I love writing articles on my website in my spare time. Please visit my Website for more details and subscribe to get technology related tips/tricks. #SOreadytohelp

Comments and Discussions

 
-- There are no messages in this forum --