I have a windows form without title bar. I want to drag it by mouse. After searching on internet, I found this code for moving form:
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case 0x84:
base.WndProc(ref m);
if ((int)m.Result == 0x1)
m.Result = (IntPtr)0x2;
return;
}
base.WndProc(ref m);
}
But it has a problem: It operates only on form regions which are not covered by any control. For example if I use label or group box, I can't move form by clicking on them.
How can I solve this problem?
One way is to implement IMessageFilter
like this.
public class MyForm : Form, IMessageFilter
{
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
public const int WM_LBUTTONDOWN = 0x0201;
[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 HashSet<Control> controlsToMove = new HashSet<Control>();
public MyForm()
{
Application.AddMessageFilter(this);
controlsToMove.Add(this);
controlsToMove.Add(this.myLabel);//Add whatever controls here you want to move the form when it is clicked and dragged
}
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == WM_LBUTTONDOWN &&
controlsToMove.Contains(Control.FromHandle(m.HWnd)))
{
ReleaseCapture();
SendMessage(this.Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
return true;
}
return false;
}
}
This is basically what you are looking to do:
Make a borderless form movable?
You might be able to add the same code to the mouse down event of other controls on your form to accomplish the same thing.
Make a borderless form movable?
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With