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
.
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();
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!